diff --git a/.eslintrc.js b/.eslintrc.js
index 6194ccd39d3f..f852c970f85c 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -14,6 +14,11 @@ const restrictedImportPaths = [
importNames: ['TouchableOpacity', 'TouchableWithoutFeedback', 'TouchableNativeFeedback', 'TouchableHighlight'],
message: "Please use 'PressableWithFeedback' and/or 'PressableWithoutFeedback' from 'src/components/Pressable' instead.",
},
+ {
+ name: 'awesome-phonenumber',
+ importNames: ['parsePhoneNumber'],
+ message: "Please use '@libs/PhoneNumber' instead.",
+ },
{
name: 'react-native-safe-area-context',
importNames: ['useSafeAreaInsets', 'SafeAreaConsumer', 'SafeAreaInsetsContext'],
diff --git a/.github/actions/javascript/bumpVersion/index.js b/.github/actions/javascript/bumpVersion/index.js
index 31a4c6d4246a..1132c137061e 100644
--- a/.github/actions/javascript/bumpVersion/index.js
+++ b/.github/actions/javascript/bumpVersion/index.js
@@ -19,6 +19,7 @@ const getBuildVersion = __nccwpck_require__(4016);
const BUILD_GRADLE_PATH = process.env.NODE_ENV === 'test' ? path.resolve(__dirname, '../../android/app/build.gradle') : './android/app/build.gradle';
const PLIST_PATH = './ios/NewExpensify/Info.plist';
const PLIST_PATH_TEST = './ios/NewExpensifyTests/Info.plist';
+const PLIST_PATH_NSE = './ios/NotificationServiceExtension/Info.plist';
exports.BUILD_GRADLE_PATH = BUILD_GRADLE_PATH;
exports.PLIST_PATH = PLIST_PATH;
@@ -90,8 +91,10 @@ exports.updateiOSVersion = function updateiOSVersion(version) {
// Update Plists
execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${shortVersion}" ${PLIST_PATH}`);
execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${shortVersion}" ${PLIST_PATH_TEST}`);
+ execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${shortVersion}" ${PLIST_PATH_NSE}`);
execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleVersion ${cfVersion}" ${PLIST_PATH}`);
execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleVersion ${cfVersion}" ${PLIST_PATH_TEST}`);
+ execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleVersion ${cfVersion}" ${PLIST_PATH_NSE}`);
// Return the cfVersion so we can set the NEW_IOS_VERSION in ios.yml
return cfVersion;
diff --git a/.github/libs/nativeVersionUpdater.js b/.github/libs/nativeVersionUpdater.js
index 07d36d823c78..ab129f4eb04a 100644
--- a/.github/libs/nativeVersionUpdater.js
+++ b/.github/libs/nativeVersionUpdater.js
@@ -10,6 +10,7 @@ const getBuildVersion = require('semver/functions/prerelease');
const BUILD_GRADLE_PATH = process.env.NODE_ENV === 'test' ? path.resolve(__dirname, '../../android/app/build.gradle') : './android/app/build.gradle';
const PLIST_PATH = './ios/NewExpensify/Info.plist';
const PLIST_PATH_TEST = './ios/NewExpensifyTests/Info.plist';
+const PLIST_PATH_NSE = './ios/NotificationServiceExtension/Info.plist';
exports.BUILD_GRADLE_PATH = BUILD_GRADLE_PATH;
exports.PLIST_PATH = PLIST_PATH;
@@ -81,8 +82,10 @@ exports.updateiOSVersion = function updateiOSVersion(version) {
// Update Plists
execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${shortVersion}" ${PLIST_PATH}`);
execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${shortVersion}" ${PLIST_PATH_TEST}`);
+ execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${shortVersion}" ${PLIST_PATH_NSE}`);
execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleVersion ${cfVersion}" ${PLIST_PATH}`);
execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleVersion ${cfVersion}" ${PLIST_PATH_TEST}`);
+ execSync(`/usr/libexec/PlistBuddy -c "Set :CFBundleVersion ${cfVersion}" ${PLIST_PATH_NSE}`);
// Return the cfVersion so we can set the NEW_IOS_VERSION in ios.yml
return cfVersion;
diff --git a/.github/scripts/createDocsRoutes.js b/.github/scripts/createDocsRoutes.js
index 6604a9d207fa..7c9ac532850d 100644
--- a/.github/scripts/createDocsRoutes.js
+++ b/.github/scripts/createDocsRoutes.js
@@ -16,7 +16,12 @@ const platformNames = {
* @returns {String}
*/
function toTitleCase(str) {
- return str.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1));
+ return _.map(str.split(' '), (word, i) => {
+ if (i !== 0 && (word.toLowerCase() === 'a' || word.toLowerCase() === 'the' || word.toLowerCase() === 'and')) {
+ return word.toLowerCase();
+ }
+ return word.charAt(0).toUpperCase() + word.substring(1);
+ }).join(' ');
}
/**
diff --git a/.github/workflows/reassurePerformanceTests.yml b/.github/workflows/reassurePerformanceTests.yml
index 116f178868c1..64b4536d9241 100644
--- a/.github/workflows/reassurePerformanceTests.yml
+++ b/.github/workflows/reassurePerformanceTests.yml
@@ -42,4 +42,3 @@ jobs:
with:
DURATION_DEVIATION_PERCENTAGE: 20
COUNT_DEVIATION: 0
-
diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml
index 0951b194430b..156b9764bcca 100644
--- a/.github/workflows/typecheck.yml
+++ b/.github/workflows/typecheck.yml
@@ -30,9 +30,9 @@ jobs:
# - git diff is used to see the files that were added on this branch
# - gh pr view is used to list files touched by this PR. Git diff may give false positives if the branch isn't up-to-date with main
# - wc counts the words in the result of the intersection
- count_new_js=$(comm -1 -2 <(git diff --name-only --diff-filter=A origin/main HEAD -- 'src/libs/*.js' 'src/hooks/*.js' 'src/styles/*.js' 'src/languages/*.js') <(gh pr view ${{ github.event.pull_request.number }} --json files | jq -r '.files | map(.path) | .[]') | wc -l)
+ count_new_js=$(comm -1 -2 <(git diff --name-only --diff-filter=A origin/main HEAD -- 'src/*.js') <(gh pr view ${{ github.event.pull_request.number }} --json files | jq -r '.files | map(.path) | .[]') | wc -l)
if [ "$count_new_js" -gt "0" ]; then
- echo "ERROR: Found new JavaScript files in the /src/libs, /src/hooks, /src/styles, or /src/languages directories; use TypeScript instead."
+ echo "ERROR: Found new JavaScript files in the project; use TypeScript instead."
exit 1
fi
env:
diff --git a/android/app/build.gradle b/android/app/build.gradle
index 63aa4215cd90..fea9cdad0a90 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -96,8 +96,8 @@ android {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
multiDexEnabled rootProject.ext.multiDexEnabled
- versionCode 1001042203
- versionName "1.4.22-3"
+ versionCode 1001042404
+ versionName "1.4.24-4"
}
flavorDimensions "default"
diff --git a/contributingGuides/TS_STYLE.md b/contributingGuides/TS_STYLE.md
index b60c28147a45..b96f24a7c949 100644
--- a/contributingGuides/TS_STYLE.md
+++ b/contributingGuides/TS_STYLE.md
@@ -671,7 +671,7 @@ declare module "external-library-name" {
> This section contains instructions that are applicable during the migration.
-- 🚨 DO NOT write new code in TypeScript yet. The only time you write TypeScript code is when the file you're editing has already been migrated to TypeScript by the migration team, or when you need to add new files under `src/libs`, `src/hooks`, `src/styles`, and `src/languages` directories. This guideline will be updated once it's time for new code to be written in TypeScript. If you're doing a major overhaul or refactoring of particular features or utilities of App and you believe it might be beneficial to migrate relevant code to TypeScript as part of the refactoring, please ask in the #expensify-open-source channel about it (and prefix your message with `TS ATTENTION:`).
+- 🚨 Any new files under `src/` directory MUST be created in TypeScript now! New files in other directories (e.g. `tests/`, `desktop/`) can be created in TypeScript, if desired.
- If you're migrating a module that doesn't have a default implementation (i.e. `index.ts`, e.g. `getPlatform`), convert `index.website.js` to `index.ts`. Without `index.ts`, TypeScript cannot get type information where the module is imported.
diff --git a/desktop/package-lock.json b/desktop/package-lock.json
index 6f62e6a5ba00..268c706bedef 100644
--- a/desktop/package-lock.json
+++ b/desktop/package-lock.json
@@ -10,7 +10,7 @@
"electron-context-menu": "^2.3.0",
"electron-log": "^4.4.8",
"electron-serve": "^1.2.0",
- "electron-updater": "^6.1.6",
+ "electron-updater": "^6.1.7",
"node-machine-id": "^1.1.12"
}
},
@@ -50,9 +50,9 @@
}
},
"node_modules/builder-util-runtime": {
- "version": "9.2.2",
- "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.2.2.tgz",
- "integrity": "sha512-Or2/ycVYRGQ876hKMfiz2Ghgzh3WllgPW75jqt1Ta2a5wprpnziFrHpQ9eUq6/ScsVXMnG4PmQqlMsE9NFg8DQ==",
+ "version": "9.2.3",
+ "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.2.3.tgz",
+ "integrity": "sha512-FGhkqXdFFZ5dNC4C+yuQB9ak311rpGAw+/ASz8ZdxwODCv1GGMWgLDeofRkdi0F3VCHQEWy/aXcJQozx2nOPiw==",
"dependencies": {
"debug": "^4.3.4",
"sax": "^1.2.4"
@@ -156,11 +156,11 @@
}
},
"node_modules/electron-updater": {
- "version": "6.1.6",
- "resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.1.6.tgz",
- "integrity": "sha512-G2bO72i7kv+bVdBAjq6lQn8zkZ3wMRRjxBD4TGBjB77UiuMDUBeP45YAs4y08udPzttGW2qzpnbOUJY5RYWZfw==",
+ "version": "6.1.7",
+ "resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.1.7.tgz",
+ "integrity": "sha512-SNOhYizjkm4ET+Y8ilJyUzcVsFJDtINzVN1TyHnZeMidZEG3YoBebMyXc/J6WSiXdUaOjC7ngekN6rNp6ardHA==",
"dependencies": {
- "builder-util-runtime": "9.2.2",
+ "builder-util-runtime": "9.2.3",
"fs-extra": "^10.1.0",
"js-yaml": "^4.1.0",
"lazy-val": "^1.0.5",
@@ -467,9 +467,9 @@
"integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ=="
},
"builder-util-runtime": {
- "version": "9.2.2",
- "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.2.2.tgz",
- "integrity": "sha512-Or2/ycVYRGQ876hKMfiz2Ghgzh3WllgPW75jqt1Ta2a5wprpnziFrHpQ9eUq6/ScsVXMnG4PmQqlMsE9NFg8DQ==",
+ "version": "9.2.3",
+ "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.2.3.tgz",
+ "integrity": "sha512-FGhkqXdFFZ5dNC4C+yuQB9ak311rpGAw+/ASz8ZdxwODCv1GGMWgLDeofRkdi0F3VCHQEWy/aXcJQozx2nOPiw==",
"requires": {
"debug": "^4.3.4",
"sax": "^1.2.4"
@@ -541,11 +541,11 @@
"integrity": "sha512-zJG3wisMrDn2G/gnjrhyB074COvly1FnS0U7Edm8bfXLB8MYX7UtwR9/y2LkFreYjzQHm9nEbAfgCmF+9M9LHQ=="
},
"electron-updater": {
- "version": "6.1.6",
- "resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.1.6.tgz",
- "integrity": "sha512-G2bO72i7kv+bVdBAjq6lQn8zkZ3wMRRjxBD4TGBjB77UiuMDUBeP45YAs4y08udPzttGW2qzpnbOUJY5RYWZfw==",
+ "version": "6.1.7",
+ "resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.1.7.tgz",
+ "integrity": "sha512-SNOhYizjkm4ET+Y8ilJyUzcVsFJDtINzVN1TyHnZeMidZEG3YoBebMyXc/J6WSiXdUaOjC7ngekN6rNp6ardHA==",
"requires": {
- "builder-util-runtime": "9.2.2",
+ "builder-util-runtime": "9.2.3",
"fs-extra": "^10.1.0",
"js-yaml": "^4.1.0",
"lazy-val": "^1.0.5",
diff --git a/desktop/package.json b/desktop/package.json
index 7545e4b57dba..563a45851eb2 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -7,7 +7,7 @@
"electron-context-menu": "^2.3.0",
"electron-log": "^4.4.8",
"electron-serve": "^1.2.0",
- "electron-updater": "^6.1.6",
+ "electron-updater": "^6.1.7",
"node-machine-id": "^1.1.12"
},
"author": "Expensify, Inc.",
diff --git a/docs/articles/expensify-classic/account-settings/Account-Details.md b/docs/articles/expensify-classic/account-settings/Account-Details.md
index bc4b94bf8a51..535e74eeb701 100644
--- a/docs/articles/expensify-classic/account-settings/Account-Details.md
+++ b/docs/articles/expensify-classic/account-settings/Account-Details.md
@@ -60,10 +60,12 @@ Is your Secondary Login (personal email) invalidated in your company account? If
4. Head to your personal email account and follow the prompts
5. You'll receive a link in the email to click that will unlink the two accounts
-# FAQ
+{% include faq-begin.md %}
## The profile picture on my account updated automatically. Why did this happen?
Our focus is always on making your experience user-friendly and saving you valuable time. One of the ways we achieve this is by utilizing a public API to retrieve public data linked to your email address.
This tool searches for public accounts or profiles associated with your email address, such as on LinkedIn. When it identifies one, it pulls in the uploaded profile picture and name to Expensify.
While this automated process is generally accurate, there may be instances where it's not entirely correct. If this happens, we apologize for any inconvenience caused. The good news is that rectifying such situations is a straightforward process. You can quickly update your information manually by following the directions provided above, ensuring your data is accurate and up to date in no time.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/account-settings/Close-Account.md b/docs/articles/expensify-classic/account-settings/Close-Account.md
index c25c22de9704..9b1e886fc94a 100644
--- a/docs/articles/expensify-classic/account-settings/Close-Account.md
+++ b/docs/articles/expensify-classic/account-settings/Close-Account.md
@@ -114,10 +114,12 @@ Here's how to do it:
By following these steps, you can easily verify your email or phone number and close an unwanted Expensify account.
-# FAQ
+{% include faq-begin.md %}
## What should I do if I'm not directed to my account when clicking the validate option from my phone or email?
It's possible your browser has blocked this, either because of some existing cache or extension. In this case, you should follow the Reset Password flow to reset the password and manually gain access with the new password, along with your email address.
## Why don't I see the Close Account option?
It's possible your account is on a managed company domain. In this case, only the admins from that company can close it.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/account-settings/Copilot.md b/docs/articles/expensify-classic/account-settings/Copilot.md
index 4fac402b7ced..31bc0eff60e6 100644
--- a/docs/articles/expensify-classic/account-settings/Copilot.md
+++ b/docs/articles/expensify-classic/account-settings/Copilot.md
@@ -59,7 +59,7 @@ To ensure a receipt is routed to the Expensify account in which you are a copilo
3. Send
-# FAQ
+{% include faq-begin.md %}
## Can a Copilot's Secondary Login be used to forward receipts?
Yes! A Copilot can use any of the email addresses tied to their account to forward receipts into the account of the person they're assisting.
@@ -67,3 +67,5 @@ Yes! A Copilot can use any of the email addresses tied to their account to forwa
No, only the original account holder can add another Copilot to the account.
## Is there a restriction on the number of Copilots I can have or the number of users for whom I can act as a Copilot?
There is no limit! You can have as many Copilots as you like, and you can be a Copilot for as many users as you need.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/account-settings/Merge-Accounts.md b/docs/articles/expensify-classic/account-settings/Merge-Accounts.md
index abb218c74118..34bf422aa983 100644
--- a/docs/articles/expensify-classic/account-settings/Merge-Accounts.md
+++ b/docs/articles/expensify-classic/account-settings/Merge-Accounts.md
@@ -19,7 +19,7 @@ Merging two accounts together is fairly straightforward. Let’s go over how to
8. Paste the code into the required field
If you have any questions about this process, feel free to reach out to Concierge for some assistance!
-# FAQ
+{% include faq-begin.md %}
## Can you merge accounts from the mobile app?
No, accounts can only be merged from the full website at expensify.com.
## Can I administratively merge two accounts together?
@@ -34,3 +34,5 @@ Yes! Please see below:
- If you have two accounts with two different verified domains, you cannot merge them together.
## What happens to my “personal” Individual workspace when merging accounts?
The old “personal” Individual workspace is deleted. If you plan to submit reports under a different workspace in the future, ensure that any reports on the Individual workspace in the old account are marked as Open before merging the accounts. You can typically do this by selecting “Undo Submit” on any submitted reports.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/International-Reimbursements.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/International-Reimbursements.md
index 7313c73ac6e6..5a5827149a4f 100644
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/International-Reimbursements.md
+++ b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/International-Reimbursements.md
@@ -75,7 +75,7 @@ Examples of additional requested information:
- An authorization letter
- An independently certified documentation such as shareholder agreement from a lawyer, notary, or public accountant if an individual owns more than 25% of the company
-# FAQ
+{% include faq-begin.md %}
## How many people can send reimbursements internationally?
@@ -103,3 +103,4 @@ This is the person who will process international reimbursements. The authorized
You can leave this form section blank since the “User” is Expensify.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/Personal-Credit-Cards.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/Personal-Credit-Cards.md
index c41178b4aa7f..05149ebf868e 100644
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/Personal-Credit-Cards.md
+++ b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/Personal-Credit-Cards.md
@@ -59,7 +59,7 @@ Expenses can be imported as either reimbursable or non-reimbursable. Select the
*Remove a card*: If you need to remove a card, you can select the red trash can icon. Please remember this will remove all unreported and un-submitted transactions from your account that are tied to this card, so be careful!
-# FAQ
+{% include faq-begin.md %}
*Is the bank/credit card import option right for me?*
If you incur expenses using your personal or business card and need to get them accounted for in your company’s accounting, then you might want to import your bank/credit card. Please note, if you have a company-assigned corporate card, check with your company's Expensify admin on how to handle these cards. Often, admins will take care of card assignments, and you won't need to import them yourself.
@@ -74,3 +74,5 @@ If you aren't able to see the expenses imported when you click “View expenses
*How do I remove an imported spreadsheet?*
If you need to remove an imported spreadsheet, you can select the red trash can icon. Please remember this will remove all unreported and unsubmitted transactions from your account that are tied to this import, so be careful!
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/business-bank-accounts/Business-Bank-Accounts-AUD.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/business-bank-accounts/Business-Bank-Accounts-AUD.md
index b59f68a65ce6..8c5ead911da4 100644
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/business-bank-accounts/Business-Bank-Accounts-AUD.md
+++ b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/business-bank-accounts/Business-Bank-Accounts-AUD.md
@@ -36,7 +36,7 @@ You can complete this process either via the web app (on a computer), or via the
If you are new to using Batch Payments in Australia, to reimburse your staff or process payroll, you may want to check out these bank-specific instructions for how to upload your .aba file:
- ANZ Bank - [Import a file for payroll payments](https://www.anz.com.au/support/internet-banking/pay-transfer-business/payroll/import-file/)
-- CommBank - [Importing and using
 Direct Entry (EFT) files](https://www.commbank.com.au/business/pds/003-279-importing-a-de-file.pdf)
+- CommBank - [Importing and using Direct Entry (EFT) files](https://www.commbank.com.au/business/pds/003-279-importing-a-de-file.pdf)
- Westpac - [Importing Payment Files](https://www.westpac.com.au/business-banking/online-banking/support-faqs/import-files/)
- NAB - [Quick Reference Guide - Upload a payment file](https://www.nab.com.au/business/online-banking/nab-connect/help)
- Bendigo Bank - [Bulk payments user guide](https://www.bendigobank.com.au/globalassets/documents/business/bulk-payments-user-guide.pdf)
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/business-bank-accounts/Business-Bank-Accounts-USD.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/business-bank-accounts/Business-Bank-Accounts-USD.md
index 2fbdac02e85c..4ae2c669561f 100644
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/business-bank-accounts/Business-Bank-Accounts-USD.md
+++ b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/business-bank-accounts/Business-Bank-Accounts-USD.md
@@ -127,7 +127,7 @@ If you get a generic error message that indicates, "Something's gone wrong", ple
8. If you have another phone available, try to follow these steps on that device
If the issue persists, please contact your Account Manager or Concierge for further troubleshooting assistance.
-# FAQ
+{% include faq-begin.md %}
## What is a Beneficial Owner?
A Beneficial Owner refers to an **individual** who owns 25% or more of the business. If no individual owns 25% or more of the business, the company does not have a Beneficial Owner.
@@ -157,3 +157,5 @@ It's a good idea to wait till the end of that second business day. If you still
Make sure to reach out to your Account Manager or to Concierge once you have done so and our team will be able to re-trigger those 3 transactions!
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/CSV-Import.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/CSV-Import.md
index fc1e83701caf..fd50c245d568 100644
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/CSV-Import.md
+++ b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/CSV-Import.md
@@ -93,9 +93,11 @@ Then, try to upload the revised spreadsheet again:
3. Check the row count again on the Output Preview to confirm it matches the spreadsheet
4. Click **Submit Spreadsheet**
-# FAQ
+{% include faq-begin.md %}
## Why can't I see my CSV transactions immediately after uploading them?
Don't worry! You'll typically need to wait 1-2 minutes after clicking **I understand, I'll wait!**
## I'm trying to import a credit. Why isn't it uploading?
Negative expenses shouldn't include a minus sign. Instead, they should just be wrapped in parentheses. For example, to indicate "-335.98," you'll want to make sure it's formatted as "(335.98)."
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Commercial-Card-Feeds.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Commercial-Card-Feeds.md
index a60c1ab7831a..f46c1a1442c2 100644
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Commercial-Card-Feeds.md
+++ b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Commercial-Card-Feeds.md
@@ -99,7 +99,7 @@ To completely remove the card connection, unassign every card from the list and
Note: If expenses are Processing and then rejected, they will also be deleted when they're returned to an Open state as the card they're linked to no longer exists.
-# FAQ
+{% include faq-begin.md %}
## My Commercial Card feed is set up. Why is a specific card not coming up when I try to assign it to an employee?
Cards will appear in the drop-down when activated and have at least one posted transaction. If the card is activated and has been used for a while and you're still not seeing it, please reach out to your Account Manager or message concierge@expensify.com for further assistance.
@@ -124,3 +124,5 @@ If your company uses a Commercial Card program that isn’t with one of our Appr
- Stripe
- Brex
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Company-Card-Settings.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Company-Card-Settings.md
index fa5879d85ea8..bc9801060223 100644
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Company-Card-Settings.md
+++ b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Company-Card-Settings.md
@@ -84,8 +84,10 @@ Expensify eReceipts serve as digital substitutes for paper receipts in your purc
To ensure seamless automatic importation, it's essential to maintain your transactions in US Dollars. Additionally, eReceipts can be directly imported from your bank account. Please be aware that CSV/OFX imported files of bank transactions do not support eReceipts.
It's important to note that eReceipts are not generated for lodging expenses. Moreover, due to incomplete or inaccurate category information from certain banks, there may be instances of invalid eReceipts being generated for hotel purchases. If you choose to re-categorize expenses, a similar situation may arise. It's crucial to remember that our Expensify eReceipt Guarantee excludes coverage for hotel and motel expenses.
-# FAQ
+{% include faq-begin.md %}
## What plan/subscription is required in order to manage corporate cards?
Group Policy (Collect or Control plan only)
## When do my company card transactions import to Expensify?
Credit card transactions are imported to Expensify once they’re posted to the bank account. This usually takes 1-3 business days between the point of purchase and when the transactions populate in your account.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Connect-ANZ.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Connect-ANZ.md
index 59104ce36a41..9844622f8539 100644
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Connect-ANZ.md
+++ b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Connect-ANZ.md
@@ -24,7 +24,7 @@ Importing your ANZ Visa into Expensify will allow your card transactions to flow
4. Once you’ve filled out and submitted your Internet Banking data authority form or ANZ Direct Online authority form, ANZ will set up the feed and send all the details directly to Expensify.
5. Then, we’ll add the card feed to your Expensify account and send you a message to let you know that it has been set up. We'll also include some webinar training resources to ensure you have all the information you need!
-# FAQ
+{% include faq-begin.md %}
## Are there discounts available for ANZ customers?
As ANZ’s preferred receipt tracking and expense management partner, Expensify offers ANZ business customers a few special perks:
@@ -44,3 +44,5 @@ After the free trial, you’ll get preferred pricing at 50% off the current rate
## Do I need to sign up for a specific period in order to receive the discount?
There is no obligation to sign up for a certain period to receive the discount. After your free trial, the 50% discount for the first 12 months, will be applied automatically to your account. After the initial 12 months, the 15% discount will also be applied automatically.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Direct-Bank-Connections.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Direct-Bank-Connections.md
index 372edd8f14ec..c9720177a8fc 100644
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Direct-Bank-Connections.md
+++ b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Direct-Bank-Connections.md
@@ -72,7 +72,7 @@ If you need to connect a separate card program from the same bank (that's access
To fix this, you would need to contact your bank and request to combine all of your cards under a single set of login credentials. That way, you can connect all of your cards from that bank to Expensify using a single set of login credentials.
-# FAQ
+{% include faq-begin.md %}
## How can I connect and manage my company’s cards centrally if I’m not a domain admin?
If you cannot access Domains, you must request Domain Admin access to an existing Domain Admin (usually the workspace owner).
@@ -112,3 +112,5 @@ If you've answered "yes" to any of these questions, you'll need to update this i
A Domain Admin can fix the connection by heading to **Settings > Domains > _Domain Name_ > Company Cards > Fix**. You will be prompted to enter the new credentials/updated information, and this should reestablish the connection.
If you are still experiencing issues with the card connection, please search for company card troubleshooting or contact Expensify Support for help.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Export-To-GL-Accounts.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Export-To-GL-Accounts.md
deleted file mode 100644
index 85b534338b53..000000000000
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Export-To-GL-Accounts.md
+++ /dev/null
@@ -1,5 +0,0 @@
----
-title: Export to GL Accounts
-description: Export to GL Accounts
----
-## Resource Coming Soon!
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Reconciliation.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Reconciliation.md
index d6de2ca66ade..2cb684a2240b 100644
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Reconciliation.md
+++ b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/company-cards/Reconciliation.md
@@ -51,7 +51,7 @@ If there are still unapproved expenses when you want to close your books for the
- Match Approved Total to Company Card Liability account in your accounting system.
- Unapproved Total becomes the Accrual amount (provided the first two amounts are correct).
-# FAQ
+{% include faq-begin.md %}
## Who can view and access the Reconciliation tab?
@@ -67,3 +67,5 @@ If a cardholder reports expenses as missing, we first recommend using the Reconc
If after updating, the expense still hasn’t appeared, you should reach out to Concierge with the missing expense specifics (merchant, date, amount and last four digits of the card number). Please note, only posted transactions will import.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/deposit-accounts/Deposit-Accounts-USD.md b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/deposit-accounts/Deposit-Accounts-USD.md
index a4ff7503f7bb..0bc5cb0ad955 100644
--- a/docs/articles/expensify-classic/bank-accounts-and-credit-cards/deposit-accounts/Deposit-Accounts-USD.md
+++ b/docs/articles/expensify-classic/bank-accounts-and-credit-cards/deposit-accounts/Deposit-Accounts-USD.md
@@ -56,7 +56,7 @@ You should be all set! The bank account will display as a deposit-only business
1. Navigate to **Settings > Account > Payments > Bank Accounts**
2. Click the **Delete** next to the bank account you want to remove
-# FAQ
+{% include faq-begin.md %}
## **What happens if my bank requires an additional security check before adding it to a third-party?**
@@ -73,3 +73,5 @@ There are a few reasons a reimbursement may be unsuccessful. The first step is t
- Your account wasn’t set up for Direct Deposit/ACH. You may want to contact your bank to confirm.
If you aren’t sure, please reach out to Concierge and we can assist!
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/billing-and-subscriptions/Billing-Overview.md b/docs/articles/expensify-classic/billing-and-subscriptions/Billing-Overview.md
index 30a507a1f9df..09dd4de2867b 100644
--- a/docs/articles/expensify-classic/billing-and-subscriptions/Billing-Overview.md
+++ b/docs/articles/expensify-classic/billing-and-subscriptions/Billing-Overview.md
@@ -26,7 +26,7 @@ If at least 50% of your approved USD spend in a given month is on your company
Additionally, every month, you receive 1% cash back on all Expensify Card purchases, and 2% if the spend across your Expensify Cards is $250k or more. Any cash back from the Expensify Card is first applied to your Expensify bill, further reducing your price per member. Any leftover cash back is deposited directly into your connected bank account.
## Savings calculator
To see how much money you can save (and even earn!) by using the Expensify Card, check out our [savings calculator](https://use.expensify.com/price-savings-calculator). Just enter a few details and see how much you’ll save!
-# FAQ
+{% include faq-begin.md %}
## What if we put less than 50% of our total spend on the Expensify Card?
If you put less than 50% of your total USD spend on your Expensify Card, your bill gets discounted on a sliding scale based on the percentage of use. So if you don't use the Expensify Card at all, you'll be charged the full rate for each member based on your plan and subscription.
Example:
@@ -36,3 +36,5 @@ Example:
You save 70% on the price per member on your bill for that month.
Note: USD spend refers to approved USD transactions on the Expensify Card in any given month, compared to all approved USD spend on workspaces in that same month.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/billing-and-subscriptions/Billing-Owner.md b/docs/articles/expensify-classic/billing-and-subscriptions/Billing-Owner.md
index 4fd7ef71c2e7..49a369c3cb51 100644
--- a/docs/articles/expensify-classic/billing-and-subscriptions/Billing-Owner.md
+++ b/docs/articles/expensify-classic/billing-and-subscriptions/Billing-Owner.md
@@ -38,7 +38,7 @@ To take over billing for the entire domain, you must:
1. Go to **Settings > Domains > _Domain Name_ > Domain Admins** and enable Consolidated Domain Billing.
Currently, Consolidated Domain Billing simply consolidates the amounts due for each Group Workspace Billing Owner (listed on the **Settings > Workspaces > Group** page). If you want to use the Annual Subscription across all Workspaces on the domain, you must also be the Billing Owner of all Group Workspaces.
-# FAQ
+{% include faq-begin.md %}
## Why can't I see the option to take over billing?
There could be two reasons:
1. You may not have the role of Workspace Admin. If you can't click on the Workspace name (if it's not a blue hyperlink), you're not a Workspace Admin. Another Workspace Admin for that Workspace must change your role before you can proceed.
@@ -47,3 +47,5 @@ There could be two reasons:
There are two ways to resolve this:
1. Have your IT dept. gain access to the account so that you can make yourself an admin. Your IT department may need to recreate the ex-employee's email address. Once your IT department has access to the employee's Home page, you can request a magic link to be sent to that email address to gain access to the account.
1. Have another admin make you a Workspace admin.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/billing-and-subscriptions/Change-Plan-Or-Subscription.md b/docs/articles/expensify-classic/billing-and-subscriptions/Change-Plan-Or-Subscription.md
index f01bb963bacf..1e631a53b0b3 100644
--- a/docs/articles/expensify-classic/billing-and-subscriptions/Change-Plan-Or-Subscription.md
+++ b/docs/articles/expensify-classic/billing-and-subscriptions/Change-Plan-Or-Subscription.md
@@ -76,9 +76,11 @@ Note: Refunds apply to Collect or Control Group Workspaces with one month of bil
Once you’ve successfully downgraded to a free Expensify account, your Workspace will be deleted and you will see a refund line item added to your Billing History.
-# FAQ
+{% include faq-begin.md %}
## Will I be charged for a monthly subscription even if I don't use SmartScans?
Yes, the Monthly Subscription is prepaid and not based on activity, so you'll be charged regardless of usage.
## I'm on a group policy; do I need the monthly subscription too?
Probably not. Group policy members already have unlimited SmartScans, so there's usually no need to buy the subscription. However, you can use it for personal use if you leave your company's Workspace.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/billing-and-subscriptions/Consolidated-Domain-Billing.md b/docs/articles/expensify-classic/billing-and-subscriptions/Consolidated-Domain-Billing.md
index 35f6a428e0af..2e829c0785d3 100644
--- a/docs/articles/expensify-classic/billing-and-subscriptions/Consolidated-Domain-Billing.md
+++ b/docs/articles/expensify-classic/billing-and-subscriptions/Consolidated-Domain-Billing.md
@@ -16,8 +16,10 @@ When a Domain Admin enables Consolidated Domain Billing, all Group workspaces ow
If you don’t have multiple billing owners across your organization, or if you want to keep billing separate for any reason, then this feature isn’t necessary.
If you have an Annual Subscription and enable Consolidated Domain Billing, the Consolidated Domain Billing feature will gather the amounts due for each Group workspace Billing Owner (listed under **Settings > Workspaces > Group**). To make full use of the Annual Subscription for all workspaces in your domain, you should also be the billing owner for all Group workspaces.
-# FAQ
+{% include faq-begin.md %}
## How do I take over the billing of a workspace with Consolidated Domain Billing enabled?
You’ll have to toggle off Consolidated Domain Billing, take over ownership of the workspace, and then toggle it back on.
## Can I use Consolidated Domain Billing to cover the bill for some workspaces, but not others?
No, this feature means that you’ll be paying the bill for all domain members who choose a subscription.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/billing-and-subscriptions/Free-Trial.md b/docs/articles/expensify-classic/billing-and-subscriptions/Free-Trial.md
index 4f660588d432..e6d8f2fedb73 100644
--- a/docs/articles/expensify-classic/billing-and-subscriptions/Free-Trial.md
+++ b/docs/articles/expensify-classic/billing-and-subscriptions/Free-Trial.md
@@ -31,7 +31,7 @@ To access these extra free weeks, all you need to do is complete the tasks on yo
- Establish a connection between Expensify and your accounting system from the outset. By doing this early, you can start testing Expensify comprehensively from end to end.
-# FAQ
+{% include faq-begin.md %}
## What happens when my Free Trial ends?
If you’ve already added a billing card to Expensify, you will automatically start your organization’s Expensify subscription after your Free Trial ends. At the beginning of the following month, we'll bill the card you have on file for your subscription, adjusting the charge to exclude the Free Trial period.
If your Free Trial concludes without a billing card on file, you will see a notification on your Home page saying, 'Your Free Trial has expired.'
@@ -42,3 +42,5 @@ If you continue without adding a billing card, you will be granted a five-day gr
If you’d like to downgrade to an individual account after your Free Trial has ended, you will need to delete any Group Workspace that you have created. This action will remove the Workspaces, subscription, and any amount owed. You can do this in one of two ways from the Expensify web app:
- Select the “Downgrade” option on the billing card task on your Home page.
- Go to **Settings > Workspaces > [Workspace name]**, then click the gear button next to the Workspace and select Delete.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/billing-and-subscriptions/Individual-Subscription.md b/docs/articles/expensify-classic/billing-and-subscriptions/Individual-Subscription.md
index aa08340dd7a6..1d952cb15b1c 100644
--- a/docs/articles/expensify-classic/billing-and-subscriptions/Individual-Subscription.md
+++ b/docs/articles/expensify-classic/billing-and-subscriptions/Individual-Subscription.md
@@ -48,7 +48,7 @@ After purchasing the subscription from the App Store, remember to sync your app
The subscription renewal date is the same as the purchase date. For instance, if you sign up for the subscription on September 7th, it will renew automatically on October 7th. You can cancel your subscription anytime during the month if you no longer need unlimited SmartScans. If you do cancel, keep in mind that your subscription (and your ability to SmartScan) will continue until the last day of the billing cycle.
-# FAQ
+{% include faq-begin.md %}
## Can I use an Individual Subscription while on a Collect or Control Plan?
You can! If you want to track expenses separately from your organization’s Workspace, you can sign up for an Individual Subscription. However, only Submit and Track Workspace plans are available when on an Individual Subscription. Collect and Control Workspace plans require an annual or pay-per-use subscription. For more information, visit expensify.com/pricing.
@@ -65,3 +65,5 @@ Your subscription is a pre-purchase for 30 days of unlimited SmartScanning. This
## How can I cancel my subscription from the iOS app?
If you signed up for the Monthly Subscription via iOS and your iTunes account, you will need to log into iTunes and locate the subscription there in order to cancel it. The ability to cancel an Expensify subscription started via iOS is strictly limited to your iTunes account.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/billing-and-subscriptions/Pay-Per-Use-Subscription.md b/docs/articles/expensify-classic/billing-and-subscriptions/Pay-Per-Use-Subscription.md
index 2133e8c7da46..326ce7fe33ab 100644
--- a/docs/articles/expensify-classic/billing-and-subscriptions/Pay-Per-Use-Subscription.md
+++ b/docs/articles/expensify-classic/billing-and-subscriptions/Pay-Per-Use-Subscription.md
@@ -11,7 +11,7 @@ Pay-per-use is a billing option for people who prefer to use Expensify month to
1. Create a Group Workspace if you haven’t already by going to **Settings > Workspaces > Group > New Workspace**
2. Once you’ve created your Workspace, under the “Subscription” section on the Group Workspace page, select “Pay-per-use”.
-# FAQ
+{% include faq-begin.md %}
## What is considered an active user?
An active user is anyone who chats, creates, modifies, submits, approves, reimburses, or exports a report in Expensify. This includes actions taken by a Copilot and Workspace automation (such as Scheduled Submit and automated reimbursement). If no one on your Group Workspace uses Expensify in a given month, you will not be billed for that month.
@@ -26,4 +26,4 @@ If you expect to have an increased number of users for more than 3 out of 12 mon
## Will billing only be in USD currency?
While USD is the default billing currency, we also have GBP, AUD, and NZD billing currencies. You can see the rates on our [pricing](https://www.expensify.com/pricing) page.
-
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/billing-and-subscriptions/Tax-Exempt.md b/docs/articles/expensify-classic/billing-and-subscriptions/Tax-Exempt.md
index 33fbec003a91..92c92e4e3a44 100644
--- a/docs/articles/expensify-classic/billing-and-subscriptions/Tax-Exempt.md
+++ b/docs/articles/expensify-classic/billing-and-subscriptions/Tax-Exempt.md
@@ -15,6 +15,8 @@ Once your account is marked as tax-exempt, the corresponding state tax will no l
If you need to remove your tax-exempt status, let your Account Manager know or contact Concierge.
-# FAQ
+{% include faq-begin.md %}
## What happens to my past Expensify bills that incorrectly had tax added to them?
Expensify can provide a refund for the tax you were charged on your previous bills. Please let your Account Manager know or contact Concierge if this is the case.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expense-and-report-features/Attendee-Tracking.md b/docs/articles/expensify-classic/expense-and-report-features/Attendee-Tracking.md
index 7f3d83af1e6e..a0bd2c442dbb 100644
--- a/docs/articles/expensify-classic/expense-and-report-features/Attendee-Tracking.md
+++ b/docs/articles/expensify-classic/expense-and-report-features/Attendee-Tracking.md
@@ -20,7 +20,7 @@ Every expense has an Attendees field and will list the expense creator’s name
![image of an expense with attendee tracking]({{site.url}}/assets/images/attendee-tracking.png){:width="100%"}
-# FAQ
+{% include faq-begin.md %}
## Can I turn off attendee tracking?
Attendee tracking is a standard field on all expenses and cannot be turned off.
@@ -49,3 +49,4 @@ There is no limit.
## How can I remove attendees from an expense?
You can add or remove attendees from an expense as long as they are on a Draft report. Expenses on submitted reports cannot be edited, so you cannot remove attendees from these.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expense-and-report-features/Currency.md b/docs/articles/expensify-classic/expense-and-report-features/Currency.md
index eb6ca9bb2d40..77b5fbbb3ebc 100644
--- a/docs/articles/expensify-classic/expense-and-report-features/Currency.md
+++ b/docs/articles/expensify-classic/expense-and-report-features/Currency.md
@@ -46,7 +46,7 @@ Then, set the default currency for that workspace to match the currency in which
For example, if you have employees in the US, France, Japan, and India, you’d want to create four separate workspaces, add the employees to each, and then set the corresponding currency for each workspace.
-# FAQ
+{% include faq-begin.md %}
## I have expenses in several different currencies. How will this show up on a report?
@@ -60,5 +60,4 @@ Expenses entered in a foreign currency are automatically converted to the defaul
If you want to bypass the exchange rate conversion, you can manually enter an expense in your default currency instead.
-
-
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expense-and-report-features/Expense-Rules.md b/docs/articles/expensify-classic/expense-and-report-features/Expense-Rules.md
index ae6a9ca77db1..295aa8d00cc9 100644
--- a/docs/articles/expensify-classic/expense-and-report-features/Expense-Rules.md
+++ b/docs/articles/expensify-classic/expense-and-report-features/Expense-Rules.md
@@ -45,11 +45,11 @@ In general, your expense rules will be applied in order, from **top to bottom**,
4. If you belong to a workspace that is tied to an accounting integration, the configuration settings for this connection may update your expense details upon export, even if the expense rules were successfully applied to the expense.
-# FAQ
+{% include faq-begin.md %}
## How can I use Expense Rules to vendor match when exporting to an accounting package?
When exporting non-reimbursable expenses to your connected accounting package, the payee field will list "Credit Card Misc." if the merchant name on the expense in Expensify is not an exact match to a vendor in the accounting package.
When an exact match is unavailable, "Credit Card Misc." prevents multiple variations of the same vendor (e.g., Starbucks and Starbucks #1234, as is often seen in credit card statements) from being created in your accounting package.
For repeated expenses, the best practice is to use Expense Rules, which will automatically update the merchant name without having to do it manually each time.
This only works for connections to QuickBooks Online, Desktop, and Xero. Vendor matching cannot be performed in this manner for NetSuite or Sage Intacct due to limitations in the API of the accounting package.
-
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expense-and-report-features/Expense-Types.md b/docs/articles/expensify-classic/expense-and-report-features/Expense-Types.md
index 795a895e81f0..9d19dbb4f9ba 100644
--- a/docs/articles/expensify-classic/expense-and-report-features/Expense-Types.md
+++ b/docs/articles/expensify-classic/expense-and-report-features/Expense-Types.md
@@ -26,7 +26,7 @@ Each report will show the total amount for all expenses in the upper right. Unde
- **Time Expenses:** Employees or jobs are billed based on an hourly rate that you can set within Expensify.
- **Distance Expenses:** These expenses are related to travel for work.
-# FAQ
+{% include faq-begin.md %}
## What’s the difference between a receipt, an expense, and a report attachment?
@@ -40,3 +40,5 @@ In Expensify, a credit is displayed as an expense with a minus (ex. -$1.00) in f
If a report includes a credit or a refund expense, it will offset the total amount on the report.
For example, the report has two reimbursable expenses, $400 and $500. The total Reimbursable is $900.
Conversely, a -$400 and $500 will be a total Reimbursable amount of $500
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expense-and-report-features/Report-Audit-Log-and-Comments.md b/docs/articles/expensify-classic/expense-and-report-features/Report-Audit-Log-and-Comments.md
index 229ca4ec1fe4..04183608e3d1 100644
--- a/docs/articles/expensify-classic/expense-and-report-features/Report-Audit-Log-and-Comments.md
+++ b/docs/articles/expensify-classic/expense-and-report-features/Report-Audit-Log-and-Comments.md
@@ -49,7 +49,7 @@ Report comments initially trigger a mobile app notification to report participan
Comments can be formatted with bold, italics, or strikethrough using basic Markdown formatting. You can also add receipts and supporting documents to a report by clicking the paperclip icon on the right side of the comment field.
-# FAQ
+{% include faq-begin.md %}
## Why don’t some timestamps in Expensify match up with what’s shown in the report audit log?
@@ -58,3 +58,5 @@ While the audit log is localized to your own timezone, some other features in Ex
## Is commenting on a report a billable action?
Yes. If you comment on a report, you become a billable actor for the current month.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expense-and-report-features/The-Expenses-Page.md b/docs/articles/expensify-classic/expense-and-report-features/The-Expenses-Page.md
index 5431355dd790..57a7f7de298c 100644
--- a/docs/articles/expensify-classic/expense-and-report-features/The-Expenses-Page.md
+++ b/docs/articles/expensify-classic/expense-and-report-features/The-Expenses-Page.md
@@ -55,7 +55,7 @@ Select the expenses you want to export by checking the box to the left of each e
Then, click **Export To** in the upper right corner of the page, and choose our default CSV format or create your own custom CSV template.
-# FAQ
+{% include faq-begin.md %}
## Can I use the filters and analytics features on the mobile app?
The various features on the Expenses Page are only available while logged into your web account.
@@ -71,3 +71,4 @@ We have more about company card expense reconciliation in this [support article]
## Can I edit multiple expenses at once?
Yes! Select the expenses you want to edit and click **Edit Multiple**.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expense-and-report-features/The-Reports-Page.md b/docs/articles/expensify-classic/expense-and-report-features/The-Reports-Page.md
index ff9e2105ffac..9c55cd9b4b8d 100644
--- a/docs/articles/expensify-classic/expense-and-report-features/The-Reports-Page.md
+++ b/docs/articles/expensify-classic/expense-and-report-features/The-Reports-Page.md
@@ -31,7 +31,7 @@ To export a report to a CSV file, follow these steps on the Reports page:
2. Navigate to the upper right corner of the page and click the "Export to" button.
3. From the drop-down options that appear, select your preferred export format.
-# FAQ
+{% include faq-begin.md %}
## What does it mean if the integration icon for a report is grayed out?
If the integration icon for a report appears grayed out, the report has yet to be fully exported.
To address this, consider these options:
@@ -41,3 +41,4 @@ To address this, consider these options:
## How can I see a specific expense on a report?
To locate a specific expense within a report, click on the Report from the Reports page and then click on an expense to view the expense details.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expensify-card/Admin-Card-Settings-and-Features.md b/docs/articles/expensify-classic/expensify-card/Admin-Card-Settings-and-Features.md
index 1bfa5590efbc..16e628acbeee 100644
--- a/docs/articles/expensify-classic/expensify-card/Admin-Card-Settings-and-Features.md
+++ b/docs/articles/expensify-classic/expensify-card/Admin-Card-Settings-and-Features.md
@@ -148,7 +148,7 @@ Here are some reasons an Expensify Card transaction might be declined:
5. The merchant is located in a restricted country
- Some countries may be off-limits for transactions. If a merchant or their headquarters (billing address) are physically located in one of these countries, Expensify Card purchases will be declined. This list may change at any time, so be sure to check back frequently: Belarus, Burundi, Cambodia, Central African Republic, Democratic Republic of the Congo, Cuba, Iran, Iraq, North Korea, Lebanon, Libya, Russia, Somalia, South Sudan, Syrian Arab Republic, Tanzania, Ukraine, Venezuela, Yemen, and Zimbabwe.
-# FAQ
+{% include faq-begin.md %}
## What happens when I reject an Expensify Card expense?
Rejecting an Expensify Card expense from an Expensify report will simply allow it to be reported on a different report.
@@ -170,3 +170,5 @@ If a transaction is pending and has a receipt attached (excluding eReceipts), a
- Partial refunds:
If a transaction is pending, a partial refund will reduce the amount of the transaction.
- If a transaction is posted, a partial refund will create a negative transaction for the refund amount.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expensify-card/Auto-Reconciliation.md b/docs/articles/expensify-classic/expensify-card/Auto-Reconciliation.md
index b39119ffa4df..73b6c9106e4e 100644
--- a/docs/articles/expensify-classic/expensify-card/Auto-Reconciliation.md
+++ b/docs/articles/expensify-classic/expensify-card/Auto-Reconciliation.md
@@ -168,7 +168,7 @@ If Auto-Reconciliation is disabled for your company's Expensify Cards, a Domain
2. Each time a monthly settlement occurs, Expensify calculates the total purchase amount since the last settlement and creates a Journal Entry. This entry credits the settlement bank account (GL Account) and debits the Expensify Liability Account in Intacct.
3. As expenses are approved and exported to Intacct, Expensify credits the Liability Account and debits the appropriate expense categories.
-# FAQ
+{% include faq-begin.md %}
## What are the timeframes for auto-reconciliation in Expensify?
We offer either daily or monthly auto-reconciliation:
@@ -209,3 +209,5 @@ To address this, please follow these steps:
2. Go to the General Ledger (GL) account where your daily Expensify Card settlement withdrawals are recorded, and locate entries for the dates identified in Step 1.
3. Adjust each settlement entry so that it now posts to the Clearing Account.
4. Create a Journal Entry or Receive Money Transaction to clear the balance in the Liability Account using the funds currently held in the Clearing Account, which was set up in Step 2.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expensify-card/Cardholder-Settings-and-Features.md b/docs/articles/expensify-classic/expensify-card/Cardholder-Settings-and-Features.md
index 3cb05cb136f6..f24ed57dc655 100644
--- a/docs/articles/expensify-classic/expensify-card/Cardholder-Settings-and-Features.md
+++ b/docs/articles/expensify-classic/expensify-card/Cardholder-Settings-and-Features.md
@@ -76,9 +76,11 @@ There was suspicious activity
- If the spending looks suspicious, we may complete a manual due diligence check, and our team will do this as quickly as possible - your cards will all be locked while this happens.
- The merchant is located in a restricted country
-# FAQ
+{% include faq-begin.md %}
## Can I use Smart Limits with a free Expensify account?
If you're on the Free plan, you won't have the option to use Smart Limits. Your card limit will simply reset at the end of each calendar month.
## I still haven't received my Expensify Card. What should I do?
For more information on why your card hasn't arrived, you can check out this resource on [Requesting a Card](https://help.expensify.com/articles/expensify-classic/expensify-card/Request-the-Card#what-if-i-havent-received-my-card-after-multiple-weeks).
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expensify-card/Dispute-A-Transaction.md b/docs/articles/expensify-classic/expensify-card/Dispute-A-Transaction.md
index 12dad0c7084d..caf540152063 100644
--- a/docs/articles/expensify-classic/expensify-card/Dispute-A-Transaction.md
+++ b/docs/articles/expensify-classic/expensify-card/Dispute-A-Transaction.md
@@ -46,7 +46,7 @@ To ensure the dispute process goes smoothly, please:
- If you recognize the merchant but not the charge, and you've transacted with them before, contact the merchant directly, as it may be a non-fraudulent error.
- Include supporting documentation like receipts or cancellation confirmations when submitting your dispute to enhance the likelihood of a favorable resolution.
-# FAQ
+{% include faq-begin.md %}
## **How am I protected from fraud using the Expensify Card?**
Real-time push notifications alert you of every card charge upfront, helping identify potential issues immediately. Expensify also leverages sophisticated algorithms to detect and/or block unusual card activity.
@@ -59,3 +59,4 @@ The dispute process can take a few days to a few months. It depends on the type
## **Can I cancel a dispute?**
Contact Concierge if you've filed a dispute and want to cancel it. You might do this if you recognize a previously reported unauthorized charge or if the merchant has already resolved the issue.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expensify-card/Expensify-Card-Perks.md b/docs/articles/expensify-classic/expensify-card/Expensify-Card-Perks.md
deleted file mode 100644
index 868ade604451..000000000000
--- a/docs/articles/expensify-classic/expensify-card/Expensify-Card-Perks.md
+++ /dev/null
@@ -1,193 +0,0 @@
----
-title: Expensify Card Perks
-description: Get the most out of your Expensify Card with exclusive perks!
----
-
-
-# Overview
-The Expensify Visa® Commercial Card is packed with perks, both native to our Card program and through exclusive discounts with partnering solutions. The Expensify Card’s primary perks include:
-- Unbeatable cash back incentive with each USD purchase
-
-Below, we’ll cover all of our exclusive offers in more detail and how to claim discounts with our partners.
-
-# Partner Specific Perks
-
-## Amazon AWS
-Whether you are a two-person startup launching a new company or a venture-backed startup, we all could use a little relief in these difficult times. AWS Activate provides you with access to the resources you need to quickly get started on AWS - including free credits, technical support, and training.
-
-All Expensify customers that have adopted The Expensify Card qualify when they add their Expensify Card for billing with AWS!
-
-**Apply now by going [to this link](https://aws.amazon.com/startups/credits) and using the OrgID: 0qyIA (Case Sensitive)**
-
-The full details on the AWS Activate program can be found in AWS's [terms & conditions](https://aws.amazon.com/activate/terms/) and the [Activate FAQs](https://aws.amazon.com/startups/faq).
-
-## Stripe
-Whether you’re creating a subscription service, an on-demand marketplace, or an e-commerce store, Stripe’s integrated payments platform helps you build and scale your business globally.
-
-**Receive waived Stripe fees, if you’re new to Stripe, for your first $5,000 in processed payments.**
-
-**How to redeem:** Sign up for Stripe using your Expensify Card.
-
-## Lamar Advertising
-Lamar provides out-of-home advertising space for clients on billboards, digital, airport displays, transit, and highway logo signs.
-
-**Receive at minimum a 10% discount on your first campaign.**
-
-**How do redeem:** Contact Expensify’s dedicated account manager, Lisa Kane, and mention you’re an Expensify cardholder.
-
-Email: lkane@lamar.com
-
-## Carta
-Simplify equity management with Carta.
-
-**Receive a 20% first-year discount and waived implementation fees for Carta.**
-
-**How to redeem:** Sign up using your Expensify Card
-
-## Pilot
-Pilot specializes in bookkeeping and tax prep for startups and e-commerce providers. When you work with Pilot, you’re paired with a dedicated finance expert who takes the work off your plate and is on hand to answer your questions.
-
-**20% off the first 6-months of Pilot Core**
-
-**How to redeem:** Sign-up using your Expensify Card.
-
-## Spotlight Reporting
-The integrated cloud reporting and forecasting tool that allows you to create insights for better business decisions. Designed by Accountants, for Accountants
-
-**20% discount off your subscription for the first 6 months, plus one free seat to Spotlight Certification.**
-
-**How to redeem:** Sign up using your Expensify Card.
-
-## Guideline
-Guideline's full-service 401(k) plans make it easier and more affordable to offer your employees the retirement benefits they deserve.
-
-**Receive 3 months free.**
-
-**How to redeem:** Sign up using your Expensify Card.
-
-## Gusto
-Gusto's people platform helps businesses like yours onboard, pay, insure, and support your hardworking team. Payroll, benefits, and more
-
-**3 months free service**
-
-**How to redeem:** Sign-up using your Expensify Card.
-
-## QuickBooks Online
-QuickBooks accounting software helps keep your books accurate and up to date, automatically such as: invoicing, cashflow, expense tracking, and more.
-
-**Receive 30% off QuickBooks Online for the first 12 months.**
-
-**How to redeem:** Sign up using your Expensify Card.
-
-## Highfive
-Highfive improves the ease and quality of intelligent in-room video conferencing.
-
-**Receive 50% off the Highfive Select starter package. 10% off the Highfive Premium Package.**
-
-**How to redeem:** Sign-up with your Expensify Card.
-
-## Zendesk
-**$436 in credits for Zendesk Suite products per month for the first year**
-
-How to redeem:
-1. Reach out to startups@zendesk.com with the following: "Expensify asked me to send an email regarding the Zendesk promotion”. You'll receive a code you use in step 5 below.
-2. Start a Zendesk Trial (can be a suite trial or something different) in USD. If your trial is not in USD, contact Zendesk. If you already have a current trial, the code applies and can be used.
-3. From inside your Zendesk trial, click the Buy Now button.
-4. Select your chosen plan with monthly billing. The $436 monthly credit works for up to 4 licenses of the Suite, but the code can also apply $436 to any alternative monthly plan selection.
-5. Enter the promo code that was provided to you in step 1 after emailing Zendesk.
-6. Complete the checkout process and note that once your free credit runs out after 12 monthly billing periods, you will be charged for your next month with Zendesk.
-
-## Xero
-Accounting Software With Everything You Need To Run Your Business Beautifully. Smart Online Accounting. Bank Connections
-
-**U.S. residents get 50% off Xero for six months.**
-
-Head to [this](https://apps.xero.com/us/app/expensify?xtid=x30expensify&utm_source=expensify&utm_medium=web&utm_campaign=cardoffer) page and sign-up for Xero using your Expensify Card!
-
-## Freshworks
-Boost your startup journey with leading customer and employee engagement solutions from Freshworks including CRM, livechat, support, marketing automation, ITSM and HRMS.
-
-How to receive $4,000 in credits on Freshworks products:
-
-[Click here](https://www.freshworks.com/partners/startup-program/expensify-card/) and fill out the form and enter your details, Freshbooks will recognize your company as an Expensify Card customer automatically.
-
-## Slack
-**Receive 25% off for the first year:** You’ll enjoy premium features like unlimited messaging and apps, Slack Connect channels, group video calls, priority support, and much more. It’s all just a click away.
-
-**How to redeem with your Expensify Card:** [Click here](https://slack.com/promo/partner?remote_promo=ead919f5) to redeem the offer by using your Expensify Card to manage the billing.
-
-## Deel.com
-Deel makes onboarding international team members in 150 different countries painless. Quickly bring on contractors or hire employees in seconds with Deel as your employer of record (EOR). It’s one simple, powerful dashboard that houses everything you need. Finalize contracts, pay employees, and manage all your payroll data in one place seamlessly.
-
-**How to redeem 3 months free, then 30% off the rest of the year with Deel.com:** Click [here](https://www.deel.com/partners/expensify) and sign up using your Expensify Card.
-
-## Snap
-**$1,000 in Snap credits**
-Whether you're looking to increase online sales, drive app installs, or get more leads, Snapchat can connect you with a unique mobile audience primed to take action. For a limited time, spend $1000 in Snapchat's Ads Manager and receive $1000 in ad credit to use towards your next campaign!
-
-**How to redeem with your Expensify Card:** Click on `create ad` or `request a call` by clicking here. Enter your details to set up your account if you don't already have one.Add the Expensify Card as your payment option for your Snap Business account.Credits will be automatically placed in your account once you've reached $1,000 in spend.
-
-## Aircall
-Aircall is the cloud-based phone system of choice for modern brands. Aircall allows sales and support teams to have meaningful and efficient phone conversations, and integrates with the most popular CRMs, Help desks, and business tools. Pricing is dependent on the number of users within the account. Discount could range from $270-$9,000+
-
-**2 Months Free**
-
-**How to redeem with your Expensify Card:**
-1. Click [here])(http://pages.aircall.io/Expensify-RewardsPartnerReferral.html)
-2. Sign up for a demo
-3. Let our team know you're an Expensify customer
-
-## NetSuite
-NetSuite helps companies manage core business processes with a cloud-based ERP and accounting software. Expensify has a direct integration with NetSuite so that expenses are coded to your exact preference and data is always synchronized across the two systems.
-
-**10% OFF for the First Year**
-
-**How to redeem:**
-1. Fill out this [Google form](https://community.expensify.com/home/leaving?allowTrusted=1&target=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLSeiOzLrdO-MgqeEMwEqgdQoh4SJBi42MZME9ycHp4SQjlk3bQ%2Fviewform%3Fusp%3Dsf_link).
-2. An Expensify rep will make an introduction to a NetSuite sales rep to get the process started. This offer is only for prospective NetSuite customers. If you are currently a NetSuite customer, this promotion does not apply.
-3. Once you are set up and pay for your first year with NetSuite, we will send you a payment equal to 10% of your first year contract within three months of paying your first NetSuite invoice.
-
-## PagerDuty
-PagerDuty's Platform for Real-Time Operations integrates machine data & human intelligence to improve visibility & agility across organizations.
-
-**25% OFF**
-
-**How to redeem:**
-1. Sign-up using your Expensify Card
-2. Use the discount code EXPENSIFYPDTEAM for a 25% discount on the Team plan or EXPENSIFYPDBUSINESS for a 25% discount on the Business plan within the Cost Summary section upon checkout.
-
-## Typeform
-Typeform makes collecting and sharing information comfortable and conversational. It's a web-based platform you can use to create anything from surveys to apps, without needing to write a single line of code.
-
-**30% off annual premium and professional plans**
-
-**How to redeem with your Expensify Card:**
-1. Click on the 'Get Typeform` by [clicking here](https://try.typeform.com/expensify/?utm_source=expensify&utm_medium=referral&utm_campaign=expensify_integration&utm_content=directory)
-2. Enter your details and setup your free account
-3. Verify your email by clicking on the link that Typeform sends you
-4. Go through the on boarding flow within Tyepform
-5. Click on the 'Upgrade' button from within your workspace
-6. Select your plan
-7. Enter the coupon 'EXPENSIFY30' on the checkout page
-8. Click on 'Upgrade now' once you've filled out all of your payment details with your Expensify Card
-
-## Intercom
-Intercom builds a suite of messaging-first products for businesses to accelerate growth across the customer lifecycle.
-
-**3-months free service**
-
-**How to redeem:** Sign-up using your Expensify Card.
-
-## Talkspace
-Prescription management and personalized treatment from a network of licensed prescribers trained in mental healthcare. Therapists are licensed, verified and background-checked. Working with a Talkspace therapist will give you an unbiased, trained perspective and provide you with the guidance and tools to help you feel better. When it comes to your mental health, the right therapist makes all the difference.
-
-**$125 OFF Talkspace purchases**
-
-**How to redeem with your Expensify Card:** Use the code at EXPENSIFY at the time of checkout.
-
-## Stripe Atlas
-Stripe Atlas helps removes obstacles typically associated with starting a business so you can build your startup from anywhere in the world.
-
-**Receive $100 off Stripe Atlas and get access to a startup toolkit and special offers on additional Strip Atlas services.**
-
-**How to redeem:** Sign up with your Expensify Card.
diff --git a/docs/articles/expensify-classic/expensify-card/Request-the-Card.md b/docs/articles/expensify-classic/expensify-card/Request-the-Card.md
index ca0e7b4709b2..9940535e1fad 100644
--- a/docs/articles/expensify-classic/expensify-card/Request-the-Card.md
+++ b/docs/articles/expensify-classic/expensify-card/Request-the-Card.md
@@ -38,7 +38,7 @@ If you need to cancel your Expensify Card and cannot access the website or mobil
It's not possible to order a replacement card over the phone, so, if applicable, you would need to handle this step from your Expensify account.
-# FAQ
+{% include faq-begin.md %}
## What if I haven’t received my card after multiple weeks?
@@ -47,3 +47,5 @@ Reach out to support, and we can locate a tracking number for the card. If the c
## I’m self-employed. Can I set up the Expensify Card as an individual?
Yep! As long as you have a business bank account and have registered your company with the IRS, you are eligible to use the Expensify Card as an individual business owner.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expensify-card/Set-Up-the-Card-for-Your-Company.md b/docs/articles/expensify-classic/expensify-card/Set-Up-the-Card-for-Your-Company.md
index e0ef1f3f00fe..464f2129d800 100644
--- a/docs/articles/expensify-classic/expensify-card/Set-Up-the-Card-for-Your-Company.md
+++ b/docs/articles/expensify-classic/expensify-card/Set-Up-the-Card-for-Your-Company.md
@@ -46,7 +46,7 @@ If you have a validated domain, you can set a limit for multiple members by sett
The Company Cards page will act as a hub to view all employees who have been issued a card and where you can view and edit the individual card limits. You’ll also be able to see anyone who has requested a card but doesn’t have one yet.
-# FAQ
+{% include faq-begin.md %}
## Are there foreign transaction fees?
@@ -65,3 +65,5 @@ The Expensify Card is a free corporate card, and no fees are associated with it.
As long as the verified bank account used to apply for the Expensify Card is a US bank account, your cardholders can be anywhere in the world.
Otherwise, the Expensify Card is not available for customers using non-US banks. With that said, launching international support is a top priority for us. Let us know if you’re interested in contacting support, and we’ll reach out as soon as the Expensify Card is available outside the United States.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/expensify-partner-program/How-to-Join-the-ExpensifyApproved!-Partner-Program.md b/docs/articles/expensify-classic/expensify-partner-program/How-to-Join-the-ExpensifyApproved!-Partner-Program.md
deleted file mode 100644
index e14fadbec915..000000000000
--- a/docs/articles/expensify-classic/expensify-partner-program/How-to-Join-the-ExpensifyApproved!-Partner-Program.md
+++ /dev/null
@@ -1,38 +0,0 @@
----
-title: ExpensifyApproved! Partner Program
-description: How to Join the ExpensifyApproved! Partner Program
----
-
-# Overview
-
-As trusted accountants and financial advisors, you strive to offer your clients the best tools available. Expensify is recognized as a leading, all-in-one expense and corporate card management platform suitable for clients of every size. By becoming an ExpensifyApproved! Partner, you unlock exclusive benefits for both you and your clientele.
-## Key Benefits
-Dedicated Partner Manager: Enjoy personalized assistance with an assigned Partner Manager post-course completion.
-Client Onboarding Support: A dedicated Client Onboarding Manager will aid in smooth transitions.
-Free Expensify Account: Complimentary access to our platform for your convenience.
-Revenue share (US-only): All partners receive 0.5% revenue share on client Expensify Card transactions. Keep this as a bonus or offer it to your clients as cash back.
-Exclusive CPA Card (US-only): Automated expense reconciliation from swipe to journal entry with the CPA Card.
-Special Pricing Offers (US-only): Avail partner-specific discounts for your clients and a revenue share from client Expensify Card transactions.
-Professional Growth (US-only): Earn 3 CPE credits after completing the ExpensifyApproved! University.
-Cobranded Marketing - Collaborate with your Partner Manager to craft custom marketing materials, case studies, and more.
-
-# How to join the ExpensifyApproved! Partner Program
-
-1. Enroll in ExpensifyApproved! University (EA!U)
-Visit university.expensify.com and enroll in the “Getting Started with Expensify” course.
-This course imparts the essentials of Expensify, ensuring you follow the best practices for client setups.
-
-2. Complete the course
-Grasp the core features and functionalities of Expensify.
-Ensure you're equipped to serve your clients using Expensify to its fullest.
-Once completed, you’ll be prompted to schedule a call with your Partner Manager. **This call is required to earn your certification.**
-
-3. Once you successfully complete the course, you'll unlock:
-- A dedicated Partner Manager - assigned to you after you have completed the course!
-- A dedicated Client Setup Specialist
-- Membership to the ExpensifyApproved! Partner Program.
-- A complimentary free Expensify account
-- Access to the exclusive CPA Card (US-only).
-- Partner-specific discounts to extend to your clients.
-- A 0.5% revenue share on client Expensify Card expenses (US-only)
-- 3 CPE credits (US-only).
diff --git a/docs/articles/expensify-classic/expensify-partner-program/Partner-Billing-Guide.md b/docs/articles/expensify-classic/expensify-partner-program/Partner-Billing-Guide.md
index 750a1fc10e77..86dbfe5d0720 100644
--- a/docs/articles/expensify-classic/expensify-partner-program/Partner-Billing-Guide.md
+++ b/docs/articles/expensify-classic/expensify-partner-program/Partner-Billing-Guide.md
@@ -63,7 +63,7 @@ Using client IDs for Optimized Billing in Expensify: A unique identifier feature
- Using client IDs for all Workspaces: It's beneficial to use client IDs for all Workspaces to ensure each one is easily recognizable.
- Benefits of itemized billing receipts: Employing client IDs offers itemized billing by client, with each itemization detailing unique active users.
-# FAQ
+{% include faq-begin.md %}
**Do I automatically get the special billing rate as an ExpensifyApproved! Partner?**
- Yes, when you join the ExpensifyApproved! program, you will automatically get the special billing rate. To join the ExpensifyApproved! Program, you need to enroll in ExpensifyApproved! University.
@@ -85,3 +85,5 @@ Using client IDs for Optimized Billing in Expensify: A unique identifier feature
**Where can I see the Billing Receipts?**
- All billing owners receive an emailed PDF of their monthly billing receipt, but a CSV version can also be downloaded from the platform.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/get-paid-back/Per-Diem-Expenses.md b/docs/articles/expensify-classic/get-paid-back/Per-Diem-Expenses.md
index 1b537839af77..e7a43c1d1d61 100644
--- a/docs/articles/expensify-classic/get-paid-back/Per-Diem-Expenses.md
+++ b/docs/articles/expensify-classic/get-paid-back/Per-Diem-Expenses.md
@@ -29,7 +29,7 @@ You can include meal deductions or overnight lodging costs if your jurisdiction
### Step 6: Submit for Approval
Finally, submit your Per Diem expense for approval, and you'll be on your way to getting reimbursed!
-# FAQ
+{% include faq-begin.md %}
## Can I edit my per diem expenses?
Per Diems cannot be amended. To make changes, delete the expense and recreate it as needed.
@@ -43,3 +43,5 @@ Reach out to your internal Admin team, as they've configured the rates in your p
## Can I add start and end times to per diems?
Unfortunately, you cannot add start and end times to Per Diems in Expensify.
By following these steps, you can efficiently create and manage your Per Diem expenses in Expensify, making the process of tracking and getting reimbursed hassle-free.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/get-paid-back/Referral-Program.md b/docs/articles/expensify-classic/get-paid-back/Referral-Program.md
index b4a2b4a7de74..24605dd17d3f 100644
--- a/docs/articles/expensify-classic/get-paid-back/Referral-Program.md
+++ b/docs/articles/expensify-classic/get-paid-back/Referral-Program.md
@@ -1,54 +1,49 @@
---
-title: Expensify Referral Program
-description: Send your joining link, submit a receipt or invoice, and we'll pay you if your referral adopts Expensify.
+title: Earn money with Expensify referrals
+description: Get paid with the Expensify referral program! Share your link, earn $250 per successful sign-up, and enjoy unlimited income potential. It’s that easy.
redirect_from: articles/other/Referral-Program/
---
-# About
+# Earn money with Expensify referrals
-Expensify has grown thanks to our users who love Expensify so much that they tell their friends, colleagues, managers, and fellow business founders to use it, too.
+Picture this: You've found Expensify and it's transformed your approach to expense management and financial organization. You love it so much that you can't help but recommend it to friends, family, and colleagues. Wouldn’t it be nice if you could get rewarded just for spreading the word?
-As a thank you, every time you bring a new user into the platform who directly or indirectly leads to the adoption of a paid annual plan on Expensify, you will earn $250.
+With Expensify referrals, you can. Every time someone you invite to the platform signs up for a paid annual plan on Expensify, you’ll earn $250. Think of it as a thank-you gift from us to you!
-# How to get paid for referring people to Expensify
+## How to get paid for Expensify referrals
-1. Submit a report or invoice, or share your referral link with anyone you know who is spending too much time on expenses, or works at a company that could benefit from using Expensify.
+Here are a few easy ways to get paid for Expensify friend referrals:
-2. You will get $250 for any referred business that commits to an annual subscription, has 2 or more active users, and makes two monthly payments.
+- Submit an expense report to your boss (even just one receipt!)
+- Send an invoice to a client or customer
+- Share your referral link with a friend
+ - To find your referral link, open your Expensify mobile app and go to **Settings > Refer a friend, earn cash! > Share invite link**.
-That’s right! You can refer anyone working at any company you know.
+**If the person you referred commits to an annual subscription with two or more active users and makes two monthly payments, you’ll get $250. Cha-ching!**
-If their company goes on to become an Expensify customer with an annual subscription, and you are the earliest recorded referrer of a user on that company’s paid Expensify Policy, you'll get paid a referral reward.
+## Who can you refer?
-The best way to start is to submit any receipt to your manager (you'll get paid back and set yourself up for $250 if they start a subscription: win-win!)
+You can refer anyone who might benefit from Expensify. Seriously. Anybody.
-Referral rewards for the Spring/Summer 2023 campaign will be paid by direct deposit.
+Know a small business owner? Refer them! An [accountant](https://use.expensify.com/accountants-program)? Refer them! A best friend from childhood who keeps losing paper receipts? Refer them!
-# FAQ
+Plus, you can [refer an unlimited amount of new users](https://use.expensify.com/blog/earn-50000-by-referring-your-friends-to-expensify/) with the Expensify referral program, so your earning potential is truly sky-high.
-- **How will I know if I am the first person to refer a company to Expensify?**
+## Common questions about Expensify benefits
-Successful referrers are notified after their referral pays for 2 months of an annual subscription. We will check for the earliest recorded referrer of a user on the policy, and if that is you, then we will let you know.
+Still have questions about the Expensify referral program? We’ve got answers. Check out our FAQ below.
-- **How will you pay me if I am successful?**
+### How will I know if I am the first person to refer someone to Expensify?
-In the Spring 2023 campaign, Expensify will be paying successful referrers via direct deposit to the Deposit-Only account you have on file. Referral payouts will happen once a month for the duration of the campaign. If you do not have a Deposit-Only account at the time of your referral payout, your deposit will be processed in the next batch.
+You’ll know if you’re the first person to refer someone to Expensify if we reach out to let you know that they’ve successfully adopted Expensify and have paid for two months of an annual subscription.
-Learn how to add a Deposit-Only account [here](https://community.expensify.com/discussion/4641/how-to-add-a-deposit-only-bank-account-both-personal-and-business).
+Simply put, we check for the earliest recorded referrer of a member on the workspace, and if that’s you, then we’ll let you know.
-- **I’m outside of the US, how do I get paid?**
+### My referral wasn’t counted! How can I appeal?
-While our referral payouts are in USD, you will be able to get paid via a Wise Borderless account. Learn more [here](https://community.expensify.com/discussion/5940/how-to-get-reimbursed-outside-the-us-with-wise-for-non-us-employees).
+If you think your Expensify friend referral wasn’t counted, please send a message to concierge@expensify.com with the email of the person you referred. Our team will review the referral and get back to you.
-- **My referral wasn’t counted! How can I appeal?**
+## Share the Expensify love — and get paid in the process
-Expensify reserves the right to modify the terms of the referral program at any time, and pays out referral bonuses for eligible companies at its own discretion.
-
-Please send a message to concierge@expensify.com with the billing owner of the company you have referred and our team will review the referral and get back to you.
-
-- **Where can I find my referral link?**
-
-Expensify members who are opted-in for our newsletters will have received an email containing their unique referral link.
-
-On the mobile app, go to **Settings** > **Invite a Friend** > **Share Invite Link** to retrieve your referral link.
+Who needs a side hustle when you have Expensify? With Expensify benefits, it’s not just about managing your expenses — it's about expanding your income too. Share your Expensify referral link now or send over an invoice to unlock unlimited earning potential.
diff --git a/docs/articles/expensify-classic/get-paid-back/Trips.md b/docs/articles/expensify-classic/get-paid-back/Trips.md
index a65a8bfb8eec..ccfbe1592291 100644
--- a/docs/articles/expensify-classic/get-paid-back/Trips.md
+++ b/docs/articles/expensify-classic/get-paid-back/Trips.md
@@ -28,10 +28,12 @@ To view details about your past or upcoming trips, follow these steps within the
2. Navigate to the "Menu" option (top left ≡ icon)
3. Select **Trips**
-# FAQ
+{% include faq-begin.md %}
## How do I capture Trip receipts sent to my personal email address?
If you received your receipt in an email that is not associated with your Expensify account, you can add this email as a [secondary login](https://help.expensify.com/articles/expensify-classic/account-settings/Account-Details#how-to-add-a-secondary-login) to directly forward the receipt into your account.
## How do I upload Trip receipts that were not sent to me by email?
If your trip receipt was not sent to you by email, you can manually upload the receipt to your account. Check out this resource for more information on [manually uploading receipts](https://help.expensify.com/articles/expensify-classic/get-paid-back/expenses/Upload-Receipts#manually-upload).
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/get-paid-back/expenses/Apply-Tax.md b/docs/articles/expensify-classic/get-paid-back/expenses/Apply-Tax.md
index b5f5ec8be048..c89176bcc0e8 100644
--- a/docs/articles/expensify-classic/get-paid-back/expenses/Apply-Tax.md
+++ b/docs/articles/expensify-classic/get-paid-back/expenses/Apply-Tax.md
@@ -19,7 +19,7 @@ There may be multiple tax rates set up within your Workspace, so if the tax on y
If the tax amount on your receipt is different to the calculated amount or the tax rate doesn’t show up, you can always manually type in the correct tax amount.
-# FAQ
+{% include faq-begin.md %}
## How do I set up multiple taxes (GST/PST/QST) on indirect connections?
Expenses sometimes have more than one tax applied to them - for example in Canada, expenses can have both a Federal GST and a provincial PST or QST.
@@ -37,3 +37,4 @@ Many tax authorities do not require the reporting of tax amounts by rate and the
Alternatively, you can apply each specific tax rate by splitting the expense into the components that each rate will be applied to. To do this, click on **Split Expense** and apply the correct tax rate to each part.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/get-paid-back/expenses/Merge-Expenses.md b/docs/articles/expensify-classic/get-paid-back/expenses/Merge-Expenses.md
index a8444b98c951..a26146536e42 100644
--- a/docs/articles/expensify-classic/get-paid-back/expenses/Merge-Expenses.md
+++ b/docs/articles/expensify-classic/get-paid-back/expenses/Merge-Expenses.md
@@ -37,7 +37,7 @@ On the mobile app, merging is prompted when you see the message _"Potential dupl
If the expenses exist on two different reports, you will be asked which report you'd like the newly created single expense to be reported onto.
-# FAQ
+{% include faq-begin.md %}
## Can you merge expenses across different reports?
diff --git a/docs/articles/expensify-classic/get-paid-back/expenses/Upload-Receipts.md b/docs/articles/expensify-classic/get-paid-back/expenses/Upload-Receipts.md
index 29380dab5a5b..b0e3ee1b9ade 100644
--- a/docs/articles/expensify-classic/get-paid-back/expenses/Upload-Receipts.md
+++ b/docs/articles/expensify-classic/get-paid-back/expenses/Upload-Receipts.md
@@ -19,7 +19,7 @@ To SmartScan a receipt on your mobile app, tap the green camera button, point an
## Manually Upload
To upload receipts on the web, simply navigate to the Expenses page and click on **New Expense**. Select **Scan Receipt** and choose the file you would like to upload, or drag-and-drop your image directly into the Expenses page, and that will start the SmartScanning process!
-# FAQ
+{% include faq-begin.md %}
## How do you SmartScan multiple receipts?
You can utilize the Rapid Fire Mode to quickly SmartScan multiple receipts at once!
@@ -34,3 +34,5 @@ Once that email address has been added as a Secondary Login, simply forward your
You can crop and rotate a receipt image on the web app, and you can only edit one expense at a time.
Navigate to your Expenses page and locate the expense whose receipt image you'd like to edit, then click the expense to open the Edit screen. If there is an image file associated with the receipt, you will see the Rotate and Crop buttons. Alternatively, you can also navigate to your Reports page, click on a report, and locate the individual expense.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/get-paid-back/reports/Create-A-Report.md b/docs/articles/expensify-classic/get-paid-back/reports/Create-A-Report.md
index ea808695e7cd..88ec2b730d1e 100644
--- a/docs/articles/expensify-classic/get-paid-back/reports/Create-A-Report.md
+++ b/docs/articles/expensify-classic/get-paid-back/reports/Create-A-Report.md
@@ -147,7 +147,7 @@ As you go through each violation, click View to look at the expense in more deta
Click Next to move on to the next item.
Click Finish to complete the review process when you’re done.
-# FAQ
+{% include faq-begin.md %}
## Is there a difference between Expense Reports, Bills, and Invoices?
@@ -164,3 +164,5 @@ If someone external to the business sends you an invoice for their services, you
## When should I submit my report?
Your Company Admin can answer this one, and they may have configured the workspace’s [Scheduled Submit] setting to enforce a regular cadence for you. If not, you can still set this up under your [Individual workspace].
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/getting-started/Invite-Members.md b/docs/articles/expensify-classic/getting-started/Invite-Members.md
index 5b3c17c2e8fb..5a27f58cf2e8 100644
--- a/docs/articles/expensify-classic/getting-started/Invite-Members.md
+++ b/docs/articles/expensify-classic/getting-started/Invite-Members.md
@@ -51,7 +51,7 @@ Here's how it works: If a colleague signs up with a work email address that matc
To enable this feature, go to **Settings > Workspace > Group > *Workspace Name* > People**.
-# FAQ
+{% include faq-begin.md %}
## Who can invite members to Expensify
Any Workspace Admin can add members to a Group Workspace using any of the above methods.
@@ -60,3 +60,5 @@ Under **Settings > Workspace > Group > *Workspace Name* > People > Invite** you
## How can I invite members via the API?
If you would like to integrate an open API HR software, you can use our [Advanced Employee Updater API](https://integrations.expensify.com/Integration-Server/doc/employeeUpdater/) to invite members to your Workspace.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/getting-started/Plan-Types.md b/docs/articles/expensify-classic/getting-started/Plan-Types.md
index 90c632ffa5cc..4f8c52c2e1a1 100644
--- a/docs/articles/expensify-classic/getting-started/Plan-Types.md
+++ b/docs/articles/expensify-classic/getting-started/Plan-Types.md
@@ -20,7 +20,7 @@ The Track plan is tailored for solo Expensify users who don't require expense su
## Individual Submit Plan
The Submit plan is designed for individuals who need to keep track of their expenses and share them with someone else, such as their boss, accountant, or even a housemate. It's specifically tailored for single users who want to both track and submit their expenses efficiently.
-# FAQ
+{% include faq-begin.md %}
## How can I change Individual plans?
You have the flexibility to switch between a Track and Submit plan, or vice versa, at any time by navigating to **Settings > Workspaces > Individual > *Workspace Name* > Plan**. This allows you to adapt your expense management approach as needed.
@@ -30,3 +30,5 @@ You can easily upgrade from a Collect to a Control plan at any time by going to
## How does pricing work if I have two types of Group Workspace plans?
If you have a Control and Collect Workspace, you will be charged at the Control Workspace rate.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/getting-started/Tips-And-Tricks.md b/docs/articles/expensify-classic/getting-started/Tips-and-Tricks.md
similarity index 100%
rename from docs/articles/expensify-classic/getting-started/Tips-And-Tricks.md
rename to docs/articles/expensify-classic/getting-started/Tips-and-Tricks.md
diff --git a/docs/articles/expensify-classic/getting-started/approved-accountants/Card-Revenue-Share-For-Expensify-Approved-Partners.md b/docs/articles/expensify-classic/getting-started/approved-accountants/Card-Revenue-Share-For-Expensify-Approved-Partners.md
index a8e1b0690b72..189ff671b213 100644
--- a/docs/articles/expensify-classic/getting-started/approved-accountants/Card-Revenue-Share-For-Expensify-Approved-Partners.md
+++ b/docs/articles/expensify-classic/getting-started/approved-accountants/Card-Revenue-Share-For-Expensify-Approved-Partners.md
@@ -10,7 +10,7 @@ Start making more with us! We're thrilled to announce a new incentive for our US
# How-to
To benefit from this program, all you need to do is ensure that you are listed as a domain admin on your client's Expensify account. If you're not currently a domain admin, your client can follow the instructions outlined in [our help article](https://community.expensify.com/discussion/5749/how-to-add-and-remove-domain-admins#:~:text=Domain%20Admins%20have%20total%20control,a%20member%20of%20the%20domain.) to assign you this role.
-# FAQ
+{% include faq-begin.md %}
- What if my firm is not permitted to accept revenue share from our clients?
We understand that different firms may have different policies. If your firm is unable to accept this revenue share, you can pass the revenue share back to your client to give them an additional 0.5% of cash back using your own internal payment tools.
- What if my firm does not wish to participate in the program?
diff --git a/docs/articles/expensify-classic/getting-started/approved-accountants/Your-Expensify-Partner-Manager.md b/docs/articles/expensify-classic/getting-started/approved-accountants/Your-Expensify-Partner-Manager.md
index 104cd49daf96..fb3cb5341f61 100644
--- a/docs/articles/expensify-classic/getting-started/approved-accountants/Your-Expensify-Partner-Manager.md
+++ b/docs/articles/expensify-classic/getting-started/approved-accountants/Your-Expensify-Partner-Manager.md
@@ -22,7 +22,7 @@ You can contact your Partner Manager by:
- Signing in to new.expensify.com and searching for your Partner Manager
- Replying to or clicking the chat link on any email you get from your Partner Manager
-# FAQs
+{% include faq-begin.md %}
## How do I know if my Partner Manager is online?
You will be able to see if they are online via their status in new.expensify.com, which will either say “online” or have their working hours.
@@ -32,4 +32,6 @@ If you’re unable to contact your Partner Manager (i.e., they're out of office
## Can I get on a call with my Partner Manager?
Of course! You can ask your Partner Manager to schedule a call whenever you think one might be helpful. Partner Managers can discuss client onboarding strategies, firm wide training, and client setups.
-We recommend continuing to work with Concierge for **general support questions**, as this team is always online and available to help immediately.
\ No newline at end of file
+We recommend continuing to work with Concierge for **general support questions**, as this team is always online and available to help immediately.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/getting-started/support/Expensify-Support.md b/docs/articles/expensify-classic/getting-started/support/Expensify-Support.md
index f4a6acdd8571..870edf959b32 100644
--- a/docs/articles/expensify-classic/getting-started/support/Expensify-Support.md
+++ b/docs/articles/expensify-classic/getting-started/support/Expensify-Support.md
@@ -91,7 +91,7 @@ Your Partner Manager should reach out to you once you've completed ExpensifyAppr
- **Be Clear and Specific**: When asking questions or reporting issues, provide specific examples like affected users' email addresses or report IDs. This makes it easier for us to assist you effectively.
- **Practice Kindness**: Remember that we're here to help. Please be polite, considerate, and patient as we work together to resolve any concerns you have.
-# FAQ
+{% include faq-begin.md %}
## Who gets an Account Manager?
Members who have 10 or more active users, or clients of ExpensifyApproved! Accounts are automatically assigned a dedicated Account Manager.
@@ -115,3 +115,5 @@ We recommend working with Concierge on general support questions, as this team i
## Who gets assigned a Setup Specialist?
This feature is specifically for new members! Whenever you start a free trial, a product Setup Specialist will be assigned to guide you through configuring your Expensify account.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/insights-and-custom-reporting/Default-Export-Templates.md b/docs/articles/expensify-classic/insights-and-custom-reporting/Default-Export-Templates.md
index f6043aaea2eb..b89dca85df04 100644
--- a/docs/articles/expensify-classic/insights-and-custom-reporting/Default-Export-Templates.md
+++ b/docs/articles/expensify-classic/insights-and-custom-reporting/Default-Export-Templates.md
@@ -20,7 +20,7 @@ Below is a breakdown of the available default templates.
3. Click the **Export to** in the top right corner
4. Select the export template you’d like to use
-# FAQ
+{% include faq-begin.md %}
## Why are my numbers exporting in a weird format?
Do your numbers look something like this: 1.7976931348623157e+308? This means that your spreadsheet program is formatting long numbers in an exponential or scientific format. If that happens, you can correct it by changing the data to Plain Text or a Number in your spreadsheet program.
## Why are my leading zeros missing?
@@ -28,3 +28,4 @@ Is the export showing “1” instead of “01”? This means that your spreadsh
## I want a report that is not in the default list, how can I build that?
For a guide on building your own custom template check out Exports > Custom Exports in the Help pages!
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/insights-and-custom-reporting/Insights.md b/docs/articles/expensify-classic/insights-and-custom-reporting/Insights.md
index 6c71630015c5..ce07f4b56450 100644
--- a/docs/articles/expensify-classic/insights-and-custom-reporting/Insights.md
+++ b/docs/articles/expensify-classic/insights-and-custom-reporting/Insights.md
@@ -35,7 +35,7 @@ The Insights dashboard allows you to monitor all aspects of company spend across
2. Build up a report using these [formulas](https://community.expensify.com/discussion/5795/deep-dive-expense-level-formula/p1?new=1)
3. If you need any help, click the **Support** button on the top left to contact your Account Manager
-# FAQs
+{% include faq-begin.md %}
#### Can I share my custom export report?
@@ -98,4 +98,6 @@ We’ve built a huge variety of custom reports for customers, so make sure to re
- Unposted Travel Aging Report
- Vendor Spend
- … or anything you can imagine!
-{% endraw %}
\ No newline at end of file
+{% endraw %}
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/insights-and-custom-reporting/Other-Export-Options.md b/docs/articles/expensify-classic/insights-and-custom-reporting/Other-Export-Options.md
index 7ba84cef6b94..9d752dec3eb9 100644
--- a/docs/articles/expensify-classic/insights-and-custom-reporting/Other-Export-Options.md
+++ b/docs/articles/expensify-classic/insights-and-custom-reporting/Other-Export-Options.md
@@ -30,10 +30,12 @@ The PDF will include all expenses, any attached receipts, and all report notes.
3. Click on **Details** in the top right of the report
4. Click the **print icon**
-# FAQ
+{% include faq-begin.md %}
## Why isn’t my report exporting?
Big reports with lots of expenses may cause the PDF download to fail due to images with large resolutions. In that case, try breaking the report into multiple smaller reports. Also, please note that a report must have at least one expense to be exported or saved as a PDF.
## Can I download multiple PDFs at once?
No, you can’t download multiple reports as PDFs at the same time. If you’d like to export multiple reports, an alternative to consider is the CSV export option.
## The data exported to Excel is showing incorrectly. How can I fix this?
When opening a CSV file export from Expensify in Excel, it’ll automatically register report IDs and transaction IDs as numbers and assign the number format to the report ID column. If a number is greater than a certain length, Excel will contract the number and display it in exponential form. To prevent this, the number needs to be imported as text, which can be done by opening Excel and clicking File > Import > select your CSV file > follow the prompts and on step 3 set the report ID/transactionID column to import as Text.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/integrations/HR-integrations/ADP.md b/docs/articles/expensify-classic/integrations/HR-integrations/ADP.md
index 65b276796c2a..47cbd2fdc1f3 100644
--- a/docs/articles/expensify-classic/integrations/HR-integrations/ADP.md
+++ b/docs/articles/expensify-classic/integrations/HR-integrations/ADP.md
@@ -70,7 +70,7 @@ You can set Custom Fields and Payroll Codes in bulk using a CSV upload in Expens
If you have additional requirements for your ADP upload, for example, additional headings or datasets, reach out to your Expensify Account Manager who will assist you in customizing your ADP export. Expensify Account Managers are trained to accommodate your data requests and help you retrieve them from the system.
-# FAQ
+{% include faq-begin.md %}
- Do I need to convert my employee list into new column headings so I can upload it to Expensify?
@@ -79,3 +79,5 @@ Yes, you’ll need to convert your ADP employee data to the same headings as the
- Can I add special fields/items to my ADP Payroll Custom Export Format?
Yes! You can ask your Expensify Account Manager to help you prepare your ADP Payroll export so that it meets your specific requirements. Just reach out to them via the Chat option in Expensify and they’ll help you get set up.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/integrations/HR-integrations/Gusto.md b/docs/articles/expensify-classic/integrations/HR-integrations/Gusto.md
index f7a5127c9c0e..33a174325bf7 100644
--- a/docs/articles/expensify-classic/integrations/HR-integrations/Gusto.md
+++ b/docs/articles/expensify-classic/integrations/HR-integrations/Gusto.md
@@ -34,7 +34,7 @@ Expensify's direct integration with Gusto will automatically:
2. Click **Save** in the bottom right corner to sync employees into Expensify
3. If the connection is successful, you'll see a summary of how many employees were synced. If any employees were skipped, we'll tell you why.
-# FAQ
+{% include faq-begin.md %}
## Can I import different sets of employees into different Expensify workspaces?
No - Gusto will add all employees to one Expensify workspace, so if you have more than one workspace, you'll need to choose when connecting.
@@ -53,3 +53,5 @@ If your employees are set up in Expensify with their company emails, but with th
To resolve this, you can ask each affected employee to merge their existing Expensify account with the new Expensify account by navigating to **Settings > Account > Account Details** and scrolling down to **Merge Accounts**.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/integrations/accounting-integrations/Certinia.md b/docs/articles/expensify-classic/integrations/accounting-integrations/Certinia.md
index 0856e2694340..6c7014827ea6 100644
--- a/docs/articles/expensify-classic/integrations/accounting-integrations/Certinia.md
+++ b/docs/articles/expensify-classic/integrations/accounting-integrations/Certinia.md
@@ -87,7 +87,7 @@ When exporting to Certinia PSA/SRP you may see up to three different currencies
* Amount field on the Expense line: this currency is derived from the Expensify workspace default report currency.
* Reimbursable Amount on the Expense line: this currency is derived from the currency of the resource with an email matching the report submitter.
-# FAQ
+{% include faq-begin.md %}
## What happens if the report can’t be exported to Certinia?
* The preferred exporter will receive an email outlining the issue and any specific error messages
* Any error messages preventing the export from taking place will be recorded in the report’s history
@@ -148,3 +148,5 @@ Log into Certinia and go to Setup > Manage Users > Users and find the user whose
* Enable Modify All Data and save
Sync the connection within Expensify by going to **Settings** > **Workspaces** > **Groups** > _[Workspace Name]_ > **Connections** > **Sync Now** and then attempt to export the report again
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/integrations/accounting-integrations/Indirect-Accounting-Integrations.md b/docs/articles/expensify-classic/integrations/accounting-integrations/Indirect-Accounting-Integrations.md
index 852db0b7f7c0..09fad1b0ed1a 100644
--- a/docs/articles/expensify-classic/integrations/accounting-integrations/Indirect-Accounting-Integrations.md
+++ b/docs/articles/expensify-classic/integrations/accounting-integrations/Indirect-Accounting-Integrations.md
@@ -30,7 +30,7 @@ To export a report, click **Export To** in the top-left of a report and select y
To export multiple reports, tick the checkbox next to the reports on the **Reports** page, then click **Export To** and select your accounting package from the dropdown menu.
-# FAQ
+{% include faq-begin.md %}
## Which accounting packages offer this indirect integration with Expensify?
@@ -46,3 +46,5 @@ We support a pre-configured flat-file integration for the following accounting p
If your accounting package isn’t listed, but it still accepts a flat-file import, select **Other** when completing the Accounting Software task on your Home page or head to **Settings** > **Workspaces** > **Group** > _Your desired workspace_ > **Export Formats**. This option allows you to create your own templates to export your expense and report data into a format compatible with your accounting system.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/integrations/accounting-integrations/NetSuite.md b/docs/articles/expensify-classic/integrations/accounting-integrations/NetSuite.md
index 8092ed9c6dd6..3ce0d07cb65d 100644
--- a/docs/articles/expensify-classic/integrations/accounting-integrations/NetSuite.md
+++ b/docs/articles/expensify-classic/integrations/accounting-integrations/NetSuite.md
@@ -558,7 +558,7 @@ Here's how you can send them to us:
Send these two files to your Account Manager or Concierge so we can continue troubleshooting!
-# FAQ
+{% include faq-begin.md %}
## What type of Expensify plan is required for connecting to NetSuite?
@@ -573,3 +573,5 @@ If a report is exported to NetSuite and then marked as paid in NetSuite, the rep
## If I enable Auto Sync, what happens to existing approved and reimbursed reports?
If you previously had Auto Sync disabled but want to allow that feature to be used going forward, you can safely turn on Auto Sync without affecting existing reports. Auto Sync will only take effect for reports created after enabling that feature.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/integrations/accounting-integrations/QuickBooks-Desktop.md b/docs/articles/expensify-classic/integrations/accounting-integrations/QuickBooks-Desktop.md
index 958e423273ce..8fe31f3ec4f4 100644
--- a/docs/articles/expensify-classic/integrations/accounting-integrations/QuickBooks-Desktop.md
+++ b/docs/articles/expensify-classic/integrations/accounting-integrations/QuickBooks-Desktop.md
@@ -88,7 +88,7 @@ You can bring in Customers/Projects from QuickBooks into Expensify in two ways:
## Items
Items can be imported from QuickBooks as categories alongside your expense accounts.
-# FAQ
+{% include faq-begin.md %}
## How do I sync my connection?
1: Ensure that both the Expensify Sync Manager and QuickBooks Desktop are running.
2: On the Expensify website, navigate to **Settings** > **Policies** > **Group** > _[Policy Name]_ > **Connections** > **QuickBooks Desktop**, and click **Sync now**.
@@ -143,3 +143,5 @@ To resolve this error, follow these steps:
Verify that the Sync Manager's status is **Connected**.
3. If the Sync Manager status is already **Connected**, click **Edit** and then *Save* to refresh the connection. Afterwards, try syncing your policy again.
4. If the error persists, double-check that the token you see in the Sync Manager matches the token in your connection settings.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/integrations/accounting-integrations/QuickBooks-Online.md b/docs/articles/expensify-classic/integrations/accounting-integrations/QuickBooks-Online.md
index 4075aaf18016..623e5f1dd997 100644
--- a/docs/articles/expensify-classic/integrations/accounting-integrations/QuickBooks-Online.md
+++ b/docs/articles/expensify-classic/integrations/accounting-integrations/QuickBooks-Online.md
@@ -302,7 +302,7 @@ Here are the QuickBooks Online fields that can be mapped as a report field withi
- Customers/Projects
- Locations
-# FAQ
+{% include faq-begin.md %}
## What happens if the report can't be exported to QuickBooks Online automatically?
@@ -320,3 +320,5 @@ To ensure reports are reviewed before export, set up your Workspaces with the ap
- If a report has been exported and reimbursed via ACH, it will be automatically marked as paid in QuickBooks Online during the next sync.
- If a report has been exported and marked as paid in QuickBooks Online, it will be automatically marked as reimbursed in Expensify during the next sync.
- Reports that have yet to be exported to QuickBooks Online won't be automatically exported.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/integrations/accounting-integrations/Sage-Intacct.md b/docs/articles/expensify-classic/integrations/accounting-integrations/Sage-Intacct.md
index ac0a90ba6d37..560a65d0d722 100644
--- a/docs/articles/expensify-classic/integrations/accounting-integrations/Sage-Intacct.md
+++ b/docs/articles/expensify-classic/integrations/accounting-integrations/Sage-Intacct.md
@@ -550,7 +550,7 @@ When ACH reimbursement is enabled, the "Sync Reimbursed Reports" feature will ad
Intacct requires that the target account for the Bill Payment be a Cash and Cash Equivalents account type. If you aren't seeing the account you want in that list, please first confirm that the category on the account is Cash and Cash Equivalents.
-# FAQ
+{% include faq-begin.md %}
## What if my report isn't automatically exported to Sage Intacct?
There are a number of factors that can cause automatic export to fail. If this happens, the preferred exporter will receive an email and an Inbox task outlining the issue and any associated error messages.
The same information will be populated in the comments section of the report.
@@ -566,3 +566,5 @@ If your workspace has been connected to Intacct with Auto Sync disabled, you can
If a report has been exported to Intacct and reimbursed via ACH in Expensify, we'll automatically mark it as paid in Intacct during the next sync.
If a report has been exported to Intacct and marked as paid in Intacct, we'll automatically mark it as reimbursed in Expensify during the next sync.
If a report has not been exported to Intacct, it will not be exported to Intacct automatically.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/integrations/accounting-integrations/Xero.md b/docs/articles/expensify-classic/integrations/accounting-integrations/Xero.md
index 98cc6f2bfdf6..9dd479e90cf1 100644
--- a/docs/articles/expensify-classic/integrations/accounting-integrations/Xero.md
+++ b/docs/articles/expensify-classic/integrations/accounting-integrations/Xero.md
@@ -236,7 +236,7 @@ If we can't find a match, we'll create a new customer record in Xero.
And that's it! You've successfully set up and managed your invoice exports to Xero, making your tracking smooth and efficient.
-# FAQ
+{% include faq-begin.md %}
## Will receipt images be exported to Xero?
@@ -258,3 +258,5 @@ It will be automatically marked as reimbursed in Expensify during the next sync.
Reports that haven't been exported to Xero won't be sent automatically.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/integrations/travel-integrations/Additional-Travel-Integrations.md b/docs/articles/expensify-classic/integrations/travel-integrations/Additional-Travel-Integrations.md
index ac37a01b3e6b..7dcc8e5e9c29 100644
--- a/docs/articles/expensify-classic/integrations/travel-integrations/Additional-Travel-Integrations.md
+++ b/docs/articles/expensify-classic/integrations/travel-integrations/Additional-Travel-Integrations.md
@@ -52,7 +52,7 @@ You can automatically import receipts from many travel platforms into Expensify,
- From your account settings, choose whether expenses should be sent to Expensify automatically or manually.
- We recommend sending them automatically, so you can travel without even thinking about your expense reports.
-# FAQ
+{% include faq-begin.md %}
**Q: What if I don’t have the option for Send to Expensify in Trainline?**
@@ -69,3 +69,5 @@ A: Yes, you can set a weekly or monthly cadence for SpotHero expenses to be emai
**Q: Do I need to select a specific profile before booking in Bolt Work and Grab?**
A: Yes, ensure you have selected your work or business profile as the payment method before booking.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/integrations/travel-integrations/Navan.md b/docs/articles/expensify-classic/integrations/travel-integrations/Navan.md
index 237047fa270e..b1bf3c9745ff 100644
--- a/docs/articles/expensify-classic/integrations/travel-integrations/Navan.md
+++ b/docs/articles/expensify-classic/integrations/travel-integrations/Navan.md
@@ -20,7 +20,7 @@ Once you complete these steps, any flights you book through Navan will automatic
If you booked your Navan flight using your Expensify Card, the Navan expense will automatically merge with the card expense. Learn more about the Expensify Card [here](https://use.expensify.com/company-credit-card).
-# FAQ
+{% include faq-begin.md %}
## How do I expense a prepaid hotel booking in Expensify using the Navan integration?
Bookings that weren’t made in Navan directly (such as a prepaid hotel booking) won’t auto-import into Expensify. To import these trips into Expensify, follow these steps:
@@ -45,3 +45,5 @@ Costs depend on your subscription plans with Expensify and Navan. Expensify does
## How do I disconnect the integration?
To disconnect the integration, navigate to the integrations section in Navan, find Expensify, and select the option to disable the integration.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/manage-employees-and-report-approvals/Removing-Members.md b/docs/articles/expensify-classic/manage-employees-and-report-approvals/Removing-Members.md
index 33ffe7172603..65acc3630582 100644
--- a/docs/articles/expensify-classic/manage-employees-and-report-approvals/Removing-Members.md
+++ b/docs/articles/expensify-classic/manage-employees-and-report-approvals/Removing-Members.md
@@ -13,7 +13,7 @@ Removing a member from a workspace disables their ability to use the workspace.
![image of members table in a workspace]({{site.url}}/assets/images/ExpensifyHelp_RemovingMembers.png){:width="100%"}
-# FAQ
+{% include faq-begin.md %}
## Will reports from this member on this workspace still be available?
Yes, as long as the reports have been submitted. You can navigate to the Reports page and enter the member's email in the search field to find them. However, Draft reports will be removed from the workspace, so these will no longer be visible to the Workspace Admin.
@@ -34,3 +34,5 @@ If a member is a **preferred exporter, billing owner, report approver** or has *
## How do I remove a user completely from a company account?
If you have a Control Workspace and have Domain Control enabled, you will need to remove them from the domain to delete members' accounts entirely and deactivate the Expensify Card.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/manage-employees-and-report-approvals/Vacation-Delegate.md b/docs/articles/expensify-classic/manage-employees-and-report-approvals/Vacation-Delegate.md
index 7c21b12a83e1..4727b1c4a38b 100644
--- a/docs/articles/expensify-classic/manage-employees-and-report-approvals/Vacation-Delegate.md
+++ b/docs/articles/expensify-classic/manage-employees-and-report-approvals/Vacation-Delegate.md
@@ -38,7 +38,7 @@ Your delegate's actions will be noted in the history and comments of each report
The system records every action your vacation delegate takes on your behalf in the **Report History and Comments**. So, you can see when they approved an expense report for you.
-# FAQs
+{% include faq-begin.md %}
## Why can't my Vacation Delegate reimburse reports that they approve?
@@ -50,5 +50,4 @@ If they do not have access to the reimbursement account used on your workspace,
Don't worry, your delegate can also pick their own **Vacation Delegate**. This way, expense reports continue to get approved even if multiple people are away.
-
-
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/send-payments/Pay-Bills.md b/docs/articles/expensify-classic/send-payments/Pay-Bills.md
index 8a5c7c5c7f88..81dcf3488462 100644
--- a/docs/articles/expensify-classic/send-payments/Pay-Bills.md
+++ b/docs/articles/expensify-classic/send-payments/Pay-Bills.md
@@ -70,7 +70,17 @@ To mark a Bill as paid outside of Expensify:
**Fees:** None
-# FAQ
+# Deep Dive: How company bills and vendor invoices are processed in Expensify
+
+Here is how a vendor or supplier bill goes from received to paid in Expensify:
+
+1. When a vendor or supplier bill is received in Expensify via, the document is SmartScanned automatically and a Bill is created. The Bill is owned by the primary domain contact, who will see the Bill on the Reports page on their default group policy.
+2. When the Bill is ready for processing, it is submitted and follows the primary domain contact’s approval workflow. Each time the Bill is approved, it is visible in the next approver's Inbox.
+3. The final approver pays the Bill from their Expensify account on the web via one of the methods.
+4. The Bill is coded with the relevant imported GL codes from a connected accounting software. After it has finished going through the approval workflow the Bill can be exported back to the accounting package connected to the policy.
+
+
+{% include faq-begin.md %}
## What is my company's billing intake email?
Your billing intake email is [yourdomain.com]@expensify.cash. Example, if your domain is `company.io` your billing email is `company.io@expensify.cash`.
@@ -100,11 +110,4 @@ Payments are currently only supported for users paying in United States Dollars
A Bill is a payable which represents an amount owed to a payee (usually a vendor or supplier), and is usually created from a vendor invoice. An Invoice is a receivable, and indicates an amount owed to you by someone else.
-# Deep Dive: How company bills and vendor invoices are processed in Expensify
-
-Here is how a vendor or supplier bill goes from received to paid in Expensify:
-
-1. When a vendor or supplier bill is received in Expensify via, the document is SmartScanned automatically and a Bill is created. The Bill is owned by the primary domain contact, who will see the Bill on the Reports page on their default group policy.
-2. When the Bill is ready for processing, it is submitted and follows the primary domain contact’s approval workflow. Each time the Bill is approved, it is visible in the next approver's Inbox.
-3. The final approver pays the Bill from their Expensify account on the web via one of the methods.
-4. The Bill is coded with the relevant imported GL codes from a connected accounting software. After it has finished going through the approval workflow the Bill can be exported back to the accounting package connected to the policy.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/send-payments/Reimbursing-Reports.md b/docs/articles/expensify-classic/send-payments/Reimbursing-Reports.md
index e55d99d70827..69b39bae2874 100644
--- a/docs/articles/expensify-classic/send-payments/Reimbursing-Reports.md
+++ b/docs/articles/expensify-classic/send-payments/Reimbursing-Reports.md
@@ -19,6 +19,8 @@ To reimburse directly in Expensify, the following needs to be already configured
If all of those settings are in place, to reimburse a report, you will click **Reimburse** on the report and then select **Via Direct Deposit (ACH)**.
+![Reimbursing Reports Dropdown]({{site.url}}/assets/images/Reimbursing Reports Dropdown.png){:width="100%"}
+
## Indirect or Manual Reimbursement
If you don't have the option to utilize direct reimbursement, you can choose to mark a report as reimbursed by clicking the **Reimburse** button at the top of the report and then selecting **I’ll do it manually – just mark as reimbursed**.
@@ -63,7 +65,7 @@ If either limit has been reached, you can expect funds deposited within your ban
Rapid Reimbursement is not available for non-US-based reimbursement. If you are receiving a reimbursement to a non-US-based deposit account, you should expect to see the funds deposited in your bank account within four business days.
-# FAQ
+{% include faq-begin.md %}
## Who can reimburse reports?
Only a workspace admin who has added a verified business bank account to their Expensify account can reimburse employees.
@@ -73,3 +75,7 @@ Only a workspace admin who has added a verified business bank account to their E
Instead of a bulk reimbursement option, you can set up automatic reimbursement. With this configured, reports below a certain threshold (defined by you) will be automatically reimbursed via ACH as soon as they're "final approved."
To set your manual reimbursement threshold, head to **Settings > Workspace > Group > _[Workspace Name]_ > Reimbursement > Manual Reimbursement**.
+
+![Manual Reimbursement]({{site.url}}/assets/images/Reimbursing Manual.png){:width="100%"}
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/send-payments/Third-Party-Payments.md b/docs/articles/expensify-classic/send-payments/Third-Party-Payments.md
index 1a567dbe6fa3..cae289a0526a 100644
--- a/docs/articles/expensify-classic/send-payments/Third-Party-Payments.md
+++ b/docs/articles/expensify-classic/send-payments/Third-Party-Payments.md
@@ -42,7 +42,7 @@ Once you've set up your third party payment option, you can start using it to re
4. **Track Payment Status**: You can track the status of payments and view transaction details within your Expensify account.
-# FAQ’s
+{% include faq-begin.md %}
## Q: Are there any fees associated with using third party payment options in Expensify?
@@ -57,3 +57,5 @@ A: Expensify allows you to link multiple payment providers if needed. You can se
A: The reimbursement limit may depend on the policies and settings configured within your Expensify account and the limits imposed by your chosen payment provider.
With Expensify's third party payment options, you can simplify your expense management and reimbursement processes. By following the steps outlined in this guide, you can set up and use third party payments efficiently.
+
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/workspace-and-domain-settings/Budgets.md b/docs/articles/expensify-classic/workspace-and-domain-settings/Budgets.md
index 3c5bc0fe2421..30adac589dc0 100644
--- a/docs/articles/expensify-classic/workspace-and-domain-settings/Budgets.md
+++ b/docs/articles/expensify-classic/workspace-and-domain-settings/Budgets.md
@@ -42,7 +42,7 @@ Expensify’s Budgets feature allows you to:
- **Per individual budget**: you can enter an amount if you want to set a budget per person
- **Notification threshold** - this is the % in which you will be notified as the budgets are hit
-# FAQ
+{% include faq-begin.md %}
## Can I import budgets as a CSV?
At this time, you cannot import budgets via CSV since we don’t import categories or tags from direct accounting integrations.
@@ -54,3 +54,4 @@ Notifications are sent twice:
## How will I be notified when a budget is hit?
A message will be sent in the #admins room of the Workspace.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/workspace-and-domain-settings/Categories.md b/docs/articles/expensify-classic/workspace-and-domain-settings/Categories.md
index 783bd50f17a3..0cd7ba790a9c 100644
--- a/docs/articles/expensify-classic/workspace-and-domain-settings/Categories.md
+++ b/docs/articles/expensify-classic/workspace-and-domain-settings/Categories.md
@@ -143,7 +143,7 @@ Category violations can happen for the following reasons:
If Scheduled Submit is enabled on a workspace, expenses with category violations will not be auto-submitted unless the expense has a comment added.
-# FAQ
+{% include faq-begin.md %}
## The correct category list isn't showing when one of my employees is categorizing their expenses. Why is this happening?
Its possible the employee is defaulted to their personal workspace so the expenses are not pulling the correct categories to choose from. Check to be sure the report is listed under the correct workspace by looking under the details section on top right of report.
@@ -151,3 +151,4 @@ Its possible the employee is defaulted to their personal workspace so the expens
## Will the account numbers from our accounting system (QuickBooks Online, Sage Intacct, etc.) show in the Category list when employees are choosing what chart of accounts category to code their expense to?
The GL account numbers will be visible in the workspace settings when connected to a Control-level workspace for workspace admins to see. We do not provide this information in an employee-facing capacity because most employees do not have access to that information within the accounting integration.
If you wish to have this information available to your employees when they are categorizing their expenses, you can edit the account name in your accounting software to include the GL number — i.e. **Accounts Payable - 12345**
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/workspace-and-domain-settings/Domains-Overview.md b/docs/articles/expensify-classic/workspace-and-domain-settings/Domains-Overview.md
index cf2f0f59a4a0..6cafe3dccfaf 100644
--- a/docs/articles/expensify-classic/workspace-and-domain-settings/Domains-Overview.md
+++ b/docs/articles/expensify-classic/workspace-and-domain-settings/Domains-Overview.md
@@ -131,10 +131,11 @@ To enable SAML SSO in Expensify you will first need to claim and verify your dom
- For disputing digital Expensify Card purchases, two-factor authentication must be enabled.
- It might take up to 2 hours for domain-level enforcement to take effect, and users will be prompted to configure their individual 2FA settings on their next login to Expensify.
-# FAQ
+{% include faq-begin.md %}
## How many domains can I have?
You can manage multiple domains by adding them through **Settings > Domains > New Domain**. However, to verify additional domains, you must be a Workspace Admin on a Control Workspace. Keep in mind that the Collect plan allows verification for just one domain.
## What’s the difference between claiming a domain and verifying a domain?
Claiming a domain is limited to users with matching email domains, and allows Workspace Admins with a company email to manage bills, company cards, and reconciliation. Verifying a domain offers extra features and security.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/workspace-and-domain-settings/Expenses.md b/docs/articles/expensify-classic/workspace-and-domain-settings/Expenses.md
index 388bb5d5cbc9..ea701dc09d3e 100644
--- a/docs/articles/expensify-classic/workspace-and-domain-settings/Expenses.md
+++ b/docs/articles/expensify-classic/workspace-and-domain-settings/Expenses.md
@@ -106,7 +106,7 @@ If you enable tax but don’t select a tax rate or enter a tax reclaimable amoun
Note: _Expensify won’t automatically track cumulative mileage. If you need to track cumulative mileage per employee, we recommend building a mileage report using our custom export formulas._
-# FAQs
+{% include faq-begin.md %}
## Why do I see eReceipts for expenses greater than $75?
@@ -116,3 +116,4 @@ An eReceipt is generated for Expensify card purchases of any amount in the follo
Expensify does not update mileage rates to match the rate provided by the IRS. An admin of the workspace will need to update the rate or create a new rate in the workspace. This is because Expensify has customers worldwide, not just in the United States, and most companies want to communicate the change with employees and control the timing.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/workspace-and-domain-settings/Per-Diem.md b/docs/articles/expensify-classic/workspace-and-domain-settings/Per-Diem.md
index fcb1c8018613..87aef233aeb1 100644
--- a/docs/articles/expensify-classic/workspace-and-domain-settings/Per-Diem.md
+++ b/docs/articles/expensify-classic/workspace-and-domain-settings/Per-Diem.md
@@ -86,7 +86,7 @@ When you _Export to CSV_, Expensify also assigns a Rate ID to each existing rate
Note: _This rate ID corresponds to the Destination+Subrate. You cannot overwrite Destinations, but you can overwrite the Subrate within a Destination by using this rate ID. Always use the “Clear Rate” option with a fresh upload when removing large numbers of rates rather than deleting them individually._
-# FAQs
+{% include faq-begin.md %}
## How do I report on my team's Per Diem expenses?
@@ -95,3 +95,4 @@ Great question! We’ve added a Per Diem export for users to export Per Diem exp
## What if I need help setting the exact rate amounts and currencies?
Right now, Expensify can't help determine what these should be. They vary widely based on your country of origin, the state within that jurisdiction, your company workspace, and the time (usually year) you traveled. There's a demonstration spreadsheet [here](https://s3-us-west-1.amazonaws.com/concierge-responses-expensify-com/uploads%2F1596692482998-Germany+-+Per+Diem.csv), but it shouldn't be used for actual claims unless verified by your internal finance team or accountants.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/workspace-and-domain-settings/Reimbursement.md b/docs/articles/expensify-classic/workspace-and-domain-settings/Reimbursement.md
index a1916465fca8..ed2384d12006 100644
--- a/docs/articles/expensify-classic/workspace-and-domain-settings/Reimbursement.md
+++ b/docs/articles/expensify-classic/workspace-and-domain-settings/Reimbursement.md
@@ -32,7 +32,7 @@ A Workspace admin can enanble indirect reimbursement via **Settings > Workspaces
**Additional features under Reimbursement > Indirect:**
If you reimburse through a seperate system or through payroll, Expensify can collect and export employee bank account details for you. Just reach out to your Account Manager or concierge@expensify.com for us to add the Reimbursement Details Export format to the account.
-# FAQ
+{% include faq-begin.md %}
## How do I export employee bank account details once the Reimbursement Details Export format is added to my account?
@@ -45,3 +45,4 @@ Bank account names can be updated via **Settings > Accounts > Payments** and cli
## What is the benefit of setting a default reimburser?
The main benefit of being defined as the "reimburser" in the Workspace settings is that this user will receive notifications on their Home page alerting them when reports need to be reimbursed.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/workspace-and-domain-settings/SAML-SSO.md b/docs/articles/expensify-classic/workspace-and-domain-settings/SAML-SSO.md
index 758cb70067e1..e4b27b238e46 100644
--- a/docs/articles/expensify-classic/workspace-and-domain-settings/SAML-SSO.md
+++ b/docs/articles/expensify-classic/workspace-and-domain-settings/SAML-SSO.md
@@ -77,7 +77,7 @@ To enable SSO with Microsoft ADFS follow these steps:
Assuming you’ve also set up Expensify SAML configuration with your metadata, SAML logins on Expensify.com should now work. For reference, ADFS’ default metadata path is: https://yourservicename.yourdomainname.com/FederationMetadata/2007-06/FederationMetadata.xml.
-# FAQ
+{% include faq-begin.md %}
## What should I do if I’m getting an error when trying to set up SSO?
You can double check your configuration data for errors using samltool.com. If you’re still having issues, you can reach out to your Account Manager or contact Concierge for assistance.
@@ -87,3 +87,4 @@ The entityID for Expensify is https://expensify.com. Remember not to copy and pa
## Can you have multiple domains with only one entityID?
Yes. Please send a message to Concierge or your account manager and we will enable the ability to use the same entityID with multiple domains.
+{% include faq-end.md %}
diff --git a/docs/articles/expensify-classic/workspace-and-domain-settings/Tags.md b/docs/articles/expensify-classic/workspace-and-domain-settings/Tags.md
index 2e6bd335ce4c..d802a183c8ba 100644
--- a/docs/articles/expensify-classic/workspace-and-domain-settings/Tags.md
+++ b/docs/articles/expensify-classic/workspace-and-domain-settings/Tags.md
@@ -78,7 +78,7 @@ Alternatively, if you update the tag details in your accounting integration, be
# Deep Dive
## Make tags required
You can require tags for any workspace expenses by enabling People must tag expenses on the Tags page by navigating to Settings > Workspace > Group > [Workspace Name] > Tags.
-# FAQ
+{% include faq-begin.md %}
## What are the different tag options?
If you want your second tag to depend on the first one, use dependent tags. Include GL codes if needed, especially when using accounting integrations.
@@ -91,4 +91,4 @@ Multi-level tagging is only available with the Control type policy.
## I can’t see "Do you want to use multiple level tags" feature on my company's expense workspace. Why is that?
If you are connected to an accounting integration, you will not see this feature. You will need to add those tags in your integration first, then sync the connection.
-
+{% include faq-end.md %}
diff --git a/docs/articles/new-expensify/bank-accounts/Connect-a-Bank-Account.md b/docs/articles/new-expensify/bank-accounts/Connect-a-Bank-Account.md
index de66315f2d79..307641c9c605 100644
--- a/docs/articles/new-expensify/bank-accounts/Connect-a-Bank-Account.md
+++ b/docs/articles/new-expensify/bank-accounts/Connect-a-Bank-Account.md
@@ -114,7 +114,7 @@ If you get a generic error message that indicates, "Something's gone wrong", ple
8. If you have another phone available, try to follow these steps on that device
If the issue persists, please contact your Account Manager or Concierge for further troubleshooting assistance.
-# FAQ
+{% include faq-begin.md %}
## What is a Beneficial Owner?
A Beneficial Owner refers to an **individual** who owns 25% or more of the business. If no individual owns 25% or more of the business, the company does not have a Beneficial Owner.
@@ -140,3 +140,4 @@ It's a good idea to wait till the end of that second business day. If you still
Make sure to reach out to your Account Manager or Concierge once that's all set, and our team will be able to re-trigger those three test transactions!
+{% include faq-end.md %}
diff --git a/docs/articles/new-expensify/billing-and-plan-types/The-Free-Plan.md b/docs/articles/new-expensify/billing-and-plan-types/The-Free-Plan.md
index 3b79072aa393..b036c5b087d2 100644
--- a/docs/articles/new-expensify/billing-and-plan-types/The-Free-Plan.md
+++ b/docs/articles/new-expensify/billing-and-plan-types/The-Free-Plan.md
@@ -60,7 +60,7 @@ Request an edit an expense or remove an expense before you pay, you can let your
- Automatic submission is already set up, so your admin can pay you back immediately once you create an expense.
- Your admin will get a notification when you send them a new expense, but you can also remind them to pay you by making a comment in the Report History section of your Processing report or chatting with them on new.expensify.com.
-# FAQs
+{% include faq-begin.md %}
## Do I need a business bank account to use the Free Plan?
@@ -145,3 +145,5 @@ Depending on how quickly you report it to us, we may be able to help cancel a re
## As an admin, can I edit users’ expenses and delete them from reports?
No. Only users can edit and delete expenses on the Free plan. Admin control of submitted expenses on a workspace is a feature of our paid plans. If you need something changed, let the user know by commenting in the Report History section of the report on www.expensify.com or by chatting with them in new.expensify.com.
+
+{% include faq-end.md %}
diff --git a/docs/articles/new-expensify/chat/Introducing-Expensify-Chat.md b/docs/articles/new-expensify/chat/Introducing-Expensify-Chat.md
index 25ccdefad261..c7ae49e02292 100644
--- a/docs/articles/new-expensify/chat/Introducing-Expensify-Chat.md
+++ b/docs/articles/new-expensify/chat/Introducing-Expensify-Chat.md
@@ -136,7 +136,7 @@ You will receive a whisper from Concierge any time your content has been flagged
*Note: Any message sent in public chat rooms are automatically reviewed by an automated system looking for offensive content and sent to our moderators for final decisions if it is found.*
-# FAQs
+{% include faq-begin.md %}
## What are the #announce and #admins rooms?
@@ -162,3 +162,4 @@ The way your chats display in the left-hand menu is customizable. We offer two d
- #focus mode will display only unread and pinned chats, and will sort them alphabetically. This setting is perfect for when you need to cut distractions and focus on a crucial project.
You can find your display mode by clicking on your Profile > Preferences > Priority Mode.
+{% include faq-end.md %}
diff --git a/docs/articles/new-expensify/payments/Distance-Requests.md b/docs/articles/new-expensify/payments/Distance-Requests.md
index 91b88409be8b..899cb48fd1f5 100644
--- a/docs/articles/new-expensify/payments/Distance-Requests.md
+++ b/docs/articles/new-expensify/payments/Distance-Requests.md
@@ -20,8 +20,9 @@ Expensify allows you to request reimbursement for mileage by creating a distance
-# FAQs
+{% include faq-begin.md %}
## Is there an easy way to reuse recent locations?
Yes! We save your recently used locations and list them out on the page where you select the Start and Finish.
+{% include faq-end.md %}
diff --git a/docs/articles/new-expensify/payments/Referral-Program.md b/docs/articles/new-expensify/payments/Referral-Program.md
index 6ffb923aeb76..a1b1043dff47 100644
--- a/docs/articles/new-expensify/payments/Referral-Program.md
+++ b/docs/articles/new-expensify/payments/Referral-Program.md
@@ -31,7 +31,7 @@ The sky's the limit for this referral program! Your referral can be anyone - a f
For now, referral rewards will be paid via direct deposit into bank accounts that are connected to Expensify.
-# FAQ
+{% include faq-begin.md %}
- **How will I know if I'm the first person to refer a company to Expensify?**
@@ -54,3 +54,4 @@ Expensify reserves the right to modify the terms of the referral program at any
- **Where can I find my referral link?**
In New Expensify, go to **Settings** > **Share code** > **Get $250** to retrieve your invite link.
+{% include faq-end.md %}
diff --git a/docs/articles/new-expensify/payments/Request-Money.md b/docs/articles/new-expensify/payments/Request-Money.md
index 43a72a075de7..9aac4787484c 100644
--- a/docs/articles/new-expensify/payments/Request-Money.md
+++ b/docs/articles/new-expensify/payments/Request-Money.md
@@ -31,6 +31,7 @@ These two features ensure you can live in the moment and settle up afterward.
- Enter a reason for the split
- The split is then shared equally between the attendees
-# FAQs
+{% include faq-begin.md %}
## Can I request money from more than one person at a time?
If you need to request money for more than one person at a time, you’ll want to use the Split Bill feature. The Request Money option is for one-to-one payments between two people.
+{% include faq-end.md %}
diff --git a/docs/articles/new-expensify/workspace-and-domain-settings/Domain-Settings-Overview.md b/docs/articles/new-expensify/workspace-and-domain-settings/Domain-Settings-Overview.md
index cf2f0f59a4a0..40d759479390 100644
--- a/docs/articles/new-expensify/workspace-and-domain-settings/Domain-Settings-Overview.md
+++ b/docs/articles/new-expensify/workspace-and-domain-settings/Domain-Settings-Overview.md
@@ -131,10 +131,12 @@ To enable SAML SSO in Expensify you will first need to claim and verify your dom
- For disputing digital Expensify Card purchases, two-factor authentication must be enabled.
- It might take up to 2 hours for domain-level enforcement to take effect, and users will be prompted to configure their individual 2FA settings on their next login to Expensify.
-# FAQ
+{% include faq-begin.md %}
## How many domains can I have?
You can manage multiple domains by adding them through **Settings > Domains > New Domain**. However, to verify additional domains, you must be a Workspace Admin on a Control Workspace. Keep in mind that the Collect plan allows verification for just one domain.
## What’s the difference between claiming a domain and verifying a domain?
Claiming a domain is limited to users with matching email domains, and allows Workspace Admins with a company email to manage bills, company cards, and reconciliation. Verifying a domain offers extra features and security.
+
+{% include faq-end.md %}
diff --git a/ios/NewExpensify/Info.plist b/ios/NewExpensify/Info.plist
index f58687c66c63..2dc6d59d5e4f 100644
--- a/ios/NewExpensify/Info.plist
+++ b/ios/NewExpensify/Info.plist
@@ -19,7 +19,7 @@
CFBundlePackageType
APPL
CFBundleShortVersionString
- 1.4.22
+ 1.4.24
CFBundleSignature
????
CFBundleURLTypes
@@ -40,7 +40,7 @@
CFBundleVersion
- 1.4.22.3
+ 1.4.24.4
ITSAppUsesNonExemptEncryption
LSApplicationQueriesSchemes
diff --git a/ios/NewExpensifyTests/Info.plist b/ios/NewExpensifyTests/Info.plist
index b7b8c9d3416b..5f68b5ba2579 100644
--- a/ios/NewExpensifyTests/Info.plist
+++ b/ios/NewExpensifyTests/Info.plist
@@ -15,10 +15,10 @@
CFBundlePackageType
BNDL
CFBundleShortVersionString
- 1.4.22
+ 1.4.24
CFBundleSignature
????
CFBundleVersion
- 1.4.22.3
+ 1.4.24.4
diff --git a/ios/NotificationServiceExtension/Info.plist b/ios/NotificationServiceExtension/Info.plist
index 57421ebf9b75..ccc7422fe3b4 100644
--- a/ios/NotificationServiceExtension/Info.plist
+++ b/ios/NotificationServiceExtension/Info.plist
@@ -9,5 +9,9 @@
NSExtensionPrincipalClass
$(PRODUCT_MODULE_NAME).NotificationService
+ CFBundleVersion
+ 1.4.23.0
+ CFBundleShortVersionString
+ 1.4.23
-
+
\ No newline at end of file
diff --git a/ios/Podfile.lock b/ios/Podfile.lock
index ee54d98895a5..77c390c46416 100644
--- a/ios/Podfile.lock
+++ b/ios/Podfile.lock
@@ -614,7 +614,7 @@ PODS:
- React-Core
- react-native-pager-view (6.2.0):
- React-Core
- - react-native-pdf (6.7.4):
+ - react-native-pdf (6.7.3):
- React-Core
- react-native-performance (5.1.0):
- React-Core
@@ -1265,7 +1265,7 @@ SPEC CHECKSUMS:
react-native-key-command: 5af6ee30ff4932f78da6a2109017549042932aa5
react-native-netinfo: ccbe1085dffd16592791d550189772e13bf479e2
react-native-pager-view: 0ccb8bf60e2ebd38b1f3669fa3650ecce81db2df
- react-native-pdf: 79aa75e39a80c1d45ffe58aa500f3cf08f267a2e
+ react-native-pdf: b4ca3d37a9a86d9165287741c8b2ef4d8940c00e
react-native-performance: cef2b618d47b277fb5c3280b81a3aad1e72f2886
react-native-plaid-link-sdk: df1618a85a615d62ff34e34b76abb7a56497fbc1
react-native-quick-sqlite: bcc7a7a250a40222f18913a97cd356bf82d0a6c4
diff --git a/package-lock.json b/package-lock.json
index 55bfafbec2f2..5416b5d4ea19 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "new.expensify",
- "version": "1.4.22-3",
+ "version": "1.4.24-4",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "new.expensify",
- "version": "1.4.22-3",
+ "version": "1.4.24-4",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
@@ -96,7 +96,7 @@
"react-native-modal": "^13.0.0",
"react-native-onyx": "1.0.118",
"react-native-pager-view": "^6.2.0",
- "react-native-pdf": "^6.7.4",
+ "react-native-pdf": "^6.7.3",
"react-native-performance": "^5.1.0",
"react-native-permissions": "^3.9.3",
"react-native-picker-select": "git+https://github.com/Expensify/react-native-picker-select.git#7a407cd4174d9838a944c1c2e1cb4a9737ac69c5",
@@ -161,6 +161,7 @@
"@testing-library/jest-native": "5.4.1",
"@testing-library/react-native": "11.5.1",
"@trivago/prettier-plugin-sort-imports": "^4.2.0",
+ "@types/canvas-size": "^1.2.2",
"@types/concurrently": "^7.0.0",
"@types/jest": "^29.5.2",
"@types/jest-when": "^3.5.2",
@@ -20916,6 +20917,12 @@
"@types/responselike": "^1.0.0"
}
},
+ "node_modules/@types/canvas-size": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/@types/canvas-size/-/canvas-size-1.2.2.tgz",
+ "integrity": "sha512-yuTXFWC4tHV3lt5ZtbIP9VeeMNbDYm5mPyqaQnaMuSSx2mjsfZGXMNmHTnfdsR5qZdB6dtbaV5IP2PKv79vmKg==",
+ "dev": true
+ },
"node_modules/@types/concurrently": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/@types/concurrently/-/concurrently-7.0.0.tgz",
@@ -47635,9 +47642,9 @@
}
},
"node_modules/react-native-pdf": {
- "version": "6.7.4",
- "resolved": "https://registry.npmjs.org/react-native-pdf/-/react-native-pdf-6.7.4.tgz",
- "integrity": "sha512-sBeNcsrTRnLjmiU9Wx7Uk0K2kPSQtKIIG+FECdrEG16TOdtmQ3iqqEwt0dmy0pJegpg07uES5BXqiKsKkRUIFw==",
+ "version": "6.7.3",
+ "resolved": "https://registry.npmjs.org/react-native-pdf/-/react-native-pdf-6.7.3.tgz",
+ "integrity": "sha512-bK1fVkj18kBA5YlRFNJ3/vJ1bEX3FDHyAPY6ArtIdVs+vv0HzcK5WH9LSd2bxUsEMIyY9CSjP4j8BcxNXTiQkQ==",
"dependencies": {
"crypto-js": "4.2.0",
"deprecated-react-native-prop-types": "^2.3.0"
@@ -71204,6 +71211,12 @@
"@types/responselike": "^1.0.0"
}
},
+ "@types/canvas-size": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/@types/canvas-size/-/canvas-size-1.2.2.tgz",
+ "integrity": "sha512-yuTXFWC4tHV3lt5ZtbIP9VeeMNbDYm5mPyqaQnaMuSSx2mjsfZGXMNmHTnfdsR5qZdB6dtbaV5IP2PKv79vmKg==",
+ "dev": true
+ },
"@types/concurrently": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/@types/concurrently/-/concurrently-7.0.0.tgz",
@@ -90531,9 +90544,9 @@
"requires": {}
},
"react-native-pdf": {
- "version": "6.7.4",
- "resolved": "https://registry.npmjs.org/react-native-pdf/-/react-native-pdf-6.7.4.tgz",
- "integrity": "sha512-sBeNcsrTRnLjmiU9Wx7Uk0K2kPSQtKIIG+FECdrEG16TOdtmQ3iqqEwt0dmy0pJegpg07uES5BXqiKsKkRUIFw==",
+ "version": "6.7.3",
+ "resolved": "https://registry.npmjs.org/react-native-pdf/-/react-native-pdf-6.7.3.tgz",
+ "integrity": "sha512-bK1fVkj18kBA5YlRFNJ3/vJ1bEX3FDHyAPY6ArtIdVs+vv0HzcK5WH9LSd2bxUsEMIyY9CSjP4j8BcxNXTiQkQ==",
"requires": {
"crypto-js": "4.2.0",
"deprecated-react-native-prop-types": "^2.3.0"
diff --git a/package.json b/package.json
index 7264cb5fa25e..7753368b6632 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "new.expensify",
- "version": "1.4.22-3",
+ "version": "1.4.24-4",
"author": "Expensify, Inc.",
"homepage": "https://new.expensify.com",
"description": "New Expensify is the next generation of Expensify: a reimagination of payments based atop a foundation of chat.",
@@ -144,7 +144,7 @@
"react-native-modal": "^13.0.0",
"react-native-onyx": "1.0.118",
"react-native-pager-view": "^6.2.0",
- "react-native-pdf": "^6.7.4",
+ "react-native-pdf": "^6.7.3",
"react-native-performance": "^5.1.0",
"react-native-permissions": "^3.9.3",
"react-native-picker-select": "git+https://github.com/Expensify/react-native-picker-select.git#7a407cd4174d9838a944c1c2e1cb4a9737ac69c5",
@@ -209,6 +209,7 @@
"@testing-library/jest-native": "5.4.1",
"@testing-library/react-native": "11.5.1",
"@trivago/prettier-plugin-sort-imports": "^4.2.0",
+ "@types/canvas-size": "^1.2.2",
"@types/concurrently": "^7.0.0",
"@types/jest": "^29.5.2",
"@types/jest-when": "^3.5.2",
diff --git a/patches/@react-native+virtualized-lists+0.72.8.patch b/patches/@react-native+virtualized-lists+0.72.8.patch
new file mode 100644
index 000000000000..a3bef95f1618
--- /dev/null
+++ b/patches/@react-native+virtualized-lists+0.72.8.patch
@@ -0,0 +1,34 @@
+diff --git a/node_modules/@react-native/virtualized-lists/Lists/VirtualizedList.js b/node_modules/@react-native/virtualized-lists/Lists/VirtualizedList.js
+index ef5a3f0..2590edd 100644
+--- a/node_modules/@react-native/virtualized-lists/Lists/VirtualizedList.js
++++ b/node_modules/@react-native/virtualized-lists/Lists/VirtualizedList.js
+@@ -125,19 +125,6 @@ function windowSizeOrDefault(windowSize: ?number) {
+ return windowSize ?? 21;
+ }
+
+-function findLastWhere(
+- arr: $ReadOnlyArray,
+- predicate: (element: T) => boolean,
+-): T | null {
+- for (let i = arr.length - 1; i >= 0; i--) {
+- if (predicate(arr[i])) {
+- return arr[i];
+- }
+- }
+-
+- return null;
+-}
+-
+ /**
+ * Base implementation for the more convenient [``](https://reactnative.dev/docs/flatlist)
+ * and [``](https://reactnative.dev/docs/sectionlist) components, which are also better
+@@ -1019,7 +1006,8 @@ class VirtualizedList extends StateSafePureComponent {
+ const spacerKey = this._getSpacerKey(!horizontal);
+
+ const renderRegions = this.state.renderMask.enumerateRegions();
+- const lastSpacer = findLastWhere(renderRegions, r => r.isSpacer);
++ const lastRegion = renderRegions[renderRegions.length - 1];
++ const lastSpacer = lastRegion?.isSpacer ? lastRegion : null;
+
+ for (const section of renderRegions) {
+ if (section.isSpacer) {
diff --git a/patches/react-native+0.72.4+005+fix-boost-dependency.patch b/patches/react-native+0.72.4+005+fix-boost-dependency.patch
new file mode 100644
index 000000000000..477cf97b4a02
--- /dev/null
+++ b/patches/react-native+0.72.4+005+fix-boost-dependency.patch
@@ -0,0 +1,27 @@
+diff --git a/node_modules/react-native/ReactAndroid/build.gradle b/node_modules/react-native/ReactAndroid/build.gradle
+index f44b6e4..818833b 100644
+--- a/node_modules/react-native/ReactAndroid/build.gradle
++++ b/node_modules/react-native/ReactAndroid/build.gradle
+@@ -243,7 +243,8 @@ task createNativeDepsDirectories {
+ }
+
+ task downloadBoost(dependsOn: createNativeDepsDirectories, type: Download) {
+- src("https://boostorg.jfrog.io/artifactory/main/release/${BOOST_VERSION.replace("_", ".")}/source/boost_${BOOST_VERSION}.tar.gz")
++ def transformedVersion = BOOST_VERSION.replace("_", ".")
++ src("https://archives.boost.io/release/${transformedVersion}/source/boost_${BOOST_VERSION}.tar.gz")
+ onlyIfModified(true)
+ overwrite(false)
+ retries(5)
+diff --git a/node_modules/react-native/third-party-podspecs/boost.podspec b/node_modules/react-native/third-party-podspecs/boost.podspec
+index 3d9331c..bbbb738 100644
+--- a/node_modules/react-native/third-party-podspecs/boost.podspec
++++ b/node_modules/react-native/third-party-podspecs/boost.podspec
+@@ -10,7 +10,7 @@ Pod::Spec.new do |spec|
+ spec.homepage = 'http://www.boost.org'
+ spec.summary = 'Boost provides free peer-reviewed portable C++ source libraries.'
+ spec.authors = 'Rene Rivera'
+- spec.source = { :http => 'https://boostorg.jfrog.io/artifactory/main/release/1.76.0/source/boost_1_76_0.tar.bz2',
++ spec.source = { :http => 'https://archives.boost.io/release/1.76.0/source/boost_1_76_0.tar.bz2',
+ :sha256 => 'f0397ba6e982c4450f27bf32a2a83292aba035b827a5623a14636ea583318c41' }
+
+ # Pinning to the same version as React.podspec.
diff --git a/patches/react-native-reanimated+3.6.1+001+fix-boost-dependency.patch b/patches/react-native-reanimated+3.6.1+001+fix-boost-dependency.patch
new file mode 100644
index 000000000000..9a98cb7af85f
--- /dev/null
+++ b/patches/react-native-reanimated+3.6.1+001+fix-boost-dependency.patch
@@ -0,0 +1,13 @@
+diff --git a/node_modules/react-native-reanimated/android/build.gradle b/node_modules/react-native-reanimated/android/build.gradle
+index 3de90e5..42d9d1a 100644
+--- a/node_modules/react-native-reanimated/android/build.gradle
++++ b/node_modules/react-native-reanimated/android/build.gradle
+@@ -567,7 +567,7 @@ if (REACT_NATIVE_MINOR_VERSION < 71) {
+ task downloadBoost(dependsOn: resolveBoost, type: Download) {
+ def transformedVersion = BOOST_VERSION.replace("_", ".")
+ def artifactLocalName = "boost_${BOOST_VERSION}.tar.gz"
+- def srcUrl = "https://boostorg.jfrog.io/artifactory/main/release/${transformedVersion}/source/${artifactLocalName}"
++ def srcUrl = "https://archives.boost.io/release/${transformedVersion}/source/${artifactLocalName}"
+ if (REACT_NATIVE_MINOR_VERSION < 69) {
+ srcUrl = "https://github.com/react-native-community/boost-for-react-native/releases/download/v${transformedVersion}-0/${artifactLocalName}"
+ }
diff --git a/patches/react-native-vision-camera+2.16.2+001+fix-boost-dependency.patch b/patches/react-native-vision-camera+2.16.2+001+fix-boost-dependency.patch
new file mode 100644
index 000000000000..ef4fbf1d5084
--- /dev/null
+++ b/patches/react-native-vision-camera+2.16.2+001+fix-boost-dependency.patch
@@ -0,0 +1,13 @@
+diff --git a/node_modules/react-native-vision-camera/android/build.gradle b/node_modules/react-native-vision-camera/android/build.gradle
+index d308e15..2d87d8e 100644
+--- a/node_modules/react-native-vision-camera/android/build.gradle
++++ b/node_modules/react-native-vision-camera/android/build.gradle
+@@ -347,7 +347,7 @@ if (ENABLE_FRAME_PROCESSORS) {
+
+ task downloadBoost(dependsOn: createNativeDepsDirectories, type: Download) {
+ def transformedVersion = BOOST_VERSION.replace("_", ".")
+- def srcUrl = "https://boostorg.jfrog.io/artifactory/main/release/${transformedVersion}/source/boost_${BOOST_VERSION}.tar.gz"
++ def srcUrl = "https://archives.boost.io/release/${transformedVersion}/source/boost_${BOOST_VERSION}.tar.gz"
+ if (REACT_NATIVE_VERSION < 69) {
+ srcUrl = "https://github.com/react-native-community/boost-for-react-native/releases/download/v${transformedVersion}-0/boost_${BOOST_VERSION}.tar.gz"
+ }
diff --git a/patches/react-native-web+0.19.9+001+initial.patch b/patches/react-native-web+0.19.9+001+initial.patch
index d88ef83d4bcd..91ba6bfd59c0 100644
--- a/patches/react-native-web+0.19.9+001+initial.patch
+++ b/patches/react-native-web+0.19.9+001+initial.patch
@@ -1,286 +1,648 @@
diff --git a/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js b/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js
-index c879838..288316c 100644
+index c879838..0c9dfcb 100644
--- a/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js
+++ b/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js
-@@ -117,6 +117,14 @@ function findLastWhere(arr, predicate) {
- *
- */
- class VirtualizedList extends StateSafePureComponent {
-+ pushOrUnshift(input, item) {
-+ if (this.props.inverted) {
-+ input.unshift(item);
-+ } else {
-+ input.push(item);
+@@ -285,7 +285,7 @@ class VirtualizedList extends StateSafePureComponent {
+ // $FlowFixMe[missing-local-annot]
+
+ constructor(_props) {
+- var _this$props$updateCel;
++ var _this$props$updateCel, _this$props$maintainV, _this$props$maintainV2;
+ super(_props);
+ this._getScrollMetrics = () => {
+ return this._scrollMetrics;
+@@ -520,6 +520,11 @@ class VirtualizedList extends StateSafePureComponent {
+ visibleLength,
+ zoomScale
+ };
++ if (this.state.pendingScrollUpdateCount > 0) {
++ this.setState(state => ({
++ pendingScrollUpdateCount: state.pendingScrollUpdateCount - 1
++ }));
++ }
+ this._updateViewableItems(this.props, this.state.cellsAroundViewport);
+ if (!this.props) {
+ return;
+@@ -569,7 +574,7 @@ class VirtualizedList extends StateSafePureComponent {
+ this._updateCellsToRender = () => {
+ this._updateViewableItems(this.props, this.state.cellsAroundViewport);
+ this.setState((state, props) => {
+- var cellsAroundViewport = this._adjustCellsAroundViewport(props, state.cellsAroundViewport);
++ var cellsAroundViewport = this._adjustCellsAroundViewport(props, state.cellsAroundViewport, state.pendingScrollUpdateCount);
+ var renderMask = VirtualizedList._createRenderMask(props, cellsAroundViewport, this._getNonViewportRenderRegions(props));
+ if (cellsAroundViewport.first === state.cellsAroundViewport.first && cellsAroundViewport.last === state.cellsAroundViewport.last && renderMask.equals(state.renderMask)) {
+ return null;
+@@ -589,7 +594,7 @@ class VirtualizedList extends StateSafePureComponent {
+ return {
+ index,
+ item,
+- key: this._keyExtractor(item, index, props),
++ key: VirtualizedList._keyExtractor(item, index, props),
+ isViewable
+ };
+ };
+@@ -621,12 +626,10 @@ class VirtualizedList extends StateSafePureComponent {
+ };
+ this._getFrameMetrics = (index, props) => {
+ var data = props.data,
+- getItem = props.getItem,
+ getItemCount = props.getItemCount,
+ getItemLayout = props.getItemLayout;
+ invariant(index >= 0 && index < getItemCount(data), 'Tried to get frame for out of range index ' + index);
+- var item = getItem(data, index);
+- var frame = this._frames[this._keyExtractor(item, index, props)];
++ var frame = this._frames[VirtualizedList._getItemKey(props, index)];
+ if (!frame || frame.index !== index) {
+ if (getItemLayout) {
+ /* $FlowFixMe[prop-missing] (>=0.63.0 site=react_native_fb) This comment
+@@ -650,7 +653,7 @@ class VirtualizedList extends StateSafePureComponent {
+
+ // The last cell we rendered may be at a new index. Bail if we don't know
+ // where it is.
+- if (focusedCellIndex >= itemCount || this._keyExtractor(props.getItem(props.data, focusedCellIndex), focusedCellIndex, props) !== this._lastFocusedCellKey) {
++ if (focusedCellIndex >= itemCount || VirtualizedList._getItemKey(props, focusedCellIndex) !== this._lastFocusedCellKey) {
+ return [];
+ }
+ var first = focusedCellIndex;
+@@ -690,9 +693,15 @@ class VirtualizedList extends StateSafePureComponent {
+ }
+ }
+ var initialRenderRegion = VirtualizedList._initialRenderRegion(_props);
++ var minIndexForVisible = (_this$props$maintainV = (_this$props$maintainV2 = this.props.maintainVisibleContentPosition) == null ? void 0 : _this$props$maintainV2.minIndexForVisible) !== null && _this$props$maintainV !== void 0 ? _this$props$maintainV : 0;
+ this.state = {
+ cellsAroundViewport: initialRenderRegion,
+- renderMask: VirtualizedList._createRenderMask(_props, initialRenderRegion)
++ renderMask: VirtualizedList._createRenderMask(_props, initialRenderRegion),
++ firstVisibleItemKey: this.props.getItemCount(this.props.data) > minIndexForVisible ? VirtualizedList._getItemKey(this.props, minIndexForVisible) : null,
++ // When we have a non-zero initialScrollIndex, we will receive a
++ // scroll event later so this will prevent the window from updating
++ // until we get a valid offset.
++ pendingScrollUpdateCount: this.props.initialScrollIndex != null && this.props.initialScrollIndex > 0 ? 1 : 0
+ };
+
+ // REACT-NATIVE-WEB patch to preserve during future RN merges: Support inverted wheel scroller.
+@@ -748,6 +757,26 @@ class VirtualizedList extends StateSafePureComponent {
+ }
+ }
+ }
++ static _findItemIndexWithKey(props, key, hint) {
++ var itemCount = props.getItemCount(props.data);
++ if (hint != null && hint >= 0 && hint < itemCount) {
++ var curKey = VirtualizedList._getItemKey(props, hint);
++ if (curKey === key) {
++ return hint;
++ }
++ }
++ for (var ii = 0; ii < itemCount; ii++) {
++ var _curKey = VirtualizedList._getItemKey(props, ii);
++ if (_curKey === key) {
++ return ii;
++ }
+ }
++ return null;
+ }
-+
- // scrollToEnd may be janky without getItemLayout prop
- scrollToEnd(params) {
- var animated = params ? params.animated : true;
-@@ -350,6 +358,7 @@ class VirtualizedList extends StateSafePureComponent {
- };
- this._defaultRenderScrollComponent = props => {
- var onRefresh = props.onRefresh;
-+ var inversionStyle = this.props.inverted ? this.props.horizontal ? styles.rowReverse : styles.columnReverse : null;
- if (this._isNestedWithSameOrientation()) {
- // $FlowFixMe[prop-missing] - Typing ReactNativeComponent revealed errors
- return /*#__PURE__*/React.createElement(View, props);
-@@ -367,13 +376,16 @@ class VirtualizedList extends StateSafePureComponent {
- refreshing: props.refreshing,
- onRefresh: onRefresh,
- progressViewOffset: props.progressViewOffset
-- }) : props.refreshControl
-+ }) : props.refreshControl,
-+ contentContainerStyle: [inversionStyle, this.props.contentContainerStyle]
- }))
- );
- } else {
- // $FlowFixMe[prop-missing] Invalid prop usage
- // $FlowFixMe[incompatible-use]
-- return /*#__PURE__*/React.createElement(ScrollView, props);
-+ return /*#__PURE__*/React.createElement(ScrollView, _extends({}, props, {
-+ contentContainerStyle: [inversionStyle, this.props.contentContainerStyle]
-+ }));
++ static _getItemKey(props, index) {
++ var item = props.getItem(props.data, index);
++ return VirtualizedList._keyExtractor(item, index, props);
++ }
+ static _createRenderMask(props, cellsAroundViewport, additionalRegions) {
+ var itemCount = props.getItemCount(props.data);
+ invariant(cellsAroundViewport.first >= 0 && cellsAroundViewport.last >= cellsAroundViewport.first - 1 && cellsAroundViewport.last < itemCount, "Invalid cells around viewport \"[" + cellsAroundViewport.first + ", " + cellsAroundViewport.last + "]\" was passed to VirtualizedList._createRenderMask");
+@@ -796,7 +825,7 @@ class VirtualizedList extends StateSafePureComponent {
+ }
+ }
+ }
+- _adjustCellsAroundViewport(props, cellsAroundViewport) {
++ _adjustCellsAroundViewport(props, cellsAroundViewport, pendingScrollUpdateCount) {
+ var data = props.data,
+ getItemCount = props.getItemCount;
+ var onEndReachedThreshold = onEndReachedThresholdOrDefault(props.onEndReachedThreshold);
+@@ -819,17 +848,9 @@ class VirtualizedList extends StateSafePureComponent {
+ last: Math.min(cellsAroundViewport.last + renderAhead, getItemCount(data) - 1)
+ };
+ } else {
+- // If we have a non-zero initialScrollIndex and run this before we've scrolled,
+- // we'll wipe out the initialNumToRender rendered elements starting at initialScrollIndex.
+- // So let's wait until we've scrolled the view to the right place. And until then,
+- // we will trust the initialScrollIndex suggestion.
+-
+- // Thus, we want to recalculate the windowed render limits if any of the following hold:
+- // - initialScrollIndex is undefined or is 0
+- // - initialScrollIndex > 0 AND scrolling is complete
+- // - initialScrollIndex > 0 AND the end of the list is visible (this handles the case
+- // where the list is shorter than the visible area)
+- if (props.initialScrollIndex && !this._scrollMetrics.offset && Math.abs(distanceFromEnd) >= Number.EPSILON) {
++ // If we have a pending scroll update, we should not adjust the render window as it
++ // might override the correct window.
++ if (pendingScrollUpdateCount > 0) {
+ return cellsAroundViewport.last >= getItemCount(data) ? VirtualizedList._constrainToItemCount(cellsAroundViewport, props) : cellsAroundViewport;
}
+ newCellsAroundViewport = computeWindowedRenderLimits(props, maxToRenderPerBatchOrDefault(props.maxToRenderPerBatch), windowSizeOrDefault(props.windowSize), cellsAroundViewport, this.__getFrameMetricsApprox, this._scrollMetrics);
+@@ -902,16 +923,36 @@ class VirtualizedList extends StateSafePureComponent {
+ }
+ }
+ static getDerivedStateFromProps(newProps, prevState) {
++ var _newProps$maintainVis, _newProps$maintainVis2;
+ // first and last could be stale (e.g. if a new, shorter items props is passed in), so we make
+ // sure we're rendering a reasonable range here.
+ var itemCount = newProps.getItemCount(newProps.data);
+ if (itemCount === prevState.renderMask.numCells()) {
+ return prevState;
+ }
+- var constrainedCells = VirtualizedList._constrainToItemCount(prevState.cellsAroundViewport, newProps);
++ var maintainVisibleContentPositionAdjustment = null;
++ var prevFirstVisibleItemKey = prevState.firstVisibleItemKey;
++ var minIndexForVisible = (_newProps$maintainVis = (_newProps$maintainVis2 = newProps.maintainVisibleContentPosition) == null ? void 0 : _newProps$maintainVis2.minIndexForVisible) !== null && _newProps$maintainVis !== void 0 ? _newProps$maintainVis : 0;
++ var newFirstVisibleItemKey = newProps.getItemCount(newProps.data) > minIndexForVisible ? VirtualizedList._getItemKey(newProps, minIndexForVisible) : null;
++ if (newProps.maintainVisibleContentPosition != null && prevFirstVisibleItemKey != null && newFirstVisibleItemKey != null) {
++ if (newFirstVisibleItemKey !== prevFirstVisibleItemKey) {
++ // Fast path if items were added at the start of the list.
++ var hint = itemCount - prevState.renderMask.numCells() + minIndexForVisible;
++ var firstVisibleItemIndex = VirtualizedList._findItemIndexWithKey(newProps, prevFirstVisibleItemKey, hint);
++ maintainVisibleContentPositionAdjustment = firstVisibleItemIndex != null ? firstVisibleItemIndex - minIndexForVisible : null;
++ } else {
++ maintainVisibleContentPositionAdjustment = null;
++ }
++ }
++ var constrainedCells = VirtualizedList._constrainToItemCount(maintainVisibleContentPositionAdjustment != null ? {
++ first: prevState.cellsAroundViewport.first + maintainVisibleContentPositionAdjustment,
++ last: prevState.cellsAroundViewport.last + maintainVisibleContentPositionAdjustment
++ } : prevState.cellsAroundViewport, newProps);
+ return {
+ cellsAroundViewport: constrainedCells,
+- renderMask: VirtualizedList._createRenderMask(newProps, constrainedCells)
++ renderMask: VirtualizedList._createRenderMask(newProps, constrainedCells),
++ firstVisibleItemKey: newFirstVisibleItemKey,
++ pendingScrollUpdateCount: maintainVisibleContentPositionAdjustment != null ? prevState.pendingScrollUpdateCount + 1 : prevState.pendingScrollUpdateCount
};
- this._onCellLayout = (e, cellKey, index) => {
-@@ -683,7 +695,7 @@ class VirtualizedList extends StateSafePureComponent {
- onViewableItemsChanged = _this$props3.onViewableItemsChanged,
- viewabilityConfig = _this$props3.viewabilityConfig;
- if (onViewableItemsChanged) {
-- this._viewabilityTuples.push({
-+ this.pushOrUnshift(this._viewabilityTuples, {
- viewabilityHelper: new ViewabilityHelper(viewabilityConfig),
- onViewableItemsChanged: onViewableItemsChanged
- });
-@@ -937,10 +949,10 @@ class VirtualizedList extends StateSafePureComponent {
- var key = _this._keyExtractor(item, ii, _this.props);
+ }
+ _pushCells(cells, stickyHeaderIndices, stickyIndicesFromProps, first, last, inversionStyle) {
+@@ -934,7 +975,7 @@ class VirtualizedList extends StateSafePureComponent {
+ last = Math.min(end, last);
+ var _loop = function _loop() {
+ var item = getItem(data, ii);
+- var key = _this._keyExtractor(item, ii, _this.props);
++ var key = VirtualizedList._keyExtractor(item, ii, _this.props);
_this._indicesToKeys.set(ii, key);
if (stickyIndicesFromProps.has(ii + stickyOffset)) {
-- stickyHeaderIndices.push(cells.length);
-+ _this.pushOrUnshift(stickyHeaderIndices, cells.length);
- }
- var shouldListenForLayout = getItemLayout == null || debug || _this._fillRateHelper.enabled();
-- cells.push( /*#__PURE__*/React.createElement(CellRenderer, _extends({
-+ _this.pushOrUnshift(cells, /*#__PURE__*/React.createElement(CellRenderer, _extends({
- CellRendererComponent: CellRendererComponent,
- ItemSeparatorComponent: ii < end ? ItemSeparatorComponent : undefined,
- ListItemComponent: ListItemComponent,
-@@ -1012,14 +1024,14 @@ class VirtualizedList extends StateSafePureComponent {
- // 1. Add cell for ListHeaderComponent
- if (ListHeaderComponent) {
- if (stickyIndicesFromProps.has(0)) {
-- stickyHeaderIndices.push(0);
-+ this.pushOrUnshift(stickyHeaderIndices, 0);
- }
- var _element = /*#__PURE__*/React.isValidElement(ListHeaderComponent) ? ListHeaderComponent :
- /*#__PURE__*/
- // $FlowFixMe[not-a-component]
- // $FlowFixMe[incompatible-type-arg]
- React.createElement(ListHeaderComponent, null);
-- cells.push( /*#__PURE__*/React.createElement(VirtualizedListCellContextProvider, {
-+ this.pushOrUnshift(cells, /*#__PURE__*/React.createElement(VirtualizedListCellContextProvider, {
+ stickyHeaderIndices.push(cells.length);
+@@ -969,20 +1010,23 @@ class VirtualizedList extends StateSafePureComponent {
+ }
+ static _constrainToItemCount(cells, props) {
+ var itemCount = props.getItemCount(props.data);
+- var last = Math.min(itemCount - 1, cells.last);
++ var lastPossibleCellIndex = itemCount - 1;
++
++ // Constraining `last` may significantly shrink the window. Adjust `first`
++ // to expand the window if the new `last` results in a new window smaller
++ // than the number of cells rendered per batch.
+ var maxToRenderPerBatch = maxToRenderPerBatchOrDefault(props.maxToRenderPerBatch);
++ var maxFirst = Math.max(0, lastPossibleCellIndex - maxToRenderPerBatch);
+ return {
+- first: clamp(0, itemCount - 1 - maxToRenderPerBatch, cells.first),
+- last
++ first: clamp(0, cells.first, maxFirst),
++ last: Math.min(lastPossibleCellIndex, cells.last)
+ };
+ }
+ _isNestedWithSameOrientation() {
+ var nestedContext = this.context;
+ return !!(nestedContext && !!nestedContext.horizontal === horizontalOrDefault(this.props.horizontal));
+ }
+- _keyExtractor(item, index, props
+- // $FlowFixMe[missing-local-annot]
+- ) {
++ static _keyExtractor(item, index, props) {
+ if (props.keyExtractor != null) {
+ return props.keyExtractor(item, index);
+ }
+@@ -1022,7 +1066,12 @@ class VirtualizedList extends StateSafePureComponent {
+ cells.push( /*#__PURE__*/React.createElement(VirtualizedListCellContextProvider, {
cellKey: this._getCellKey() + '-header',
key: "$header"
- }, /*#__PURE__*/React.createElement(View, {
-@@ -1038,7 +1050,7 @@ class VirtualizedList extends StateSafePureComponent {
- // $FlowFixMe[not-a-component]
- // $FlowFixMe[incompatible-type-arg]
- React.createElement(ListEmptyComponent, null);
-- cells.push( /*#__PURE__*/React.createElement(VirtualizedListCellContextProvider, {
-+ this.pushOrUnshift(cells, /*#__PURE__*/React.createElement(VirtualizedListCellContextProvider, {
- cellKey: this._getCellKey() + '-empty',
- key: "$empty"
- }, /*#__PURE__*/React.cloneElement(_element2, {
-@@ -1077,7 +1089,7 @@ class VirtualizedList extends StateSafePureComponent {
- var firstMetrics = this.__getFrameMetricsApprox(section.first, this.props);
- var lastMetrics = this.__getFrameMetricsApprox(last, this.props);
- var spacerSize = lastMetrics.offset + lastMetrics.length - firstMetrics.offset;
-- cells.push( /*#__PURE__*/React.createElement(View, {
-+ this.pushOrUnshift(cells, /*#__PURE__*/React.createElement(View, {
- key: "$spacer-" + section.first,
- style: {
- [spacerKey]: spacerSize
-@@ -1100,7 +1112,7 @@ class VirtualizedList extends StateSafePureComponent {
- // $FlowFixMe[not-a-component]
- // $FlowFixMe[incompatible-type-arg]
- React.createElement(ListFooterComponent, null);
-- cells.push( /*#__PURE__*/React.createElement(VirtualizedListCellContextProvider, {
-+ this.pushOrUnshift(cells, /*#__PURE__*/React.createElement(VirtualizedListCellContextProvider, {
- cellKey: this._getFooterCellKey(),
- key: "$footer"
- }, /*#__PURE__*/React.createElement(View, {
-@@ -1266,7 +1278,7 @@ class VirtualizedList extends StateSafePureComponent {
- * suppresses an error found when Flow v0.68 was deployed. To see the
- * error delete this comment and run Flow. */
- if (frame.inLayout) {
-- framesInLayout.push(frame);
-+ this.pushOrUnshift(framesInLayout, frame);
- }
+- }, /*#__PURE__*/React.createElement(View, {
++ }, /*#__PURE__*/React.createElement(View
++ // We expect that header component will be a single native view so make it
++ // not collapsable to avoid this view being flattened and make this assumption
++ // no longer true.
++ , {
++ collapsable: false,
+ onLayout: this._onLayoutHeader,
+ style: [inversionStyle, this.props.ListHeaderComponentStyle]
+ },
+@@ -1124,7 +1173,11 @@ class VirtualizedList extends StateSafePureComponent {
+ // TODO: Android support
+ invertStickyHeaders: this.props.invertStickyHeaders !== undefined ? this.props.invertStickyHeaders : this.props.inverted,
+ stickyHeaderIndices,
+- style: inversionStyle ? [inversionStyle, this.props.style] : this.props.style
++ style: inversionStyle ? [inversionStyle, this.props.style] : this.props.style,
++ maintainVisibleContentPosition: this.props.maintainVisibleContentPosition != null ? _objectSpread(_objectSpread({}, this.props.maintainVisibleContentPosition), {}, {
++ // Adjust index to account for ListHeaderComponent.
++ minIndexForVisible: this.props.maintainVisibleContentPosition.minIndexForVisible + (this.props.ListHeaderComponent ? 1 : 0)
++ }) : undefined
+ });
+ this._hasMore = this.state.cellsAroundViewport.last < itemCount - 1;
+ var innerRet = /*#__PURE__*/React.createElement(VirtualizedListContextProvider, {
+@@ -1307,8 +1360,12 @@ class VirtualizedList extends StateSafePureComponent {
+ onStartReached = _this$props8.onStartReached,
+ onStartReachedThreshold = _this$props8.onStartReachedThreshold,
+ onEndReached = _this$props8.onEndReached,
+- onEndReachedThreshold = _this$props8.onEndReachedThreshold,
+- initialScrollIndex = _this$props8.initialScrollIndex;
++ onEndReachedThreshold = _this$props8.onEndReachedThreshold;
++ // If we have any pending scroll updates it means that the scroll metrics
++ // are out of date and we should not call any of the edge reached callbacks.
++ if (this.state.pendingScrollUpdateCount > 0) {
++ return;
++ }
+ var _this$_scrollMetrics2 = this._scrollMetrics,
+ contentLength = _this$_scrollMetrics2.contentLength,
+ visibleLength = _this$_scrollMetrics2.visibleLength,
+@@ -1348,16 +1405,10 @@ class VirtualizedList extends StateSafePureComponent {
+ // and call onStartReached only once for a given content length,
+ // and only if onEndReached is not being executed
+ else if (onStartReached != null && this.state.cellsAroundViewport.first === 0 && isWithinStartThreshold && this._scrollMetrics.contentLength !== this._sentStartForContentLength) {
+- // On initial mount when using initialScrollIndex the offset will be 0 initially
+- // and will trigger an unexpected onStartReached. To avoid this we can use
+- // timestamp to differentiate between the initial scroll metrics and when we actually
+- // received the first scroll event.
+- if (!initialScrollIndex || this._scrollMetrics.timestamp !== 0) {
+- this._sentStartForContentLength = this._scrollMetrics.contentLength;
+- onStartReached({
+- distanceFromStart
+- });
+- }
++ this._sentStartForContentLength = this._scrollMetrics.contentLength;
++ onStartReached({
++ distanceFromStart
++ });
+ }
+
+ // If the user scrolls away from the start or end and back again,
+@@ -1412,6 +1463,11 @@ class VirtualizedList extends StateSafePureComponent {
}
- var windowTop = this.__getFrameMetricsApprox(this.state.cellsAroundViewport.first, this.props).offset;
-@@ -1452,6 +1464,12 @@ var styles = StyleSheet.create({
- left: 0,
- borderColor: 'red',
- borderWidth: 2
-+ },
-+ rowReverse: {
-+ flexDirection: 'row-reverse'
-+ },
-+ columnReverse: {
-+ flexDirection: 'column-reverse'
}
- });
- export default VirtualizedList;
-\ No newline at end of file
+ _updateViewableItems(props, cellsAroundViewport) {
++ // If we have any pending scroll updates it means that the scroll metrics
++ // are out of date and we should not call any of the visibility callbacks.
++ if (this.state.pendingScrollUpdateCount > 0) {
++ return;
++ }
+ this._viewabilityTuples.forEach(tuple => {
+ tuple.viewabilityHelper.onUpdate(props, this._scrollMetrics.offset, this._scrollMetrics.visibleLength, this._getFrameMetrics, this._createViewToken, tuple.onViewableItemsChanged, cellsAroundViewport);
+ });
diff --git a/node_modules/react-native-web/src/vendor/react-native/VirtualizedList/index.js b/node_modules/react-native-web/src/vendor/react-native/VirtualizedList/index.js
-index c7d68bb..46b3fc9 100644
+index c7d68bb..43f9653 100644
--- a/node_modules/react-native-web/src/vendor/react-native/VirtualizedList/index.js
+++ b/node_modules/react-native-web/src/vendor/react-native/VirtualizedList/index.js
-@@ -167,6 +167,14 @@ function findLastWhere(
- class VirtualizedList extends StateSafePureComponent {
- static contextType: typeof VirtualizedListContext = VirtualizedListContext;
+@@ -75,6 +75,10 @@ type ViewabilityHelperCallbackTuple = {
+ type State = {
+ renderMask: CellRenderMask,
+ cellsAroundViewport: {first: number, last: number},
++ // Used to track items added at the start of the list for maintainVisibleContentPosition.
++ firstVisibleItemKey: ?string,
++ // When > 0 the scroll position available in JS is considered stale and should not be used.
++ pendingScrollUpdateCount: number,
+ };
+
+ /**
+@@ -447,9 +451,24 @@ class VirtualizedList extends StateSafePureComponent {
+
+ const initialRenderRegion = VirtualizedList._initialRenderRegion(props);
-+ pushOrUnshift(input: Array, item: Item) {
-+ if (this.props.inverted) {
-+ input.unshift(item)
-+ } else {
-+ input.push(item)
++ const minIndexForVisible =
++ this.props.maintainVisibleContentPosition?.minIndexForVisible ?? 0;
++
+ this.state = {
+ cellsAroundViewport: initialRenderRegion,
+ renderMask: VirtualizedList._createRenderMask(props, initialRenderRegion),
++ firstVisibleItemKey:
++ this.props.getItemCount(this.props.data) > minIndexForVisible
++ ? VirtualizedList._getItemKey(this.props, minIndexForVisible)
++ : null,
++ // When we have a non-zero initialScrollIndex, we will receive a
++ // scroll event later so this will prevent the window from updating
++ // until we get a valid offset.
++ pendingScrollUpdateCount:
++ this.props.initialScrollIndex != null &&
++ this.props.initialScrollIndex > 0
++ ? 1
++ : 0,
+ };
+
+ // REACT-NATIVE-WEB patch to preserve during future RN merges: Support inverted wheel scroller.
+@@ -534,6 +553,40 @@ class VirtualizedList extends StateSafePureComponent {
+ }
+ }
+
++ static _findItemIndexWithKey(
++ props: Props,
++ key: string,
++ hint: ?number,
++ ): ?number {
++ const itemCount = props.getItemCount(props.data);
++ if (hint != null && hint >= 0 && hint < itemCount) {
++ const curKey = VirtualizedList._getItemKey(props, hint);
++ if (curKey === key) {
++ return hint;
++ }
+ }
++ for (let ii = 0; ii < itemCount; ii++) {
++ const curKey = VirtualizedList._getItemKey(props, ii);
++ if (curKey === key) {
++ return ii;
++ }
++ }
++ return null;
++ }
++
++ static _getItemKey(
++ props: {
++ data: Props['data'],
++ getItem: Props['getItem'],
++ keyExtractor: Props['keyExtractor'],
++ ...
++ },
++ index: number,
++ ): string {
++ const item = props.getItem(props.data, index);
++ return VirtualizedList._keyExtractor(item, index, props);
+ }
+
- // scrollToEnd may be janky without getItemLayout prop
- scrollToEnd(params?: ?{animated?: ?boolean, ...}) {
- const animated = params ? params.animated : true;
-@@ -438,7 +446,7 @@ class VirtualizedList extends StateSafePureComponent {
+ static _createRenderMask(
+ props: Props,
+ cellsAroundViewport: {first: number, last: number},
+@@ -617,6 +670,7 @@ class VirtualizedList extends StateSafePureComponent {
+ _adjustCellsAroundViewport(
+ props: Props,
+ cellsAroundViewport: {first: number, last: number},
++ pendingScrollUpdateCount: number,
+ ): {first: number, last: number} {
+ const {data, getItemCount} = props;
+ const onEndReachedThreshold = onEndReachedThresholdOrDefault(
+@@ -648,21 +702,9 @@ class VirtualizedList extends StateSafePureComponent {
+ ),
+ };
} else {
- const {onViewableItemsChanged, viewabilityConfig} = this.props;
- if (onViewableItemsChanged) {
-- this._viewabilityTuples.push({
-+ this.pushOrUnshift(this._viewabilityTuples, {
- viewabilityHelper: new ViewabilityHelper(viewabilityConfig),
- onViewableItemsChanged: onViewableItemsChanged,
- });
-@@ -814,13 +822,13 @@ class VirtualizedList extends StateSafePureComponent {
+- // If we have a non-zero initialScrollIndex and run this before we've scrolled,
+- // we'll wipe out the initialNumToRender rendered elements starting at initialScrollIndex.
+- // So let's wait until we've scrolled the view to the right place. And until then,
+- // we will trust the initialScrollIndex suggestion.
+-
+- // Thus, we want to recalculate the windowed render limits if any of the following hold:
+- // - initialScrollIndex is undefined or is 0
+- // - initialScrollIndex > 0 AND scrolling is complete
+- // - initialScrollIndex > 0 AND the end of the list is visible (this handles the case
+- // where the list is shorter than the visible area)
+- if (
+- props.initialScrollIndex &&
+- !this._scrollMetrics.offset &&
+- Math.abs(distanceFromEnd) >= Number.EPSILON
+- ) {
++ // If we have a pending scroll update, we should not adjust the render window as it
++ // might override the correct window.
++ if (pendingScrollUpdateCount > 0) {
+ return cellsAroundViewport.last >= getItemCount(data)
+ ? VirtualizedList._constrainToItemCount(cellsAroundViewport, props)
+ : cellsAroundViewport;
+@@ -771,14 +813,59 @@ class VirtualizedList extends StateSafePureComponent {
+ return prevState;
+ }
+
++ let maintainVisibleContentPositionAdjustment: ?number = null;
++ const prevFirstVisibleItemKey = prevState.firstVisibleItemKey;
++ const minIndexForVisible =
++ newProps.maintainVisibleContentPosition?.minIndexForVisible ?? 0;
++ const newFirstVisibleItemKey =
++ newProps.getItemCount(newProps.data) > minIndexForVisible
++ ? VirtualizedList._getItemKey(newProps, minIndexForVisible)
++ : null;
++ if (
++ newProps.maintainVisibleContentPosition != null &&
++ prevFirstVisibleItemKey != null &&
++ newFirstVisibleItemKey != null
++ ) {
++ if (newFirstVisibleItemKey !== prevFirstVisibleItemKey) {
++ // Fast path if items were added at the start of the list.
++ const hint =
++ itemCount - prevState.renderMask.numCells() + minIndexForVisible;
++ const firstVisibleItemIndex = VirtualizedList._findItemIndexWithKey(
++ newProps,
++ prevFirstVisibleItemKey,
++ hint,
++ );
++ maintainVisibleContentPositionAdjustment =
++ firstVisibleItemIndex != null
++ ? firstVisibleItemIndex - minIndexForVisible
++ : null;
++ } else {
++ maintainVisibleContentPositionAdjustment = null;
++ }
++ }
++
+ const constrainedCells = VirtualizedList._constrainToItemCount(
+- prevState.cellsAroundViewport,
++ maintainVisibleContentPositionAdjustment != null
++ ? {
++ first:
++ prevState.cellsAroundViewport.first +
++ maintainVisibleContentPositionAdjustment,
++ last:
++ prevState.cellsAroundViewport.last +
++ maintainVisibleContentPositionAdjustment,
++ }
++ : prevState.cellsAroundViewport,
+ newProps,
+ );
+
+ return {
+ cellsAroundViewport: constrainedCells,
+ renderMask: VirtualizedList._createRenderMask(newProps, constrainedCells),
++ firstVisibleItemKey: newFirstVisibleItemKey,
++ pendingScrollUpdateCount:
++ maintainVisibleContentPositionAdjustment != null
++ ? prevState.pendingScrollUpdateCount + 1
++ : prevState.pendingScrollUpdateCount,
+ };
+ }
+
+@@ -810,7 +897,7 @@ class VirtualizedList extends StateSafePureComponent {
+
+ for (let ii = first; ii <= last; ii++) {
+ const item = getItem(data, ii);
+- const key = this._keyExtractor(item, ii, this.props);
++ const key = VirtualizedList._keyExtractor(item, ii, this.props);
this._indicesToKeys.set(ii, key);
if (stickyIndicesFromProps.has(ii + stickyOffset)) {
-- stickyHeaderIndices.push(cells.length);
-+ this.pushOrUnshift(stickyHeaderIndices, (cells.length));
- }
+@@ -853,15 +940,19 @@ class VirtualizedList extends StateSafePureComponent {
+ props: Props,
+ ): {first: number, last: number} {
+ const itemCount = props.getItemCount(props.data);
+- const last = Math.min(itemCount - 1, cells.last);
++ const lastPossibleCellIndex = itemCount - 1;
- const shouldListenForLayout =
- getItemLayout == null || debug || this._fillRateHelper.enabled();
++ // Constraining `last` may significantly shrink the window. Adjust `first`
++ // to expand the window if the new `last` results in a new window smaller
++ // than the number of cells rendered per batch.
+ const maxToRenderPerBatch = maxToRenderPerBatchOrDefault(
+ props.maxToRenderPerBatch,
+ );
++ const maxFirst = Math.max(0, lastPossibleCellIndex - maxToRenderPerBatch);
-- cells.push(
-+ this.pushOrUnshift(cells,
- {
- // 1. Add cell for ListHeaderComponent
- if (ListHeaderComponent) {
- if (stickyIndicesFromProps.has(0)) {
-- stickyHeaderIndices.push(0);
-+ this.pushOrUnshift(stickyHeaderIndices, 0);
- }
- const element = React.isValidElement(ListHeaderComponent) ? (
- ListHeaderComponent
-@@ -932,7 +940,7 @@ class VirtualizedList extends StateSafePureComponent {
- // $FlowFixMe[incompatible-type-arg]
-
- );
-- cells.push(
-+ this.pushOrUnshift(cells,
- {
+ _getSpacerKey = (isVertical: boolean): string =>
+ isVertical ? 'height' : 'width';
+
+- _keyExtractor(
++ static _keyExtractor(
+ item: Item,
+ index: number,
+ props: {
+ keyExtractor?: ?(item: Item, index: number) => string,
+ ...
+ },
+- // $FlowFixMe[missing-local-annot]
+- ) {
++ ): string {
+ if (props.keyExtractor != null) {
+ return props.keyExtractor(item, index);
+ }
+@@ -937,6 +1027,10 @@ class VirtualizedList extends StateSafePureComponent {
cellKey={this._getCellKey() + '-header'}
key="$header">
-@@ -963,7 +971,7 @@ class VirtualizedList extends StateSafePureComponent {
- // $FlowFixMe[incompatible-type-arg]
-
- )): any);
-- cells.push(
-+ this.pushOrUnshift(cells,
-
-@@ -1017,7 +1025,7 @@ class VirtualizedList extends StateSafePureComponent {
- const lastMetrics = this.__getFrameMetricsApprox(last, this.props);
- const spacerSize =
- lastMetrics.offset + lastMetrics.length - firstMetrics.offset;
-- cells.push(
-+ this.pushOrUnshift(cells,
- {
- // $FlowFixMe[incompatible-type-arg]
-
- );
-- cells.push(
-+ this.pushOrUnshift(cells,
-
-@@ -1246,6 +1254,12 @@ class VirtualizedList extends StateSafePureComponent {
- * LTI update could not be added via codemod */
- _defaultRenderScrollComponent = props => {
- const onRefresh = props.onRefresh;
-+ const inversionStyle = this.props.inverted
-+ ? this.props.horizontal
-+ ? styles.rowReverse
-+ : styles.columnReverse
-+ : null;
-+
- if (this._isNestedWithSameOrientation()) {
- // $FlowFixMe[prop-missing] - Typing ReactNativeComponent revealed errors
- return ;
-@@ -1273,12 +1287,24 @@ class VirtualizedList extends StateSafePureComponent {
- props.refreshControl
- )
- }
-+ contentContainerStyle={[
-+ inversionStyle,
-+ this.props.contentContainerStyle,
-+ ]}
- />
- );
- } else {
- // $FlowFixMe[prop-missing] Invalid prop usage
- // $FlowFixMe[incompatible-use]
-- return ;
-+ return (
-+
-+ );
- }
- };
+ {
+ style: inversionStyle
+ ? [inversionStyle, this.props.style]
+ : this.props.style,
++ maintainVisibleContentPosition:
++ this.props.maintainVisibleContentPosition != null
++ ? {
++ ...this.props.maintainVisibleContentPosition,
++ // Adjust index to account for ListHeaderComponent.
++ minIndexForVisible:
++ this.props.maintainVisibleContentPosition.minIndexForVisible +
++ (this.props.ListHeaderComponent ? 1 : 0),
++ }
++ : undefined,
+ };
-@@ -1432,7 +1458,7 @@ class VirtualizedList extends StateSafePureComponent {
- * suppresses an error found when Flow v0.68 was deployed. To see the
- * error delete this comment and run Flow. */
- if (frame.inLayout) {
-- framesInLayout.push(frame);
-+ this.pushOrUnshift(framesInLayout, frame);
- }
+ this._hasMore = this.state.cellsAroundViewport.last < itemCount - 1;
+@@ -1516,8 +1620,12 @@ class VirtualizedList extends StateSafePureComponent {
+ onStartReachedThreshold,
+ onEndReached,
+ onEndReachedThreshold,
+- initialScrollIndex,
+ } = this.props;
++ // If we have any pending scroll updates it means that the scroll metrics
++ // are out of date and we should not call any of the edge reached callbacks.
++ if (this.state.pendingScrollUpdateCount > 0) {
++ return;
++ }
+ const {contentLength, visibleLength, offset} = this._scrollMetrics;
+ let distanceFromStart = offset;
+ let distanceFromEnd = contentLength - visibleLength - offset;
+@@ -1569,14 +1677,8 @@ class VirtualizedList extends StateSafePureComponent {
+ isWithinStartThreshold &&
+ this._scrollMetrics.contentLength !== this._sentStartForContentLength
+ ) {
+- // On initial mount when using initialScrollIndex the offset will be 0 initially
+- // and will trigger an unexpected onStartReached. To avoid this we can use
+- // timestamp to differentiate between the initial scroll metrics and when we actually
+- // received the first scroll event.
+- if (!initialScrollIndex || this._scrollMetrics.timestamp !== 0) {
+- this._sentStartForContentLength = this._scrollMetrics.contentLength;
+- onStartReached({distanceFromStart});
+- }
++ this._sentStartForContentLength = this._scrollMetrics.contentLength;
++ onStartReached({distanceFromStart});
}
- const windowTop = this.__getFrameMetricsApprox(
-@@ -2044,6 +2070,12 @@ const styles = StyleSheet.create({
- borderColor: 'red',
- borderWidth: 2,
- },
-+ rowReverse: {
-+ flexDirection: 'row-reverse',
-+ },
-+ columnReverse: {
-+ flexDirection: 'column-reverse',
-+ },
- });
- export default VirtualizedList;
-\ No newline at end of file
+ // If the user scrolls away from the start or end and back again,
+@@ -1703,6 +1805,11 @@ class VirtualizedList extends StateSafePureComponent {
+ visibleLength,
+ zoomScale,
+ };
++ if (this.state.pendingScrollUpdateCount > 0) {
++ this.setState(state => ({
++ pendingScrollUpdateCount: state.pendingScrollUpdateCount - 1,
++ }));
++ }
+ this._updateViewableItems(this.props, this.state.cellsAroundViewport);
+ if (!this.props) {
+ return;
+@@ -1818,6 +1925,7 @@ class VirtualizedList extends StateSafePureComponent {
+ const cellsAroundViewport = this._adjustCellsAroundViewport(
+ props,
+ state.cellsAroundViewport,
++ state.pendingScrollUpdateCount,
+ );
+ const renderMask = VirtualizedList._createRenderMask(
+ props,
+@@ -1848,7 +1956,7 @@ class VirtualizedList extends StateSafePureComponent {
+ return {
+ index,
+ item,
+- key: this._keyExtractor(item, index, props),
++ key: VirtualizedList._keyExtractor(item, index, props),
+ isViewable,
+ };
+ };
+@@ -1909,13 +2017,12 @@ class VirtualizedList extends StateSafePureComponent {
+ inLayout?: boolean,
+ ...
+ } => {
+- const {data, getItem, getItemCount, getItemLayout} = props;
++ const {data, getItemCount, getItemLayout} = props;
+ invariant(
+ index >= 0 && index < getItemCount(data),
+ 'Tried to get frame for out of range index ' + index,
+ );
+- const item = getItem(data, index);
+- const frame = this._frames[this._keyExtractor(item, index, props)];
++ const frame = this._frames[VirtualizedList._getItemKey(props, index)];
+ if (!frame || frame.index !== index) {
+ if (getItemLayout) {
+ /* $FlowFixMe[prop-missing] (>=0.63.0 site=react_native_fb) This comment
+@@ -1950,11 +2057,8 @@ class VirtualizedList extends StateSafePureComponent {
+ // where it is.
+ if (
+ focusedCellIndex >= itemCount ||
+- this._keyExtractor(
+- props.getItem(props.data, focusedCellIndex),
+- focusedCellIndex,
+- props,
+- ) !== this._lastFocusedCellKey
++ VirtualizedList._getItemKey(props, focusedCellIndex) !==
++ this._lastFocusedCellKey
+ ) {
+ return [];
+ }
+@@ -1995,6 +2099,11 @@ class VirtualizedList extends StateSafePureComponent {
+ props: FrameMetricProps,
+ cellsAroundViewport: {first: number, last: number},
+ ) {
++ // If we have any pending scroll updates it means that the scroll metrics
++ // are out of date and we should not call any of the visibility callbacks.
++ if (this.state.pendingScrollUpdateCount > 0) {
++ return;
++ }
+ this._viewabilityTuples.forEach(tuple => {
+ tuple.viewabilityHelper.onUpdate(
+ props,
diff --git a/patches/react-native-web+0.19.9+002+fix-mvcp.patch b/patches/react-native-web+0.19.9+002+fix-mvcp.patch
deleted file mode 100644
index afd681bba3b0..000000000000
--- a/patches/react-native-web+0.19.9+002+fix-mvcp.patch
+++ /dev/null
@@ -1,687 +0,0 @@
-diff --git a/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js b/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js
-index a6fe142..faeb323 100644
---- a/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js
-+++ b/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js
-@@ -293,7 +293,7 @@ class VirtualizedList extends StateSafePureComponent {
- // $FlowFixMe[missing-local-annot]
-
- constructor(_props) {
-- var _this$props$updateCel;
-+ var _this$props$updateCel, _this$props$maintainV, _this$props$maintainV2;
- super(_props);
- this._getScrollMetrics = () => {
- return this._scrollMetrics;
-@@ -532,6 +532,11 @@ class VirtualizedList extends StateSafePureComponent {
- visibleLength,
- zoomScale
- };
-+ if (this.state.pendingScrollUpdateCount > 0) {
-+ this.setState(state => ({
-+ pendingScrollUpdateCount: state.pendingScrollUpdateCount - 1
-+ }));
-+ }
- this._updateViewableItems(this.props, this.state.cellsAroundViewport);
- if (!this.props) {
- return;
-@@ -581,7 +586,7 @@ class VirtualizedList extends StateSafePureComponent {
- this._updateCellsToRender = () => {
- this._updateViewableItems(this.props, this.state.cellsAroundViewport);
- this.setState((state, props) => {
-- var cellsAroundViewport = this._adjustCellsAroundViewport(props, state.cellsAroundViewport);
-+ var cellsAroundViewport = this._adjustCellsAroundViewport(props, state.cellsAroundViewport, state.pendingScrollUpdateCount);
- var renderMask = VirtualizedList._createRenderMask(props, cellsAroundViewport, this._getNonViewportRenderRegions(props));
- if (cellsAroundViewport.first === state.cellsAroundViewport.first && cellsAroundViewport.last === state.cellsAroundViewport.last && renderMask.equals(state.renderMask)) {
- return null;
-@@ -601,7 +606,7 @@ class VirtualizedList extends StateSafePureComponent {
- return {
- index,
- item,
-- key: this._keyExtractor(item, index, props),
-+ key: VirtualizedList._keyExtractor(item, index, props),
- isViewable
- };
- };
-@@ -633,12 +638,10 @@ class VirtualizedList extends StateSafePureComponent {
- };
- this._getFrameMetrics = (index, props) => {
- var data = props.data,
-- getItem = props.getItem,
- getItemCount = props.getItemCount,
- getItemLayout = props.getItemLayout;
- invariant(index >= 0 && index < getItemCount(data), 'Tried to get frame for out of range index ' + index);
-- var item = getItem(data, index);
-- var frame = this._frames[this._keyExtractor(item, index, props)];
-+ var frame = this._frames[VirtualizedList._getItemKey(props, index)];
- if (!frame || frame.index !== index) {
- if (getItemLayout) {
- /* $FlowFixMe[prop-missing] (>=0.63.0 site=react_native_fb) This comment
-@@ -662,7 +665,7 @@ class VirtualizedList extends StateSafePureComponent {
-
- // The last cell we rendered may be at a new index. Bail if we don't know
- // where it is.
-- if (focusedCellIndex >= itemCount || this._keyExtractor(props.getItem(props.data, focusedCellIndex), focusedCellIndex, props) !== this._lastFocusedCellKey) {
-+ if (focusedCellIndex >= itemCount || VirtualizedList._getItemKey(props, focusedCellIndex) !== this._lastFocusedCellKey) {
- return [];
- }
- var first = focusedCellIndex;
-@@ -702,9 +705,15 @@ class VirtualizedList extends StateSafePureComponent {
- }
- }
- var initialRenderRegion = VirtualizedList._initialRenderRegion(_props);
-+ var minIndexForVisible = (_this$props$maintainV = (_this$props$maintainV2 = this.props.maintainVisibleContentPosition) == null ? void 0 : _this$props$maintainV2.minIndexForVisible) !== null && _this$props$maintainV !== void 0 ? _this$props$maintainV : 0;
- this.state = {
- cellsAroundViewport: initialRenderRegion,
-- renderMask: VirtualizedList._createRenderMask(_props, initialRenderRegion)
-+ renderMask: VirtualizedList._createRenderMask(_props, initialRenderRegion),
-+ firstVisibleItemKey: this.props.getItemCount(this.props.data) > minIndexForVisible ? VirtualizedList._getItemKey(this.props, minIndexForVisible) : null,
-+ // When we have a non-zero initialScrollIndex, we will receive a
-+ // scroll event later so this will prevent the window from updating
-+ // until we get a valid offset.
-+ pendingScrollUpdateCount: this.props.initialScrollIndex != null && this.props.initialScrollIndex > 0 ? 1 : 0
- };
-
- // REACT-NATIVE-WEB patch to preserve during future RN merges: Support inverted wheel scroller.
-@@ -715,7 +724,7 @@ class VirtualizedList extends StateSafePureComponent {
- var clientLength = this.props.horizontal ? ev.target.clientWidth : ev.target.clientHeight;
- var isEventTargetScrollable = scrollLength > clientLength;
- var delta = this.props.horizontal ? ev.deltaX || ev.wheelDeltaX : ev.deltaY || ev.wheelDeltaY;
-- var leftoverDelta = delta;
-+ var leftoverDelta = delta * 0.5;
- if (isEventTargetScrollable) {
- leftoverDelta = delta < 0 ? Math.min(delta + scrollOffset, 0) : Math.max(delta - (scrollLength - clientLength - scrollOffset), 0);
- }
-@@ -760,6 +769,26 @@ class VirtualizedList extends StateSafePureComponent {
- }
- }
- }
-+ static _findItemIndexWithKey(props, key, hint) {
-+ var itemCount = props.getItemCount(props.data);
-+ if (hint != null && hint >= 0 && hint < itemCount) {
-+ var curKey = VirtualizedList._getItemKey(props, hint);
-+ if (curKey === key) {
-+ return hint;
-+ }
-+ }
-+ for (var ii = 0; ii < itemCount; ii++) {
-+ var _curKey = VirtualizedList._getItemKey(props, ii);
-+ if (_curKey === key) {
-+ return ii;
-+ }
-+ }
-+ return null;
-+ }
-+ static _getItemKey(props, index) {
-+ var item = props.getItem(props.data, index);
-+ return VirtualizedList._keyExtractor(item, index, props);
-+ }
- static _createRenderMask(props, cellsAroundViewport, additionalRegions) {
- var itemCount = props.getItemCount(props.data);
- invariant(cellsAroundViewport.first >= 0 && cellsAroundViewport.last >= cellsAroundViewport.first - 1 && cellsAroundViewport.last < itemCount, "Invalid cells around viewport \"[" + cellsAroundViewport.first + ", " + cellsAroundViewport.last + "]\" was passed to VirtualizedList._createRenderMask");
-@@ -808,7 +837,7 @@ class VirtualizedList extends StateSafePureComponent {
- }
- }
- }
-- _adjustCellsAroundViewport(props, cellsAroundViewport) {
-+ _adjustCellsAroundViewport(props, cellsAroundViewport, pendingScrollUpdateCount) {
- var data = props.data,
- getItemCount = props.getItemCount;
- var onEndReachedThreshold = onEndReachedThresholdOrDefault(props.onEndReachedThreshold);
-@@ -831,17 +860,9 @@ class VirtualizedList extends StateSafePureComponent {
- last: Math.min(cellsAroundViewport.last + renderAhead, getItemCount(data) - 1)
- };
- } else {
-- // If we have a non-zero initialScrollIndex and run this before we've scrolled,
-- // we'll wipe out the initialNumToRender rendered elements starting at initialScrollIndex.
-- // So let's wait until we've scrolled the view to the right place. And until then,
-- // we will trust the initialScrollIndex suggestion.
--
-- // Thus, we want to recalculate the windowed render limits if any of the following hold:
-- // - initialScrollIndex is undefined or is 0
-- // - initialScrollIndex > 0 AND scrolling is complete
-- // - initialScrollIndex > 0 AND the end of the list is visible (this handles the case
-- // where the list is shorter than the visible area)
-- if (props.initialScrollIndex && !this._scrollMetrics.offset && Math.abs(distanceFromEnd) >= Number.EPSILON) {
-+ // If we have a pending scroll update, we should not adjust the render window as it
-+ // might override the correct window.
-+ if (pendingScrollUpdateCount > 0) {
- return cellsAroundViewport.last >= getItemCount(data) ? VirtualizedList._constrainToItemCount(cellsAroundViewport, props) : cellsAroundViewport;
- }
- newCellsAroundViewport = computeWindowedRenderLimits(props, maxToRenderPerBatchOrDefault(props.maxToRenderPerBatch), windowSizeOrDefault(props.windowSize), cellsAroundViewport, this.__getFrameMetricsApprox, this._scrollMetrics);
-@@ -914,16 +935,36 @@ class VirtualizedList extends StateSafePureComponent {
- }
- }
- static getDerivedStateFromProps(newProps, prevState) {
-+ var _newProps$maintainVis, _newProps$maintainVis2;
- // first and last could be stale (e.g. if a new, shorter items props is passed in), so we make
- // sure we're rendering a reasonable range here.
- var itemCount = newProps.getItemCount(newProps.data);
- if (itemCount === prevState.renderMask.numCells()) {
- return prevState;
- }
-- var constrainedCells = VirtualizedList._constrainToItemCount(prevState.cellsAroundViewport, newProps);
-+ var maintainVisibleContentPositionAdjustment = null;
-+ var prevFirstVisibleItemKey = prevState.firstVisibleItemKey;
-+ var minIndexForVisible = (_newProps$maintainVis = (_newProps$maintainVis2 = newProps.maintainVisibleContentPosition) == null ? void 0 : _newProps$maintainVis2.minIndexForVisible) !== null && _newProps$maintainVis !== void 0 ? _newProps$maintainVis : 0;
-+ var newFirstVisibleItemKey = newProps.getItemCount(newProps.data) > minIndexForVisible ? VirtualizedList._getItemKey(newProps, minIndexForVisible) : null;
-+ if (newProps.maintainVisibleContentPosition != null && prevFirstVisibleItemKey != null && newFirstVisibleItemKey != null) {
-+ if (newFirstVisibleItemKey !== prevFirstVisibleItemKey) {
-+ // Fast path if items were added at the start of the list.
-+ var hint = itemCount - prevState.renderMask.numCells() + minIndexForVisible;
-+ var firstVisibleItemIndex = VirtualizedList._findItemIndexWithKey(newProps, prevFirstVisibleItemKey, hint);
-+ maintainVisibleContentPositionAdjustment = firstVisibleItemIndex != null ? firstVisibleItemIndex - minIndexForVisible : null;
-+ } else {
-+ maintainVisibleContentPositionAdjustment = null;
-+ }
-+ }
-+ var constrainedCells = VirtualizedList._constrainToItemCount(maintainVisibleContentPositionAdjustment != null ? {
-+ first: prevState.cellsAroundViewport.first + maintainVisibleContentPositionAdjustment,
-+ last: prevState.cellsAroundViewport.last + maintainVisibleContentPositionAdjustment
-+ } : prevState.cellsAroundViewport, newProps);
- return {
- cellsAroundViewport: constrainedCells,
-- renderMask: VirtualizedList._createRenderMask(newProps, constrainedCells)
-+ renderMask: VirtualizedList._createRenderMask(newProps, constrainedCells),
-+ firstVisibleItemKey: newFirstVisibleItemKey,
-+ pendingScrollUpdateCount: maintainVisibleContentPositionAdjustment != null ? prevState.pendingScrollUpdateCount + 1 : prevState.pendingScrollUpdateCount
- };
- }
- _pushCells(cells, stickyHeaderIndices, stickyIndicesFromProps, first, last, inversionStyle) {
-@@ -946,7 +987,7 @@ class VirtualizedList extends StateSafePureComponent {
- last = Math.min(end, last);
- var _loop = function _loop() {
- var item = getItem(data, ii);
-- var key = _this._keyExtractor(item, ii, _this.props);
-+ var key = VirtualizedList._keyExtractor(item, ii, _this.props);
- _this._indicesToKeys.set(ii, key);
- if (stickyIndicesFromProps.has(ii + stickyOffset)) {
- _this.pushOrUnshift(stickyHeaderIndices, cells.length);
-@@ -981,20 +1022,23 @@ class VirtualizedList extends StateSafePureComponent {
- }
- static _constrainToItemCount(cells, props) {
- var itemCount = props.getItemCount(props.data);
-- var last = Math.min(itemCount - 1, cells.last);
-+ var lastPossibleCellIndex = itemCount - 1;
-+
-+ // Constraining `last` may significantly shrink the window. Adjust `first`
-+ // to expand the window if the new `last` results in a new window smaller
-+ // than the number of cells rendered per batch.
- var maxToRenderPerBatch = maxToRenderPerBatchOrDefault(props.maxToRenderPerBatch);
-+ var maxFirst = Math.max(0, lastPossibleCellIndex - maxToRenderPerBatch);
- return {
-- first: clamp(0, itemCount - 1 - maxToRenderPerBatch, cells.first),
-- last
-+ first: clamp(0, cells.first, maxFirst),
-+ last: Math.min(lastPossibleCellIndex, cells.last)
- };
- }
- _isNestedWithSameOrientation() {
- var nestedContext = this.context;
- return !!(nestedContext && !!nestedContext.horizontal === horizontalOrDefault(this.props.horizontal));
- }
-- _keyExtractor(item, index, props
-- // $FlowFixMe[missing-local-annot]
-- ) {
-+ static _keyExtractor(item, index, props) {
- if (props.keyExtractor != null) {
- return props.keyExtractor(item, index);
- }
-@@ -1034,7 +1078,12 @@ class VirtualizedList extends StateSafePureComponent {
- this.pushOrUnshift(cells, /*#__PURE__*/React.createElement(VirtualizedListCellContextProvider, {
- cellKey: this._getCellKey() + '-header',
- key: "$header"
-- }, /*#__PURE__*/React.createElement(View, {
-+ }, /*#__PURE__*/React.createElement(View
-+ // We expect that header component will be a single native view so make it
-+ // not collapsable to avoid this view being flattened and make this assumption
-+ // no longer true.
-+ , {
-+ collapsable: false,
- onLayout: this._onLayoutHeader,
- style: [inversionStyle, this.props.ListHeaderComponentStyle]
- },
-@@ -1136,7 +1185,11 @@ class VirtualizedList extends StateSafePureComponent {
- // TODO: Android support
- invertStickyHeaders: this.props.invertStickyHeaders !== undefined ? this.props.invertStickyHeaders : this.props.inverted,
- stickyHeaderIndices,
-- style: inversionStyle ? [inversionStyle, this.props.style] : this.props.style
-+ style: inversionStyle ? [inversionStyle, this.props.style] : this.props.style,
-+ maintainVisibleContentPosition: this.props.maintainVisibleContentPosition != null ? _objectSpread(_objectSpread({}, this.props.maintainVisibleContentPosition), {}, {
-+ // Adjust index to account for ListHeaderComponent.
-+ minIndexForVisible: this.props.maintainVisibleContentPosition.minIndexForVisible + (this.props.ListHeaderComponent ? 1 : 0)
-+ }) : undefined
- });
- this._hasMore = this.state.cellsAroundViewport.last < itemCount - 1;
- var innerRet = /*#__PURE__*/React.createElement(VirtualizedListContextProvider, {
-@@ -1319,8 +1372,12 @@ class VirtualizedList extends StateSafePureComponent {
- onStartReached = _this$props8.onStartReached,
- onStartReachedThreshold = _this$props8.onStartReachedThreshold,
- onEndReached = _this$props8.onEndReached,
-- onEndReachedThreshold = _this$props8.onEndReachedThreshold,
-- initialScrollIndex = _this$props8.initialScrollIndex;
-+ onEndReachedThreshold = _this$props8.onEndReachedThreshold;
-+ // If we have any pending scroll updates it means that the scroll metrics
-+ // are out of date and we should not call any of the edge reached callbacks.
-+ if (this.state.pendingScrollUpdateCount > 0) {
-+ return;
-+ }
- var _this$_scrollMetrics2 = this._scrollMetrics,
- contentLength = _this$_scrollMetrics2.contentLength,
- visibleLength = _this$_scrollMetrics2.visibleLength,
-@@ -1360,16 +1417,10 @@ class VirtualizedList extends StateSafePureComponent {
- // and call onStartReached only once for a given content length,
- // and only if onEndReached is not being executed
- else if (onStartReached != null && this.state.cellsAroundViewport.first === 0 && isWithinStartThreshold && this._scrollMetrics.contentLength !== this._sentStartForContentLength) {
-- // On initial mount when using initialScrollIndex the offset will be 0 initially
-- // and will trigger an unexpected onStartReached. To avoid this we can use
-- // timestamp to differentiate between the initial scroll metrics and when we actually
-- // received the first scroll event.
-- if (!initialScrollIndex || this._scrollMetrics.timestamp !== 0) {
-- this._sentStartForContentLength = this._scrollMetrics.contentLength;
-- onStartReached({
-- distanceFromStart
-- });
-- }
-+ this._sentStartForContentLength = this._scrollMetrics.contentLength;
-+ onStartReached({
-+ distanceFromStart
-+ });
- }
-
- // If the user scrolls away from the start or end and back again,
-@@ -1424,6 +1475,11 @@ class VirtualizedList extends StateSafePureComponent {
- }
- }
- _updateViewableItems(props, cellsAroundViewport) {
-+ // If we have any pending scroll updates it means that the scroll metrics
-+ // are out of date and we should not call any of the visibility callbacks.
-+ if (this.state.pendingScrollUpdateCount > 0) {
-+ return;
-+ }
- this._viewabilityTuples.forEach(tuple => {
- tuple.viewabilityHelper.onUpdate(props, this._scrollMetrics.offset, this._scrollMetrics.visibleLength, this._getFrameMetrics, this._createViewToken, tuple.onViewableItemsChanged, cellsAroundViewport);
- });
-diff --git a/node_modules/react-native-web/src/vendor/react-native/VirtualizedList/index.js b/node_modules/react-native-web/src/vendor/react-native/VirtualizedList/index.js
-index d896fb1..f303b31 100644
---- a/node_modules/react-native-web/src/vendor/react-native/VirtualizedList/index.js
-+++ b/node_modules/react-native-web/src/vendor/react-native/VirtualizedList/index.js
-@@ -75,6 +75,10 @@ type ViewabilityHelperCallbackTuple = {
- type State = {
- renderMask: CellRenderMask,
- cellsAroundViewport: {first: number, last: number},
-+ // Used to track items added at the start of the list for maintainVisibleContentPosition.
-+ firstVisibleItemKey: ?string,
-+ // When > 0 the scroll position available in JS is considered stale and should not be used.
-+ pendingScrollUpdateCount: number,
- };
-
- /**
-@@ -455,9 +459,24 @@ class VirtualizedList extends StateSafePureComponent {
-
- const initialRenderRegion = VirtualizedList._initialRenderRegion(props);
-
-+ const minIndexForVisible =
-+ this.props.maintainVisibleContentPosition?.minIndexForVisible ?? 0;
-+
- this.state = {
- cellsAroundViewport: initialRenderRegion,
- renderMask: VirtualizedList._createRenderMask(props, initialRenderRegion),
-+ firstVisibleItemKey:
-+ this.props.getItemCount(this.props.data) > minIndexForVisible
-+ ? VirtualizedList._getItemKey(this.props, minIndexForVisible)
-+ : null,
-+ // When we have a non-zero initialScrollIndex, we will receive a
-+ // scroll event later so this will prevent the window from updating
-+ // until we get a valid offset.
-+ pendingScrollUpdateCount:
-+ this.props.initialScrollIndex != null &&
-+ this.props.initialScrollIndex > 0
-+ ? 1
-+ : 0,
- };
-
- // REACT-NATIVE-WEB patch to preserve during future RN merges: Support inverted wheel scroller.
-@@ -470,7 +489,7 @@ class VirtualizedList extends StateSafePureComponent {
- const delta = this.props.horizontal
- ? ev.deltaX || ev.wheelDeltaX
- : ev.deltaY || ev.wheelDeltaY;
-- let leftoverDelta = delta;
-+ let leftoverDelta = delta * 5;
- if (isEventTargetScrollable) {
- leftoverDelta = delta < 0
- ? Math.min(delta + scrollOffset, 0)
-@@ -542,6 +561,40 @@ class VirtualizedList extends StateSafePureComponent {
- }
- }
-
-+ static _findItemIndexWithKey(
-+ props: Props,
-+ key: string,
-+ hint: ?number,
-+ ): ?number {
-+ const itemCount = props.getItemCount(props.data);
-+ if (hint != null && hint >= 0 && hint < itemCount) {
-+ const curKey = VirtualizedList._getItemKey(props, hint);
-+ if (curKey === key) {
-+ return hint;
-+ }
-+ }
-+ for (let ii = 0; ii < itemCount; ii++) {
-+ const curKey = VirtualizedList._getItemKey(props, ii);
-+ if (curKey === key) {
-+ return ii;
-+ }
-+ }
-+ return null;
-+ }
-+
-+ static _getItemKey(
-+ props: {
-+ data: Props['data'],
-+ getItem: Props['getItem'],
-+ keyExtractor: Props['keyExtractor'],
-+ ...
-+ },
-+ index: number,
-+ ): string {
-+ const item = props.getItem(props.data, index);
-+ return VirtualizedList._keyExtractor(item, index, props);
-+ }
-+
- static _createRenderMask(
- props: Props,
- cellsAroundViewport: {first: number, last: number},
-@@ -625,6 +678,7 @@ class VirtualizedList extends StateSafePureComponent {
- _adjustCellsAroundViewport(
- props: Props,
- cellsAroundViewport: {first: number, last: number},
-+ pendingScrollUpdateCount: number,
- ): {first: number, last: number} {
- const {data, getItemCount} = props;
- const onEndReachedThreshold = onEndReachedThresholdOrDefault(
-@@ -656,21 +710,9 @@ class VirtualizedList extends StateSafePureComponent {
- ),
- };
- } else {
-- // If we have a non-zero initialScrollIndex and run this before we've scrolled,
-- // we'll wipe out the initialNumToRender rendered elements starting at initialScrollIndex.
-- // So let's wait until we've scrolled the view to the right place. And until then,
-- // we will trust the initialScrollIndex suggestion.
--
-- // Thus, we want to recalculate the windowed render limits if any of the following hold:
-- // - initialScrollIndex is undefined or is 0
-- // - initialScrollIndex > 0 AND scrolling is complete
-- // - initialScrollIndex > 0 AND the end of the list is visible (this handles the case
-- // where the list is shorter than the visible area)
-- if (
-- props.initialScrollIndex &&
-- !this._scrollMetrics.offset &&
-- Math.abs(distanceFromEnd) >= Number.EPSILON
-- ) {
-+ // If we have a pending scroll update, we should not adjust the render window as it
-+ // might override the correct window.
-+ if (pendingScrollUpdateCount > 0) {
- return cellsAroundViewport.last >= getItemCount(data)
- ? VirtualizedList._constrainToItemCount(cellsAroundViewport, props)
- : cellsAroundViewport;
-@@ -779,14 +821,59 @@ class VirtualizedList extends StateSafePureComponent {
- return prevState;
- }
-
-+ let maintainVisibleContentPositionAdjustment: ?number = null;
-+ const prevFirstVisibleItemKey = prevState.firstVisibleItemKey;
-+ const minIndexForVisible =
-+ newProps.maintainVisibleContentPosition?.minIndexForVisible ?? 0;
-+ const newFirstVisibleItemKey =
-+ newProps.getItemCount(newProps.data) > minIndexForVisible
-+ ? VirtualizedList._getItemKey(newProps, minIndexForVisible)
-+ : null;
-+ if (
-+ newProps.maintainVisibleContentPosition != null &&
-+ prevFirstVisibleItemKey != null &&
-+ newFirstVisibleItemKey != null
-+ ) {
-+ if (newFirstVisibleItemKey !== prevFirstVisibleItemKey) {
-+ // Fast path if items were added at the start of the list.
-+ const hint =
-+ itemCount - prevState.renderMask.numCells() + minIndexForVisible;
-+ const firstVisibleItemIndex = VirtualizedList._findItemIndexWithKey(
-+ newProps,
-+ prevFirstVisibleItemKey,
-+ hint,
-+ );
-+ maintainVisibleContentPositionAdjustment =
-+ firstVisibleItemIndex != null
-+ ? firstVisibleItemIndex - minIndexForVisible
-+ : null;
-+ } else {
-+ maintainVisibleContentPositionAdjustment = null;
-+ }
-+ }
-+
- const constrainedCells = VirtualizedList._constrainToItemCount(
-- prevState.cellsAroundViewport,
-+ maintainVisibleContentPositionAdjustment != null
-+ ? {
-+ first:
-+ prevState.cellsAroundViewport.first +
-+ maintainVisibleContentPositionAdjustment,
-+ last:
-+ prevState.cellsAroundViewport.last +
-+ maintainVisibleContentPositionAdjustment,
-+ }
-+ : prevState.cellsAroundViewport,
- newProps,
- );
-
- return {
- cellsAroundViewport: constrainedCells,
- renderMask: VirtualizedList._createRenderMask(newProps, constrainedCells),
-+ firstVisibleItemKey: newFirstVisibleItemKey,
-+ pendingScrollUpdateCount:
-+ maintainVisibleContentPositionAdjustment != null
-+ ? prevState.pendingScrollUpdateCount + 1
-+ : prevState.pendingScrollUpdateCount,
- };
- }
-
-@@ -818,11 +905,11 @@ class VirtualizedList extends StateSafePureComponent {
-
- for (let ii = first; ii <= last; ii++) {
- const item = getItem(data, ii);
-- const key = this._keyExtractor(item, ii, this.props);
-+ const key = VirtualizedList._keyExtractor(item, ii, this.props);
-
- this._indicesToKeys.set(ii, key);
- if (stickyIndicesFromProps.has(ii + stickyOffset)) {
-- this.pushOrUnshift(stickyHeaderIndices, (cells.length));
-+ this.pushOrUnshift(stickyHeaderIndices, cells.length);
- }
-
- const shouldListenForLayout =
-@@ -861,15 +948,19 @@ class VirtualizedList extends StateSafePureComponent {
- props: Props,
- ): {first: number, last: number} {
- const itemCount = props.getItemCount(props.data);
-- const last = Math.min(itemCount - 1, cells.last);
-+ const lastPossibleCellIndex = itemCount - 1;
-
-+ // Constraining `last` may significantly shrink the window. Adjust `first`
-+ // to expand the window if the new `last` results in a new window smaller
-+ // than the number of cells rendered per batch.
- const maxToRenderPerBatch = maxToRenderPerBatchOrDefault(
- props.maxToRenderPerBatch,
- );
-+ const maxFirst = Math.max(0, lastPossibleCellIndex - maxToRenderPerBatch);
-
- return {
-- first: clamp(0, itemCount - 1 - maxToRenderPerBatch, cells.first),
-- last,
-+ first: clamp(0, cells.first, maxFirst),
-+ last: Math.min(lastPossibleCellIndex, cells.last),
- };
- }
-
-@@ -891,15 +982,14 @@ class VirtualizedList extends StateSafePureComponent {
- _getSpacerKey = (isVertical: boolean): string =>
- isVertical ? 'height' : 'width';
-
-- _keyExtractor(
-+ static _keyExtractor(
- item: Item,
- index: number,
- props: {
- keyExtractor?: ?(item: Item, index: number) => string,
- ...
- },
-- // $FlowFixMe[missing-local-annot]
-- ) {
-+ ): string {
- if (props.keyExtractor != null) {
- return props.keyExtractor(item, index);
- }
-@@ -945,6 +1035,10 @@ class VirtualizedList extends StateSafePureComponent {
- cellKey={this._getCellKey() + '-header'}
- key="$header">
- {
- style: inversionStyle
- ? [inversionStyle, this.props.style]
- : this.props.style,
-+ maintainVisibleContentPosition:
-+ this.props.maintainVisibleContentPosition != null
-+ ? {
-+ ...this.props.maintainVisibleContentPosition,
-+ // Adjust index to account for ListHeaderComponent.
-+ minIndexForVisible:
-+ this.props.maintainVisibleContentPosition.minIndexForVisible +
-+ (this.props.ListHeaderComponent ? 1 : 0),
-+ }
-+ : undefined,
- };
-
- this._hasMore = this.state.cellsAroundViewport.last < itemCount - 1;
-@@ -1255,11 +1359,10 @@ class VirtualizedList extends StateSafePureComponent {
- _defaultRenderScrollComponent = props => {
- const onRefresh = props.onRefresh;
- const inversionStyle = this.props.inverted
-- ? this.props.horizontal
-- ? styles.rowReverse
-- : styles.columnReverse
-- : null;
--
-+ ? this.props.horizontal
-+ ? styles.rowReverse
-+ : styles.columnReverse
-+ : null;
- if (this._isNestedWithSameOrientation()) {
- // $FlowFixMe[prop-missing] - Typing ReactNativeComponent revealed errors
- return ;
-@@ -1542,8 +1645,12 @@ class VirtualizedList extends StateSafePureComponent {
- onStartReachedThreshold,
- onEndReached,
- onEndReachedThreshold,
-- initialScrollIndex,
- } = this.props;
-+ // If we have any pending scroll updates it means that the scroll metrics
-+ // are out of date and we should not call any of the edge reached callbacks.
-+ if (this.state.pendingScrollUpdateCount > 0) {
-+ return;
-+ }
- const {contentLength, visibleLength, offset} = this._scrollMetrics;
- let distanceFromStart = offset;
- let distanceFromEnd = contentLength - visibleLength - offset;
-@@ -1595,14 +1702,8 @@ class VirtualizedList extends StateSafePureComponent {
- isWithinStartThreshold &&
- this._scrollMetrics.contentLength !== this._sentStartForContentLength
- ) {
-- // On initial mount when using initialScrollIndex the offset will be 0 initially
-- // and will trigger an unexpected onStartReached. To avoid this we can use
-- // timestamp to differentiate between the initial scroll metrics and when we actually
-- // received the first scroll event.
-- if (!initialScrollIndex || this._scrollMetrics.timestamp !== 0) {
-- this._sentStartForContentLength = this._scrollMetrics.contentLength;
-- onStartReached({distanceFromStart});
-- }
-+ this._sentStartForContentLength = this._scrollMetrics.contentLength;
-+ onStartReached({distanceFromStart});
- }
-
- // If the user scrolls away from the start or end and back again,
-@@ -1729,6 +1830,11 @@ class VirtualizedList extends StateSafePureComponent {
- visibleLength,
- zoomScale,
- };
-+ if (this.state.pendingScrollUpdateCount > 0) {
-+ this.setState(state => ({
-+ pendingScrollUpdateCount: state.pendingScrollUpdateCount - 1,
-+ }));
-+ }
- this._updateViewableItems(this.props, this.state.cellsAroundViewport);
- if (!this.props) {
- return;
-@@ -1844,6 +1950,7 @@ class VirtualizedList extends StateSafePureComponent {
- const cellsAroundViewport = this._adjustCellsAroundViewport(
- props,
- state.cellsAroundViewport,
-+ state.pendingScrollUpdateCount,
- );
- const renderMask = VirtualizedList._createRenderMask(
- props,
-@@ -1874,7 +1981,7 @@ class VirtualizedList extends StateSafePureComponent {
- return {
- index,
- item,
-- key: this._keyExtractor(item, index, props),
-+ key: VirtualizedList._keyExtractor(item, index, props),
- isViewable,
- };
- };
-@@ -1935,13 +2042,12 @@ class VirtualizedList extends StateSafePureComponent {
- inLayout?: boolean,
- ...
- } => {
-- const {data, getItem, getItemCount, getItemLayout} = props;
-+ const {data, getItemCount, getItemLayout} = props;
- invariant(
- index >= 0 && index < getItemCount(data),
- 'Tried to get frame for out of range index ' + index,
- );
-- const item = getItem(data, index);
-- const frame = this._frames[this._keyExtractor(item, index, props)];
-+ const frame = this._frames[VirtualizedList._getItemKey(props, index)];
- if (!frame || frame.index !== index) {
- if (getItemLayout) {
- /* $FlowFixMe[prop-missing] (>=0.63.0 site=react_native_fb) This comment
-@@ -1976,11 +2082,8 @@ class VirtualizedList extends StateSafePureComponent {
- // where it is.
- if (
- focusedCellIndex >= itemCount ||
-- this._keyExtractor(
-- props.getItem(props.data, focusedCellIndex),
-- focusedCellIndex,
-- props,
-- ) !== this._lastFocusedCellKey
-+ VirtualizedList._getItemKey(props, focusedCellIndex) !==
-+ this._lastFocusedCellKey
- ) {
- return [];
- }
-@@ -2021,6 +2124,11 @@ class VirtualizedList extends StateSafePureComponent {
- props: FrameMetricProps,
- cellsAroundViewport: {first: number, last: number},
- ) {
-+ // If we have any pending scroll updates it means that the scroll metrics
-+ // are out of date and we should not call any of the visibility callbacks.
-+ if (this.state.pendingScrollUpdateCount > 0) {
-+ return;
-+ }
- this._viewabilityTuples.forEach(tuple => {
- tuple.viewabilityHelper.onUpdate(
- props,
diff --git a/patches/react-native-web+0.19.9+003+measureInWindow.patch b/patches/react-native-web+0.19.9+002+measureInWindow.patch
similarity index 100%
rename from patches/react-native-web+0.19.9+003+measureInWindow.patch
rename to patches/react-native-web+0.19.9+002+measureInWindow.patch
diff --git a/patches/react-native-web+0.19.9+004+fix-pointer-events.patch b/patches/react-native-web+0.19.9+003+fix-pointer-events.patch
similarity index 100%
rename from patches/react-native-web+0.19.9+004+fix-pointer-events.patch
rename to patches/react-native-web+0.19.9+003+fix-pointer-events.patch
diff --git a/patches/react-native-web+0.19.9+004+fixLastSpacer.patch b/patches/react-native-web+0.19.9+004+fixLastSpacer.patch
new file mode 100644
index 000000000000..fc48c00094dc
--- /dev/null
+++ b/patches/react-native-web+0.19.9+004+fixLastSpacer.patch
@@ -0,0 +1,29 @@
+diff --git a/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js b/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js
+index faeb323..68d740a 100644
+--- a/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js
++++ b/node_modules/react-native-web/dist/vendor/react-native/VirtualizedList/index.js
+@@ -78,14 +78,6 @@ function scrollEventThrottleOrDefault(scrollEventThrottle) {
+ function windowSizeOrDefault(windowSize) {
+ return windowSize !== null && windowSize !== void 0 ? windowSize : 21;
+ }
+-function findLastWhere(arr, predicate) {
+- for (var i = arr.length - 1; i >= 0; i--) {
+- if (predicate(arr[i])) {
+- return arr[i];
+- }
+- }
+- return null;
+-}
+
+ /**
+ * Base implementation for the more convenient [``](https://reactnative.dev/docs/flatlist)
+@@ -1119,7 +1111,8 @@ class VirtualizedList extends StateSafePureComponent {
+ _keylessItemComponentName = '';
+ var spacerKey = this._getSpacerKey(!horizontal);
+ var renderRegions = this.state.renderMask.enumerateRegions();
+- var lastSpacer = findLastWhere(renderRegions, r => r.isSpacer);
++ var lastRegion = renderRegions[renderRegions.length - 1];
++ var lastSpacer = lastRegion?.isSpacer ? lastRegion : null;
+ for (var _iterator = _createForOfIteratorHelperLoose(renderRegions), _step; !(_step = _iterator()).done;) {
+ var section = _step.value;
+ if (section.isSpacer) {
diff --git a/src/CONST.ts b/src/CONST.ts
index 2fd592f539c2..b1a6b6895de7 100755
--- a/src/CONST.ts
+++ b/src/CONST.ts
@@ -269,7 +269,6 @@ const CONST = {
CHRONOS_IN_CASH: 'chronosInCash',
DEFAULT_ROOMS: 'defaultRooms',
BETA_COMMENT_LINKING: 'commentLinking',
- POLICY_ROOMS: 'policyRooms',
VIOLATIONS: 'violations',
REPORT_FIELDS: 'reportFields',
},
@@ -1181,6 +1180,11 @@ const CONST = {
EXPENSIFY: 'Expensify',
VBBA: 'ACH',
},
+ ACTION: {
+ EDIT: 'edit',
+ CREATE: 'create',
+ },
+ DEFAULT_AMOUNT: 0,
TYPE: {
SEND: 'send',
SPLIT: 'split',
@@ -1365,6 +1369,7 @@ const CONST = {
DIGITS_AND_PLUS: /^\+?[0-9]*$/,
ALPHABETIC_AND_LATIN_CHARS: /^[\p{Script=Latin} ]*$/u,
NON_ALPHABETIC_AND_NON_LATIN_CHARS: /[^\p{Script=Latin}]/gu,
+ ACCENT_LATIN_CHARS: /[\u00C0-\u017F]/g,
POSITIVE_INTEGER: /^\d+$/,
PO_BOX: /\b[P|p]?(OST|ost)?\.?\s*[O|o|0]?(ffice|FFICE)?\.?\s*[B|b][O|o|0]?[X|x]?\.?\s+[#]?(\d+)\b/,
ANY_VALUE: /^.+$/,
@@ -1422,6 +1427,7 @@ const CONST = {
ROUTES: {
VALIDATE_LOGIN: /\/v($|(\/\/*))/,
UNLINK_LOGIN: /\/u($|(\/\/*))/,
+ REDUNDANT_SLASHES: /(\/{2,})|(\/$)/g,
},
TIME_STARTS_01: /^01:\d{2} [AP]M$/,
@@ -2889,8 +2895,10 @@ const CONST = {
ATTACHMENT: 'common.attachment',
},
TEACHERS_UNITE: {
- PUBLIC_ROOM_ID: '7470147100835202',
- POLICY_ID: 'B795B6319125BDF2',
+ PROD_PUBLIC_ROOM_ID: '7470147100835202',
+ PROD_POLICY_ID: 'B795B6319125BDF2',
+ TEST_PUBLIC_ROOM_ID: '207591744844000',
+ TEST_POLICY_ID: 'ABD1345ED7293535',
POLICY_NAME: 'Expensify.org / Teachers Unite!',
PUBLIC_ROOM_NAME: '#teachers-unite',
},
@@ -2954,6 +2962,7 @@ const CONST = {
MAPBOX: {
PADDING: 50,
DEFAULT_ZOOM: 10,
+ SINGLE_MARKER_ZOOM: 15,
DEFAULT_COORDINATE: [-122.4021, 37.7911],
STYLE_URL: 'mapbox://styles/expensify/cllcoiqds00cs01r80kp34tmq',
},
@@ -3058,6 +3067,11 @@ const CONST = {
CAROUSEL: 3,
},
+ BRICK_ROAD: {
+ GBR: 'GBR',
+ RBR: 'RBR',
+ },
+
VIOLATIONS: {
ALL_TAG_LEVELS_REQUIRED: 'allTagLevelsRequired',
AUTO_REPORTED_REJECTED_EXPENSE: 'autoReportedRejectedExpense',
diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts
index 89ddbdc06883..98e3856f4544 100755
--- a/src/ONYXKEYS.ts
+++ b/src/ONYXKEYS.ts
@@ -458,6 +458,7 @@ type OnyxValues = {
[ONYXKEYS.COLLECTION.REPORT_USER_IS_LEAVING_ROOM]: boolean;
[ONYXKEYS.COLLECTION.SECURITY_GROUP]: OnyxTypes.SecurityGroup;
[ONYXKEYS.COLLECTION.TRANSACTION]: OnyxTypes.Transaction;
+ [ONYXKEYS.COLLECTION.TRANSACTION_DRAFT]: OnyxTypes.Transaction;
[ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS]: OnyxTypes.RecentlyUsedTags;
[ONYXKEYS.COLLECTION.SELECTED_TAB]: string;
[ONYXKEYS.COLLECTION.PRIVATE_NOTES_DRAFT]: string;
diff --git a/src/ROUTES.ts b/src/ROUTES.ts
index b6e62814466b..7538a16d1a2c 100644
--- a/src/ROUTES.ts
+++ b/src/ROUTES.ts
@@ -314,13 +314,13 @@ const ROUTES = {
getRoute: (iouType: ValueOf, transactionID: string, reportID: string) => `create/${iouType}/start/${transactionID}/${reportID}` as const,
},
MONEY_REQUEST_STEP_CONFIRMATION: {
- route: 'create/:iouType/confirmation/:transactionID/:reportID/',
- getRoute: (iouType: ValueOf, transactionID: string, reportID: string) => `create/${iouType}/confirmation/${transactionID}/${reportID}/` as const,
+ route: 'create/:iouType/confirmation/:transactionID/:reportID',
+ getRoute: (iouType: ValueOf, transactionID: string, reportID: string) => `create/${iouType}/confirmation/${transactionID}/${reportID}` as const,
},
MONEY_REQUEST_STEP_AMOUNT: {
- route: 'create/:iouType/amount/:transactionID/:reportID/',
+ route: 'create/:iouType/amount/:transactionID/:reportID',
getRoute: (iouType: ValueOf, transactionID: string, reportID: string, backTo = '') =>
- getUrlWithBackToParam(`create/${iouType}/amount/${transactionID}/${reportID}/`, backTo),
+ getUrlWithBackToParam(`create/${iouType}/amount/${transactionID}/${reportID}`, backTo),
},
MONEY_REQUEST_STEP_TAX_RATE: {
route: 'create/:iouType/taxRate/:transactionID/:reportID?',
@@ -333,52 +333,52 @@ const ROUTES = {
getUrlWithBackToParam(`create/${iouType}/taxAmount/${transactionID}/${reportID}`, backTo),
},
MONEY_REQUEST_STEP_CATEGORY: {
- route: 'create/:iouType/category/:transactionID/:reportID/',
+ route: 'create/:iouType/category/:transactionID/:reportID',
getRoute: (iouType: ValueOf, transactionID: string, reportID: string, backTo = '') =>
- getUrlWithBackToParam(`create/${iouType}/category/${transactionID}/${reportID}/`, backTo),
+ getUrlWithBackToParam(`create/${iouType}/category/${transactionID}/${reportID}`, backTo),
},
MONEY_REQUEST_STEP_CURRENCY: {
- route: 'create/:iouType/currency/:transactionID/:reportID/:pageIndex?/',
+ route: 'create/:iouType/currency/:transactionID/:reportID/:pageIndex?',
getRoute: (iouType: ValueOf, transactionID: string, reportID: string, pageIndex = '', backTo = '') =>
getUrlWithBackToParam(`create/${iouType}/currency/${transactionID}/${reportID}/${pageIndex}`, backTo),
},
MONEY_REQUEST_STEP_DATE: {
- route: 'create/:iouType/date/:transactionID/:reportID/',
+ route: 'create/:iouType/date/:transactionID/:reportID',
getRoute: (iouType: ValueOf, transactionID: string, reportID: string, backTo = '') =>
- getUrlWithBackToParam(`create/${iouType}/date/${transactionID}/${reportID}/`, backTo),
+ getUrlWithBackToParam(`create/${iouType}/date/${transactionID}/${reportID}`, backTo),
},
MONEY_REQUEST_STEP_DESCRIPTION: {
- route: 'create/:iouType/description/:transactionID/:reportID/',
+ route: 'create/:iouType/description/:transactionID/:reportID',
getRoute: (iouType: ValueOf, transactionID: string, reportID: string, backTo = '') =>
- getUrlWithBackToParam(`create/${iouType}/description/${transactionID}/${reportID}/`, backTo),
+ getUrlWithBackToParam(`create/${iouType}/description/${transactionID}/${reportID}`, backTo),
},
MONEY_REQUEST_STEP_DISTANCE: {
- route: 'create/:iouType/distance/:transactionID/:reportID/',
+ route: 'create/:iouType/distance/:transactionID/:reportID',
getRoute: (iouType: ValueOf, transactionID: string, reportID: string, backTo = '') =>
- getUrlWithBackToParam(`create/${iouType}/distance/${transactionID}/${reportID}/`, backTo),
+ getUrlWithBackToParam(`create/${iouType}/distance/${transactionID}/${reportID}`, backTo),
},
MONEY_REQUEST_STEP_MERCHANT: {
- route: 'create/:iouType/merchant/:transactionID/:reportID/',
+ route: 'create/:iouType/merchant/:transactionID/:reportID',
getRoute: (iouType: ValueOf, transactionID: string, reportID: string, backTo = '') =>
- getUrlWithBackToParam(`create/${iouType}/merchant/${transactionID}/${reportID}/`, backTo),
+ getUrlWithBackToParam(`create/${iouType}/merchant/${transactionID}/${reportID}`, backTo),
},
MONEY_REQUEST_STEP_PARTICIPANTS: {
- route: 'create/:iouType/participants/:transactionID/:reportID/',
+ route: 'create/:iouType/participants/:transactionID/:reportID',
getRoute: (iouType: ValueOf, transactionID: string, reportID: string, backTo = '') =>
- getUrlWithBackToParam(`create/${iouType}/participants/${transactionID}/${reportID}/`, backTo),
+ getUrlWithBackToParam(`create/${iouType}/participants/${transactionID}/${reportID}`, backTo),
},
MONEY_REQUEST_STEP_SCAN: {
- route: 'create/:iouType/scan/:transactionID/:reportID/',
- getRoute: (iouType: ValueOf, transactionID: string, reportID: string, backTo = '') =>
- getUrlWithBackToParam(`create/${iouType}/scan/${transactionID}/${reportID}/`, backTo),
+ route: ':action/:iouType/scan/:transactionID/:reportID',
+ getRoute: (action: ValueOf, iouType: ValueOf, transactionID: string, reportID: string, backTo = '') =>
+ getUrlWithBackToParam(`${action}/${iouType}/scan/${transactionID}/${reportID}`, backTo),
},
MONEY_REQUEST_STEP_TAG: {
- route: 'create/:iouType/tag/:transactionID/:reportID/',
+ route: 'create/:iouType/tag/:transactionID/:reportID',
getRoute: (iouType: ValueOf, transactionID: string, reportID: string, backTo = '') =>
- getUrlWithBackToParam(`create/${iouType}/tag/${transactionID}/${reportID}/`, backTo),
+ getUrlWithBackToParam(`create/${iouType}/tag/${transactionID}/${reportID}`, backTo),
},
MONEY_REQUEST_STEP_WAYPOINT: {
- route: 'create/:iouType/waypoint/:transactionID/:reportID/:pageIndex/',
+ route: 'create/:iouType/waypoint/:transactionID/:reportID/:pageIndex',
getRoute: (iouType: ValueOf, transactionID: string, reportID: string, pageIndex = '', backTo = '') =>
getUrlWithBackToParam(`create/${iouType}/waypoint/${transactionID}/${reportID}/${pageIndex}`, backTo),
},
diff --git a/src/components/AddPlaidBankAccount.js b/src/components/AddPlaidBankAccount.js
index 656694a785a3..a5160a13f8e9 100644
--- a/src/components/AddPlaidBankAccount.js
+++ b/src/components/AddPlaidBankAccount.js
@@ -249,7 +249,6 @@ function AddPlaidBankAccount({
height={iconSize}
width={iconSize}
additionalStyles={iconStyles}
- fill={theme.icon}
/>
{bankName}
diff --git a/src/components/AmountTextInput.js b/src/components/AmountTextInput.js
deleted file mode 100644
index 231a99f0e6a6..000000000000
--- a/src/components/AmountTextInput.js
+++ /dev/null
@@ -1,89 +0,0 @@
-import PropTypes from 'prop-types';
-import React from 'react';
-import useStyleUtils from '@hooks/useStyleUtils';
-import useThemeStyles from '@hooks/useThemeStyles';
-import CONST from '@src/CONST';
-import refPropTypes from './refPropTypes';
-import TextInput from './TextInput';
-
-const propTypes = {
- /** Formatted amount in local currency */
- formattedAmount: PropTypes.string.isRequired,
-
- /** A ref to forward to amount text input */
- forwardedRef: refPropTypes,
-
- /** Function to call when amount in text input is changed */
- onChangeAmount: PropTypes.func.isRequired,
-
- /** Placeholder value for amount text input */
- placeholder: PropTypes.string.isRequired,
-
- /** Selection Object */
- selection: PropTypes.shape({
- start: PropTypes.number,
- end: PropTypes.number,
- }),
-
- /** Function to call when selection in text input is changed */
- onSelectionChange: PropTypes.func,
-
- /** Style for the input */
- style: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.object), PropTypes.object]),
-
- /** Style for the container */
- touchableInputWrapperStyle: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.object), PropTypes.object]),
-
- /** Function to call to handle key presses in the text input */
- onKeyPress: PropTypes.func,
-};
-
-const defaultProps = {
- forwardedRef: undefined,
- selection: undefined,
- onSelectionChange: () => {},
- onKeyPress: () => {},
- style: {},
- touchableInputWrapperStyle: {},
-};
-
-function AmountTextInput(props) {
- const styles = useThemeStyles();
- const StyleUtils = useStyleUtils();
- return (
-
- );
-}
-
-AmountTextInput.propTypes = propTypes;
-AmountTextInput.defaultProps = defaultProps;
-AmountTextInput.displayName = 'AmountTextInput';
-
-const AmountTextInputWithRef = React.forwardRef((props, ref) => (
-
-));
-
-AmountTextInputWithRef.displayName = 'AmountTextInputWithRef';
-
-export default AmountTextInputWithRef;
diff --git a/src/components/AmountTextInput.tsx b/src/components/AmountTextInput.tsx
new file mode 100644
index 000000000000..0f3416076cc0
--- /dev/null
+++ b/src/components/AmountTextInput.tsx
@@ -0,0 +1,64 @@
+import React from 'react';
+import type {StyleProp, TextStyle, ViewStyle} from 'react-native';
+import useThemeStyles from '@hooks/useThemeStyles';
+import CONST from '@src/CONST';
+import type {TextSelection} from './Composer/types';
+import TextInput from './TextInput';
+import type {BaseTextInputRef} from './TextInput/BaseTextInput/types';
+
+type AmountTextInputProps = {
+ /** Formatted amount in local currency */
+ formattedAmount: string;
+
+ /** Function to call when amount in text input is changed */
+ onChangeAmount: (amount: string) => void;
+
+ /** Placeholder value for amount text input */
+ placeholder: string;
+
+ /** Selection Object */
+ selection?: TextSelection;
+
+ /** Function to call when selection in text input is changed */
+ onSelectionChange?: () => void;
+
+ /** Style for the input */
+ style?: StyleProp;
+
+ /** Style for the container */
+ touchableInputWrapperStyle?: StyleProp;
+
+ /** Function to call to handle key presses in the text input */
+ onKeyPress?: () => void;
+};
+
+function AmountTextInput(
+ {formattedAmount, onChangeAmount, placeholder, selection, onSelectionChange, style, touchableInputWrapperStyle, onKeyPress}: AmountTextInputProps,
+ ref: BaseTextInputRef,
+) {
+ const styles = useThemeStyles();
+ return (
+
+ );
+}
+
+AmountTextInput.displayName = 'AmountTextInput';
+
+export default React.forwardRef(AmountTextInput);
diff --git a/src/components/AttachmentModal.js b/src/components/AttachmentModal.js
index 1b4d350f7d4f..149dd7039151 100755
--- a/src/components/AttachmentModal.js
+++ b/src/components/AttachmentModal.js
@@ -383,7 +383,15 @@ function AttachmentModal(props) {
text: props.translate('common.replace'),
onSelected: () => {
closeModal();
- Navigation.navigate(ROUTES.EDIT_REQUEST.getRoute(props.report.reportID, CONST.EDIT_REQUEST_FIELD.RECEIPT));
+ Navigation.navigate(
+ ROUTES.MONEY_REQUEST_STEP_SCAN.getRoute(
+ CONST.IOU.ACTION.EDIT,
+ CONST.IOU.TYPE.REQUEST,
+ props.transaction.transactionID,
+ props.report.reportID,
+ Navigation.getActiveRouteWithoutParams(),
+ ),
+ );
},
});
}
diff --git a/src/components/AutoCompleteSuggestions/BaseAutoCompleteSuggestions.tsx b/src/components/AutoCompleteSuggestions/BaseAutoCompleteSuggestions.tsx
index fc3bf4659bd7..5da9c6981603 100644
--- a/src/components/AutoCompleteSuggestions/BaseAutoCompleteSuggestions.tsx
+++ b/src/components/AutoCompleteSuggestions/BaseAutoCompleteSuggestions.tsx
@@ -107,7 +107,7 @@ function BaseAutoCompleteSuggestions(
keyExtractor={keyExtractor}
removeClippedSubviews={false}
showsVerticalScrollIndicator={innerHeight > rowHeight.value}
- extraData={highlightedSuggestionIndex}
+ extraData={[highlightedSuggestionIndex, renderSuggestionMenuItem]}
/>
diff --git a/src/components/AvatarCropModal/ImageCropView.js b/src/components/AvatarCropModal/ImageCropView.js
index ff91a654f5dd..92cbe3a4da04 100644
--- a/src/components/AvatarCropModal/ImageCropView.js
+++ b/src/components/AvatarCropModal/ImageCropView.js
@@ -90,7 +90,7 @@ function ImageCropView(props) {
diff --git a/src/components/AvatarWithDisplayName.tsx b/src/components/AvatarWithDisplayName.tsx
index 4580f3b7e4d4..e9e1054427b9 100644
--- a/src/components/AvatarWithDisplayName.tsx
+++ b/src/components/AvatarWithDisplayName.tsx
@@ -141,6 +141,7 @@ function AvatarWithDisplayName({
)}
{!!subtitle && (
diff --git a/src/components/BaseMiniContextMenuItem.tsx b/src/components/BaseMiniContextMenuItem.tsx
index 1f9a14cdfdee..7bed44cd8f13 100644
--- a/src/components/BaseMiniContextMenuItem.tsx
+++ b/src/components/BaseMiniContextMenuItem.tsx
@@ -8,6 +8,7 @@ import DomUtils from '@libs/DomUtils';
import getButtonState from '@libs/getButtonState';
import ReportActionComposeFocusManager from '@libs/ReportActionComposeFocusManager';
import variables from '@styles/variables';
+import CONST from '@src/CONST';
import PressableWithoutFeedback from './Pressable/PressableWithoutFeedback';
import Tooltip from './Tooltip/PopoverAnchorTooltip';
@@ -66,6 +67,7 @@ function BaseMiniContextMenuItem({tooltipText, onPress, children, isDelayButtonS
event.preventDefault();
}}
accessibilityLabel={tooltipText}
+ role={CONST.ROLE.BUTTON}
style={({hovered, pressed}) => [
styles.reportActionContextMenuMiniButton,
StyleUtils.getButtonBackgroundColorStyle(getButtonState(hovered, pressed, isDelayButtonStateComplete)),
diff --git a/src/components/Button/index.tsx b/src/components/Button/index.tsx
index dd0499d4d243..f8b820d559b7 100644
--- a/src/components/Button/index.tsx
+++ b/src/components/Button/index.tsx
@@ -1,6 +1,6 @@
-import {useIsFocused} from '@react-navigation/native';
+import {useFocusEffect} from '@react-navigation/native';
import type {ForwardedRef} from 'react';
-import React, {useCallback} from 'react';
+import React, {memo, useCallback, useMemo, useRef} from 'react';
import type {GestureResponderEvent, StyleProp, TextStyle, ViewStyle} from 'react-native';
import {ActivityIndicator, View} from 'react-native';
import Icon from '@components/Icon';
@@ -8,7 +8,7 @@ import * as Expensicons from '@components/Icon/Expensicons';
import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
import Text from '@components/Text';
import withNavigationFallback from '@components/withNavigationFallback';
-import useActiveElement from '@hooks/useActiveElement';
+import useActiveElementRole from '@hooks/useActiveElementRole';
import useKeyboardShortcut from '@hooks/useKeyboardShortcut';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
@@ -118,6 +118,57 @@ type ButtonProps = (ButtonWithText | ChildrenProps) & {
accessibilityLabel?: string;
};
+type KeyboardShortcutComponentProps = Pick;
+
+const accessibilityRoles: string[] = Object.values(CONST.ACCESSIBILITY_ROLE);
+
+const KeyboardShortcutComponent = memo(
+ ({isDisabled = false, isLoading = false, onPress = () => {}, pressOnEnter, allowBubble, enterKeyEventListenerPriority}: KeyboardShortcutComponentProps) => {
+ const isFocused = useRef(false);
+ const activeElementRole = useActiveElementRole();
+
+ const shouldDisableEnterShortcut = useMemo(() => accessibilityRoles.includes(activeElementRole ?? '') && activeElementRole !== CONST.ACCESSIBILITY_ROLE.TEXT, [activeElementRole]);
+
+ useFocusEffect(
+ useCallback(() => {
+ isFocused.current = true;
+
+ return () => {
+ isFocused.current = false;
+ };
+ }, []),
+ );
+
+ const keyboardShortcutCallback = useCallback(
+ (event?: GestureResponderEvent | KeyboardEvent) => {
+ if (!validateSubmitShortcut(isDisabled, isLoading, event)) {
+ return;
+ }
+ onPress();
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [isDisabled, isLoading],
+ );
+
+ const config = useMemo(
+ () => ({
+ isActive: pressOnEnter && !shouldDisableEnterShortcut && isFocused.current,
+ shouldBubble: allowBubble,
+ priority: enterKeyEventListenerPriority,
+ shouldPreventDefault: false,
+ }),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [shouldDisableEnterShortcut],
+ );
+
+ useKeyboardShortcut(CONST.KEYBOARD_SHORTCUTS.ENTER, keyboardShortcutCallback, config);
+
+ return null;
+ },
+);
+
+KeyboardShortcutComponent.displayName = 'KeyboardShortcutComponent';
+
function Button(
{
allowBubble = false,
@@ -164,27 +215,6 @@ function Button(
) {
const theme = useTheme();
const styles = useThemeStyles();
- const isFocused = useIsFocused();
- const activeElement = useActiveElement();
- const accessibilityRoles: string[] = Object.values(CONST.ACCESSIBILITY_ROLE);
- const shouldDisableEnterShortcut = accessibilityRoles.includes(activeElement?.role ?? '') && activeElement?.role !== CONST.ACCESSIBILITY_ROLE.TEXT;
-
- const keyboardShortcutCallback = useCallback(
- (event?: GestureResponderEvent | KeyboardEvent) => {
- if (!validateSubmitShortcut(isFocused, isDisabled, isLoading, event)) {
- return;
- }
- onPress();
- },
- [isDisabled, isFocused, isLoading, onPress],
- );
-
- useKeyboardShortcut(CONST.KEYBOARD_SHORTCUTS.ENTER, keyboardShortcutCallback, {
- isActive: pressOnEnter && !shouldDisableEnterShortcut,
- shouldBubble: allowBubble,
- priority: enterKeyEventListenerPriority,
- shouldPreventDefault: false,
- });
const renderContent = () => {
if ('children' in rest) {
@@ -247,72 +277,82 @@ function Button(
};
return (
- {
- if (event?.type === 'click') {
- const currentTarget = event?.currentTarget as HTMLElement;
- currentTarget?.blur();
- }
-
- if (shouldEnableHapticFeedback) {
- HapticFeedback.press();
- }
- return onPress(event);
- }}
- onLongPress={(event) => {
- if (isLongPressDisabled) {
- return;
- }
- if (shouldEnableHapticFeedback) {
- HapticFeedback.longPress();
- }
- onLongPress(event);
- }}
- onPressIn={onPressIn}
- onPressOut={onPressOut}
- onMouseDown={onMouseDown}
- disabled={isLoading || isDisabled}
- wrapperStyle={[
- isDisabled ? {...styles.cursorDisabled, ...styles.noSelect} : {},
- styles.buttonContainer,
- shouldRemoveRightBorderRadius ? styles.noRightBorderRadius : undefined,
- shouldRemoveLeftBorderRadius ? styles.noLeftBorderRadius : undefined,
- style,
- ]}
- style={[
- styles.button,
- small ? styles.buttonSmall : undefined,
- medium ? styles.buttonMedium : undefined,
- large ? styles.buttonLarge : undefined,
- success ? styles.buttonSuccess : undefined,
- danger ? styles.buttonDanger : undefined,
- isDisabled && (success || danger) ? styles.buttonOpacityDisabled : undefined,
- isDisabled && !danger && !success ? styles.buttonDisabled : undefined,
- shouldRemoveRightBorderRadius ? styles.noRightBorderRadius : undefined,
- shouldRemoveLeftBorderRadius ? styles.noLeftBorderRadius : undefined,
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
- 'text' in rest && (rest?.icon || rest?.shouldShowRightIcon) ? styles.alignItemsStretch : undefined,
- innerStyles,
- ]}
- hoverStyle={[
- shouldUseDefaultHover && !isDisabled ? styles.buttonDefaultHovered : undefined,
- success && !isDisabled ? styles.buttonSuccessHovered : undefined,
- danger && !isDisabled ? styles.buttonDangerHovered : undefined,
- ]}
- id={id}
- accessibilityLabel={accessibilityLabel}
- role={CONST.ROLE.BUTTON}
- hoverDimmingValue={1}
- >
- {renderContent()}
- {isLoading && (
-
- )}
-
+ <>
+
+ {
+ if (event?.type === 'click') {
+ const currentTarget = event?.currentTarget as HTMLElement;
+ currentTarget?.blur();
+ }
+
+ if (shouldEnableHapticFeedback) {
+ HapticFeedback.press();
+ }
+ return onPress(event);
+ }}
+ onLongPress={(event) => {
+ if (isLongPressDisabled) {
+ return;
+ }
+ if (shouldEnableHapticFeedback) {
+ HapticFeedback.longPress();
+ }
+ onLongPress(event);
+ }}
+ onPressIn={onPressIn}
+ onPressOut={onPressOut}
+ onMouseDown={onMouseDown}
+ disabled={isLoading || isDisabled}
+ wrapperStyle={[
+ isDisabled ? {...styles.cursorDisabled, ...styles.noSelect} : {},
+ styles.buttonContainer,
+ shouldRemoveRightBorderRadius ? styles.noRightBorderRadius : undefined,
+ shouldRemoveLeftBorderRadius ? styles.noLeftBorderRadius : undefined,
+ style,
+ ]}
+ style={[
+ styles.button,
+ small ? styles.buttonSmall : undefined,
+ medium ? styles.buttonMedium : undefined,
+ large ? styles.buttonLarge : undefined,
+ success ? styles.buttonSuccess : undefined,
+ danger ? styles.buttonDanger : undefined,
+ isDisabled && (success || danger) ? styles.buttonOpacityDisabled : undefined,
+ isDisabled && !danger && !success ? styles.buttonDisabled : undefined,
+ shouldRemoveRightBorderRadius ? styles.noRightBorderRadius : undefined,
+ shouldRemoveLeftBorderRadius ? styles.noLeftBorderRadius : undefined,
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
+ 'text' in rest && (rest?.icon || rest?.shouldShowRightIcon) ? styles.alignItemsStretch : undefined,
+ innerStyles,
+ ]}
+ hoverStyle={[
+ shouldUseDefaultHover && !isDisabled ? styles.buttonDefaultHovered : undefined,
+ success && !isDisabled ? styles.buttonSuccessHovered : undefined,
+ danger && !isDisabled ? styles.buttonDangerHovered : undefined,
+ ]}
+ id={id}
+ accessibilityLabel={accessibilityLabel}
+ role={CONST.ROLE.BUTTON}
+ hoverDimmingValue={1}
+ >
+ {renderContent()}
+ {isLoading && (
+
+ )}
+
+ >
);
}
diff --git a/src/components/Button/validateSubmitShortcut/index.native.ts b/src/components/Button/validateSubmitShortcut/index.native.ts
index 3f277ed208a1..4602b40c832f 100644
--- a/src/components/Button/validateSubmitShortcut/index.native.ts
+++ b/src/components/Button/validateSubmitShortcut/index.native.ts
@@ -3,14 +3,13 @@ import type ValidateSubmitShortcut from './types';
/**
* Validate if the submit shortcut should be triggered depending on the button state
*
- * @param isFocused Whether Button is on active screen
* @param isDisabled Indicates whether the button should be disabled
* @param isLoading Indicates whether the button should be disabled and in the loading state
* @return Returns `true` if the shortcut should be triggered
*/
-const validateSubmitShortcut: ValidateSubmitShortcut = (isFocused, isDisabled, isLoading) => {
- if (!isFocused || isDisabled || isLoading) {
+const validateSubmitShortcut: ValidateSubmitShortcut = (isDisabled, isLoading) => {
+ if (isDisabled || isLoading) {
return false;
}
diff --git a/src/components/Button/validateSubmitShortcut/index.ts b/src/components/Button/validateSubmitShortcut/index.ts
index 695c56af7bb7..f8cea44f73d6 100644
--- a/src/components/Button/validateSubmitShortcut/index.ts
+++ b/src/components/Button/validateSubmitShortcut/index.ts
@@ -3,16 +3,15 @@ import type ValidateSubmitShortcut from './types';
/**
* Validate if the submit shortcut should be triggered depending on the button state
*
- * @param isFocused Whether Button is on active screen
* @param isDisabled Indicates whether the button should be disabled
* @param isLoading Indicates whether the button should be disabled and in the loading state
* @param event Focused input event
* @returns Returns `true` if the shortcut should be triggered
*/
-const validateSubmitShortcut: ValidateSubmitShortcut = (isFocused, isDisabled, isLoading, event) => {
+const validateSubmitShortcut: ValidateSubmitShortcut = (isDisabled, isLoading, event) => {
const eventTarget = event?.target as HTMLElement;
- if (!isFocused || isDisabled || isLoading || eventTarget.nodeName === 'TEXTAREA') {
+ if (isDisabled || isLoading || eventTarget.nodeName === 'TEXTAREA') {
return false;
}
diff --git a/src/components/Button/validateSubmitShortcut/types.ts b/src/components/Button/validateSubmitShortcut/types.ts
index 088718d0334e..d1ff24fb0510 100644
--- a/src/components/Button/validateSubmitShortcut/types.ts
+++ b/src/components/Button/validateSubmitShortcut/types.ts
@@ -1,5 +1,5 @@
import type {GestureResponderEvent} from 'react-native';
-type ValidateSubmitShortcut = (isFocused: boolean, isDisabled: boolean, isLoading: boolean, event?: GestureResponderEvent | KeyboardEvent) => boolean;
+type ValidateSubmitShortcut = (isDisabled: boolean, isLoading: boolean, event?: GestureResponderEvent | KeyboardEvent) => boolean;
export default ValidateSubmitShortcut;
diff --git a/src/components/CheckboxWithLabel.tsx b/src/components/CheckboxWithLabel.tsx
index a25ccf184f52..602fb154deba 100644
--- a/src/components/CheckboxWithLabel.tsx
+++ b/src/components/CheckboxWithLabel.tsx
@@ -42,7 +42,7 @@ type CheckboxWithLabelProps = RequiredLabelProps & {
/** Error text to display */
errorText?: string;
- /** Value for checkbox. This prop is intended to be set by Form.js only */
+ /** Value for checkbox. This prop is intended to be set by FormProvider only */
value?: boolean;
/** The default value for the checkbox */
diff --git a/src/components/Composer/types.ts b/src/components/Composer/types.ts
index bfdcb6715d40..d8d88970ea78 100644
--- a/src/components/Composer/types.ts
+++ b/src/components/Composer/types.ts
@@ -6,6 +6,12 @@ type TextSelection = {
};
type ComposerProps = {
+ /** identify id in the text input */
+ id?: string;
+
+ /** Indicate whether input is multiline */
+ multiline?: boolean;
+
/** Maximum number of lines in the text input */
maxLines?: number;
@@ -18,6 +24,9 @@ type ComposerProps = {
/** Number of lines for the comment */
numberOfLines?: number;
+ /** Callback method handle when the input is changed */
+ onChangeText?: (numberOfLines: string) => void;
+
/** Callback method to update number of lines for the comment */
onNumberOfLinesChange?: (numberOfLines: number) => void;
@@ -69,6 +78,8 @@ type ComposerProps = {
onFocus?: (event: NativeSyntheticEvent) => void;
+ onBlur?: (event: NativeSyntheticEvent) => void;
+
/** Should make the input only scroll inside the element avoid scroll out to parent */
shouldContainScroll?: boolean;
};
diff --git a/src/components/ConfirmedRoute.js b/src/components/ConfirmedRoute.tsx
similarity index 61%
rename from src/components/ConfirmedRoute.js
rename to src/components/ConfirmedRoute.tsx
index 466666dd9ef6..05d6557a72e3 100644
--- a/src/components/ConfirmedRoute.js
+++ b/src/components/ConfirmedRoute.tsx
@@ -1,9 +1,7 @@
-import lodashGet from 'lodash/get';
-import lodashIsNil from 'lodash/isNil';
-import PropTypes from 'prop-types';
import React, {useCallback, useEffect} from 'react';
+import type {ReactNode} from 'react';
import {withOnyx} from 'react-native-onyx';
-import _ from 'underscore';
+import type {OnyxEntry} from 'react-native-onyx/lib/types';
import useNetwork from '@hooks/useNetwork';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
@@ -11,54 +9,51 @@ import * as TransactionUtils from '@libs/TransactionUtils';
import * as MapboxToken from '@userActions/MapboxToken';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
+import type {MapboxAccessToken, Transaction} from '@src/types/onyx';
+import type {WaypointCollection} from '@src/types/onyx/Transaction';
+import type IconAsset from '@src/types/utils/IconAsset';
import DistanceMapView from './DistanceMapView';
import * as Expensicons from './Icon/Expensicons';
import ImageSVG from './ImageSVG';
import PendingMapView from './MapView/PendingMapView';
-import transactionPropTypes from './transactionPropTypes';
-const propTypes = {
- /** Transaction that stores the distance request data */
- transaction: transactionPropTypes,
+type WayPoint = {
+ id: string;
+ coordinate: [number, number];
+ markerComponent: () => ReactNode;
+};
+type ConfirmedRoutePropsOnyxProps = {
/** Data about Mapbox token for calling Mapbox API */
- mapboxAccessToken: PropTypes.shape({
- /** Temporary token for Mapbox API */
- token: PropTypes.string,
-
- /** Time when the token will expire in ISO 8601 */
- expiration: PropTypes.string,
- }),
+ mapboxAccessToken: OnyxEntry;
};
-const defaultProps = {
- transaction: {},
- mapboxAccessToken: {
- token: '',
- },
+type ConfirmedRouteProps = ConfirmedRoutePropsOnyxProps & {
+ /** Transaction that stores the distance request data */
+ transaction: Transaction;
};
-function ConfirmedRoute({mapboxAccessToken, transaction}) {
+function ConfirmedRoute({mapboxAccessToken, transaction}: ConfirmedRouteProps) {
const {isOffline} = useNetwork();
- const {route0: route} = transaction.routes || {};
- const waypoints = lodashGet(transaction, 'comment.waypoints', {});
- const coordinates = lodashGet(route, 'geometry.coordinates', []);
+ const {route0: route} = transaction.routes ?? {};
+ const waypoints = transaction.comment?.waypoints ?? {};
+ const coordinates = route.geometry?.coordinates ?? [];
const theme = useTheme();
const styles = useThemeStyles();
const getWaypointMarkers = useCallback(
- (waypointsData) => {
- const numberOfWaypoints = _.size(waypointsData);
+ (waypointsData: WaypointCollection): WayPoint[] => {
+ const numberOfWaypoints = Object.keys(waypointsData).length;
const lastWaypointIndex = numberOfWaypoints - 1;
- return _.filter(
- _.map(waypointsData, (waypoint, key) => {
- if (!waypoint || lodashIsNil(waypoint.lat) || lodashIsNil(waypoint.lng)) {
+ return Object.entries(waypointsData)
+ .map(([key, waypoint]) => {
+ if (!waypoint?.lat || !waypoint?.lng) {
return;
}
const index = TransactionUtils.getWaypointIndex(key);
- let MarkerComponent;
+ let MarkerComponent: IconAsset;
if (index === 0) {
MarkerComponent = Expensicons.DotIndicatorUnfilled;
} else if (index === lastWaypointIndex) {
@@ -69,8 +64,8 @@ function ConfirmedRoute({mapboxAccessToken, transaction}) {
return {
id: `${waypoint.lng},${waypoint.lat},${index}`,
- coordinate: [waypoint.lng, waypoint.lat],
- markerComponent: () => (
+ coordinate: [waypoint.lng, waypoint.lat] as const,
+ markerComponent: (): ReactNode => (
),
};
- }),
- (waypoint) => waypoint,
- );
+ })
+ .filter((waypoint): waypoint is WayPoint => !!waypoint);
},
[theme],
);
@@ -95,16 +89,16 @@ function ConfirmedRoute({mapboxAccessToken, transaction}) {
return (
<>
- {!isOffline && Boolean(mapboxAccessToken.token) ? (
+ {!isOffline && Boolean(mapboxAccessToken?.token) ? (
}
style={[styles.mapView, styles.br4]}
waypoints={waypointMarkers}
styleURL={CONST.MAPBOX.STYLE_URL}
@@ -116,12 +110,10 @@ function ConfirmedRoute({mapboxAccessToken, transaction}) {
);
}
-export default withOnyx({
+export default withOnyx({
mapboxAccessToken: {
key: ONYXKEYS.MAPBOX_ACCESS_TOKEN,
},
})(ConfirmedRoute);
ConfirmedRoute.displayName = 'ConfirmedRoute';
-ConfirmedRoute.propTypes = propTypes;
-ConfirmedRoute.defaultProps = defaultProps;
diff --git a/src/components/ContextMenuItem.js b/src/components/ContextMenuItem.tsx
similarity index 67%
rename from src/components/ContextMenuItem.js
rename to src/components/ContextMenuItem.tsx
index e7d2bda3a667..781d2f718bcf 100644
--- a/src/components/ContextMenuItem.js
+++ b/src/components/ContextMenuItem.tsx
@@ -1,58 +1,52 @@
-import PropTypes from 'prop-types';
+import type {ForwardedRef} from 'react';
import React, {forwardRef, useImperativeHandle} from 'react';
import useStyleUtils from '@hooks/useStyleUtils';
import useThemeStyles from '@hooks/useThemeStyles';
import useThrottledButtonState from '@hooks/useThrottledButtonState';
import useWindowDimensions from '@hooks/useWindowDimensions';
import getButtonState from '@libs/getButtonState';
+import type IconAsset from '@src/types/utils/IconAsset';
import BaseMiniContextMenuItem from './BaseMiniContextMenuItem';
import Icon from './Icon';
-import sourcePropTypes from './Image/sourcePropTypes';
import MenuItem from './MenuItem';
-const propTypes = {
+type ContextMenuItemProps = {
/** Icon Component */
- icon: sourcePropTypes.isRequired,
+ icon: IconAsset;
/** Text to display */
- text: PropTypes.string.isRequired,
+ text: string;
/** Icon to show when interaction was successful */
- successIcon: sourcePropTypes,
+ successIcon?: IconAsset;
/** Text to show when interaction was successful */
- successText: PropTypes.string,
+ successText?: string;
/** Whether to show the mini menu */
- isMini: PropTypes.bool,
+ isMini?: boolean;
/** Callback to fire when the item is pressed */
- onPress: PropTypes.func.isRequired,
+ onPress: () => void;
/** A description text to show under the title */
- description: PropTypes.string,
+ description?: string;
/** The action accept for anonymous user or not */
- isAnonymousAction: PropTypes.bool,
+ isAnonymousAction?: boolean;
/** Whether the menu item is focused or not */
- isFocused: PropTypes.bool,
-
- /** Forwarded ref to ContextMenuItem */
- innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
+ isFocused?: boolean;
};
-const defaultProps = {
- isMini: false,
- successIcon: null,
- successText: '',
- description: '',
- isAnonymousAction: false,
- isFocused: false,
- innerRef: null,
+type ContextMenuItemHandle = {
+ triggerPressAndUpdateSuccess?: () => void;
};
-function ContextMenuItem({onPress, successIcon, successText, icon, text, isMini, description, isAnonymousAction, isFocused, innerRef}) {
+function ContextMenuItem(
+ {onPress, successIcon, successText = '', icon, text, isMini = false, description = '', isAnonymousAction = false, isFocused = false}: ContextMenuItemProps,
+ ref: ForwardedRef,
+) {
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const {windowWidth} = useWindowDimensions();
@@ -66,12 +60,12 @@ function ContextMenuItem({onPress, successIcon, successText, icon, text, isMini,
// We only set the success state when we have icon or text to represent the success state
// We may want to replace this check by checking the Result from OnPress Callback in future.
- if (successIcon || successText) {
+ if (!!successIcon || successText) {
setThrottledButtonInactive();
}
};
- useImperativeHandle(innerRef, () => ({triggerPressAndUpdateSuccess}));
+ useImperativeHandle(ref, () => ({triggerPressAndUpdateSuccess}));
const itemIcon = !isThrottledButtonActive && successIcon ? successIcon : icon;
const itemText = !isThrottledButtonActive && successText ? successText : text;
@@ -107,18 +101,6 @@ function ContextMenuItem({onPress, successIcon, successText, icon, text, isMini,
);
}
-ContextMenuItem.propTypes = propTypes;
-ContextMenuItem.defaultProps = defaultProps;
ContextMenuItem.displayName = 'ContextMenuItem';
-const ContextMenuItemWithRef = forwardRef((props, ref) => (
-
-));
-
-ContextMenuItemWithRef.displayName = 'ContextMenuItemWithRef';
-
-export default ContextMenuItemWithRef;
+export default forwardRef(ContextMenuItem);
diff --git a/src/components/DatePicker/CalendarPicker/index.js b/src/components/DatePicker/CalendarPicker/index.js
index 571ddc820d43..f10af5e4a5a7 100644
--- a/src/components/DatePicker/CalendarPicker/index.js
+++ b/src/components/DatePicker/CalendarPicker/index.js
@@ -112,14 +112,44 @@ class CalendarPicker extends React.PureComponent {
* Handles the user pressing the previous month arrow of the calendar picker.
*/
moveToPrevMonth() {
- this.setState((prev) => ({currentDateView: subMonths(new Date(prev.currentDateView), 1)}));
+ this.setState((prev) => {
+ const prevMonth = subMonths(new Date(prev.currentDateView), 1);
+ // if year is subtracted, we need to update the years list
+ let newYears = prev.years;
+ if (prevMonth.getFullYear() < prev.currentDateView.getFullYear()) {
+ newYears = _.map(prev.years, (item) => ({
+ ...item,
+ isSelected: item.value === prevMonth.getFullYear(),
+ }));
+ }
+
+ return {
+ currentDateView: prevMonth,
+ years: newYears,
+ };
+ });
}
/**
* Handles the user pressing the next month arrow of the calendar picker.
*/
moveToNextMonth() {
- this.setState((prev) => ({currentDateView: addMonths(new Date(prev.currentDateView), 1)}));
+ this.setState((prev) => {
+ const nextMonth = addMonths(new Date(prev.currentDateView), 1);
+ // if year is added, we need to update the years list
+ let newYears = prev.years;
+ if (nextMonth.getFullYear() > prev.currentDateView.getFullYear()) {
+ newYears = _.map(prev.years, (item) => ({
+ ...item,
+ isSelected: item.value === nextMonth.getFullYear(),
+ }));
+ }
+
+ return {
+ currentDateView: nextMonth,
+ years: newYears,
+ };
+ });
}
render() {
diff --git a/src/components/DeeplinkWrapper/DeeplinkRedirectLoadingIndicator.tsx b/src/components/DeeplinkWrapper/DeeplinkRedirectLoadingIndicator.tsx
index 27d8027bbcff..ed91b51a2a44 100644
--- a/src/components/DeeplinkWrapper/DeeplinkRedirectLoadingIndicator.tsx
+++ b/src/components/DeeplinkWrapper/DeeplinkRedirectLoadingIndicator.tsx
@@ -37,7 +37,6 @@ function DeeplinkRedirectLoadingIndicator({openLinkInBrowser, session}: Deeplink
diff --git a/src/components/EReceiptThumbnail.js b/src/components/EReceiptThumbnail.tsx
similarity index 74%
rename from src/components/EReceiptThumbnail.js
rename to src/components/EReceiptThumbnail.tsx
index 7c782a0aa327..5976200975cd 100644
--- a/src/components/EReceiptThumbnail.js
+++ b/src/components/EReceiptThumbnail.tsx
@@ -1,6 +1,7 @@
-import PropTypes from 'prop-types';
import React, {useMemo, useState} from 'react';
+import type {LayoutChangeEvent} from 'react-native';
import {View} from 'react-native';
+import type {OnyxEntry} from 'react-native-onyx';
import {withOnyx} from 'react-native-onyx';
import useStyleUtils from '@hooks/useStyleUtils';
import useThemeStyles from '@hooks/useThemeStyles';
@@ -8,24 +9,21 @@ import * as ReportUtils from '@libs/ReportUtils';
import variables from '@styles/variables';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
+import type {Transaction} from '@src/types/onyx';
import Icon from './Icon';
import * as eReceiptBGs from './Icon/EReceiptBGs';
import * as Expensicons from './Icon/Expensicons';
import * as MCCIcons from './Icon/MCCIcons';
import Image from './Image';
-import transactionPropTypes from './transactionPropTypes';
-const propTypes = {
- /* TransactionID of the transaction this EReceipt corresponds to */
- // eslint-disable-next-line react/no-unused-prop-types
- transactionID: PropTypes.string.isRequired,
-
- /* Onyx Props */
- transaction: transactionPropTypes,
+type EReceiptThumbnailOnyxProps = {
+ transaction: OnyxEntry;
};
-const defaultProps = {
- transaction: {},
+type EReceiptThumbnailProps = EReceiptThumbnailOnyxProps & {
+ /** TransactionID of the transaction this EReceipt corresponds to. It's used by withOnyx HOC */
+ // eslint-disable-next-line react/no-unused-prop-types
+ transactionID: string;
};
const backgroundImages = {
@@ -37,30 +35,35 @@ const backgroundImages = {
[CONST.ERECEIPT_COLORS.PINK]: eReceiptBGs.EReceiptBG_Pink,
};
-function EReceiptThumbnail({transaction}) {
+function EReceiptThumbnail({transaction}: EReceiptThumbnailProps) {
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
- // Get receipt colorway, or default to Yellow.
- const {backgroundColor: primaryColor, color: secondaryColor} = StyleUtils.getEReceiptColorStyles(StyleUtils.getEReceiptColorCode(transaction));
const [containerWidth, setContainerWidth] = useState(0);
const [containerHeight, setContainerHeight] = useState(0);
- const onContainerLayout = (event) => {
+ const backgroundImage = useMemo(() => backgroundImages[StyleUtils.getEReceiptColorCode(transaction)], [StyleUtils, transaction]);
+
+ const colorStyles = StyleUtils.getEReceiptColorStyles(StyleUtils.getEReceiptColorCode(transaction));
+ const primaryColor = colorStyles?.backgroundColor;
+ const secondaryColor = colorStyles?.color;
+
+ const onContainerLayout = (event: LayoutChangeEvent) => {
const {width, height} = event.nativeEvent.layout;
setContainerWidth(width);
setContainerHeight(height);
};
- const {mccGroup: transactionMCCGroup} = ReportUtils.getTransactionDetails(transaction);
- const MCCIcon = MCCIcons[`${transactionMCCGroup}`];
+ const transactionDetails = ReportUtils.getTransactionDetails(transaction);
+ const transactionMCCGroup = transactionDetails?.mccGroup;
+ const MCCIcon = transactionMCCGroup ? MCCIcons[`${transactionMCCGroup}`] : undefined;
const isSmall = containerWidth && containerWidth < variables.eReceiptThumbnailSmallBreakpoint;
const isMedium = containerWidth && containerWidth < variables.eReceiptThumbnailMediumBreakpoint;
- let receiptIconWidth = variables.eReceiptIconWidth;
- let receiptIconHeight = variables.eReceiptIconHeight;
- let receiptMCCSize = variables.eReceiptMCCHeightWidth;
+ let receiptIconWidth: number = variables.eReceiptIconWidth;
+ let receiptIconHeight: number = variables.eReceiptIconHeight;
+ let receiptMCCSize: number = variables.eReceiptMCCHeightWidth;
if (isSmall) {
receiptIconWidth = variables.eReceiptIconWidthSmall;
@@ -72,13 +75,11 @@ function EReceiptThumbnail({transaction}) {
receiptMCCSize = variables.eReceiptMCCHeightWidthMedium;
}
- const backgroundImage = useMemo(() => backgroundImages[StyleUtils.getEReceiptColorCode(transaction)], [StyleUtils, transaction]);
-
return (
({
transaction: {
key: ({transactionID}) => `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
},
diff --git a/src/components/EmojiPicker/EmojiPickerMenu/index.js b/src/components/EmojiPicker/EmojiPickerMenu/index.js
index 0791e5113a1d..a723eed446a4 100755
--- a/src/components/EmojiPicker/EmojiPickerMenu/index.js
+++ b/src/components/EmojiPicker/EmojiPickerMenu/index.js
@@ -36,7 +36,7 @@ const throttleTime = Browser.isMobile() ? 200 : 50;
function EmojiPickerMenu({forwardedRef, onEmojiSelected}) {
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
- const {isSmallScreenWidth} = useWindowDimensions();
+ const {isSmallScreenWidth, windowWidth} = useWindowDimensions();
const {translate} = useLocalize();
const {singleExecution} = useSingleExecution();
const {
@@ -335,7 +335,7 @@ function EmojiPickerMenu({forwardedRef, onEmojiSelected}) {
if (item.header) {
return (
-
+
{translate(`emojiPicker.headers.${code}`)}
);
@@ -368,18 +368,7 @@ function EmojiPickerMenu({forwardedRef, onEmojiSelected}) {
/>
);
},
- [
- preferredSkinTone,
- highlightedIndex,
- isUsingKeyboardMovement,
- highlightFirstEmoji,
- singleExecution,
- styles.emojiHeaderContainer,
- styles.mh4,
- styles.textLabelSupporting,
- translate,
- onEmojiSelected,
- ],
+ [preferredSkinTone, highlightedIndex, isUsingKeyboardMovement, highlightFirstEmoji, singleExecution, translate, onEmojiSelected, isSmallScreenWidth, windowWidth, styles],
);
return (
diff --git a/src/components/FlatList/MVCPFlatList.js b/src/components/FlatList/MVCPFlatList.js
new file mode 100644
index 000000000000..0abb1dc4a873
--- /dev/null
+++ b/src/components/FlatList/MVCPFlatList.js
@@ -0,0 +1,207 @@
+/* eslint-disable es/no-optional-chaining, es/no-nullish-coalescing-operators, react/prop-types */
+import PropTypes from 'prop-types';
+import React from 'react';
+import {FlatList} from 'react-native';
+
+function mergeRefs(...args) {
+ return function forwardRef(node) {
+ args.forEach((ref) => {
+ if (ref == null) {
+ return;
+ }
+ if (typeof ref === 'function') {
+ ref(node);
+ return;
+ }
+ if (typeof ref === 'object') {
+ // eslint-disable-next-line no-param-reassign
+ ref.current = node;
+ return;
+ }
+ console.error(`mergeRefs cannot handle Refs of type boolean, number or string, received ref ${String(ref)}`);
+ });
+ };
+}
+
+function useMergeRefs(...args) {
+ return React.useMemo(
+ () => mergeRefs(...args),
+ // eslint-disable-next-line
+ [...args],
+ );
+}
+
+const MVCPFlatList = React.forwardRef(({maintainVisibleContentPosition, horizontal, onScroll, ...props}, forwardedRef) => {
+ const {minIndexForVisible: mvcpMinIndexForVisible, autoscrollToTopThreshold: mvcpAutoscrollToTopThreshold} = maintainVisibleContentPosition ?? {};
+ const scrollRef = React.useRef(null);
+ const prevFirstVisibleOffsetRef = React.useRef(null);
+ const firstVisibleViewRef = React.useRef(null);
+ const mutationObserverRef = React.useRef(null);
+ const lastScrollOffsetRef = React.useRef(0);
+
+ const getScrollOffset = React.useCallback(() => {
+ if (scrollRef.current == null) {
+ return 0;
+ }
+ return horizontal ? scrollRef.current.getScrollableNode().scrollLeft : scrollRef.current.getScrollableNode().scrollTop;
+ }, [horizontal]);
+
+ const getContentView = React.useCallback(() => scrollRef.current?.getScrollableNode().childNodes[0], []);
+
+ const scrollToOffset = React.useCallback(
+ (offset, animated) => {
+ const behavior = animated ? 'smooth' : 'instant';
+ scrollRef.current?.getScrollableNode().scroll(horizontal ? {left: offset, behavior} : {top: offset, behavior});
+ },
+ [horizontal],
+ );
+
+ const prepareForMaintainVisibleContentPosition = React.useCallback(() => {
+ if (mvcpMinIndexForVisible == null) {
+ return;
+ }
+
+ const contentView = getContentView();
+ if (contentView == null) {
+ return;
+ }
+
+ const scrollOffset = getScrollOffset();
+
+ const contentViewLength = contentView.childNodes.length;
+ for (let i = mvcpMinIndexForVisible; i < contentViewLength; i++) {
+ const subview = contentView.childNodes[i];
+ const subviewOffset = horizontal ? subview.offsetLeft : subview.offsetTop;
+ if (subviewOffset > scrollOffset || i === contentViewLength - 1) {
+ prevFirstVisibleOffsetRef.current = subviewOffset;
+ firstVisibleViewRef.current = subview;
+ break;
+ }
+ }
+ }, [getContentView, getScrollOffset, mvcpMinIndexForVisible, horizontal]);
+
+ const adjustForMaintainVisibleContentPosition = React.useCallback(() => {
+ if (mvcpMinIndexForVisible == null) {
+ return;
+ }
+
+ const firstVisibleView = firstVisibleViewRef.current;
+ const prevFirstVisibleOffset = prevFirstVisibleOffsetRef.current;
+ if (firstVisibleView == null || prevFirstVisibleOffset == null) {
+ return;
+ }
+
+ const firstVisibleViewOffset = horizontal ? firstVisibleView.offsetLeft : firstVisibleView.offsetTop;
+ const delta = firstVisibleViewOffset - prevFirstVisibleOffset;
+ if (Math.abs(delta) > 0.5) {
+ const scrollOffset = getScrollOffset();
+ prevFirstVisibleOffsetRef.current = firstVisibleViewOffset;
+ scrollToOffset(scrollOffset + delta, false);
+ if (mvcpAutoscrollToTopThreshold != null && scrollOffset <= mvcpAutoscrollToTopThreshold) {
+ scrollToOffset(0, true);
+ }
+ }
+ }, [getScrollOffset, scrollToOffset, mvcpMinIndexForVisible, mvcpAutoscrollToTopThreshold, horizontal]);
+
+ const setupMutationObserver = React.useCallback(() => {
+ const contentView = getContentView();
+ if (contentView == null) {
+ return;
+ }
+
+ mutationObserverRef.current?.disconnect();
+
+ const mutationObserver = new MutationObserver(() => {
+ // This needs to execute after scroll events are dispatched, but
+ // in the same tick to avoid flickering. rAF provides the right timing.
+ requestAnimationFrame(() => {
+ // Chrome adjusts scroll position when elements are added at the top of the
+ // view. We want to have the same behavior as react-native / Safari so we
+ // reset the scroll position to the last value we got from an event.
+ const lastScrollOffset = lastScrollOffsetRef.current;
+ const scrollOffset = getScrollOffset();
+ if (lastScrollOffset !== scrollOffset) {
+ scrollToOffset(lastScrollOffset, false);
+ }
+
+ adjustForMaintainVisibleContentPosition();
+ });
+ });
+ mutationObserver.observe(contentView, {
+ attributes: true,
+ childList: true,
+ subtree: true,
+ });
+
+ mutationObserverRef.current = mutationObserver;
+ }, [adjustForMaintainVisibleContentPosition, getContentView, getScrollOffset, scrollToOffset]);
+
+ React.useEffect(() => {
+ requestAnimationFrame(() => {
+ prepareForMaintainVisibleContentPosition();
+ setupMutationObserver();
+ });
+ }, [prepareForMaintainVisibleContentPosition, setupMutationObserver]);
+
+ const setMergedRef = useMergeRefs(scrollRef, forwardedRef);
+
+ const onRef = React.useCallback(
+ (newRef) => {
+ // Make sure to only call refs and re-attach listeners if the node changed.
+ if (newRef == null || newRef === scrollRef.current) {
+ return;
+ }
+
+ setMergedRef(newRef);
+ prepareForMaintainVisibleContentPosition();
+ setupMutationObserver();
+ },
+ [prepareForMaintainVisibleContentPosition, setMergedRef, setupMutationObserver],
+ );
+
+ React.useEffect(() => {
+ const mutationObserver = mutationObserverRef.current;
+ return () => {
+ mutationObserver?.disconnect();
+ };
+ }, []);
+
+ const onScrollInternal = React.useCallback(
+ (ev) => {
+ lastScrollOffsetRef.current = getScrollOffset();
+
+ prepareForMaintainVisibleContentPosition();
+
+ onScroll?.(ev);
+ },
+ [getScrollOffset, prepareForMaintainVisibleContentPosition, onScroll],
+ );
+
+ return (
+
+ );
+});
+
+MVCPFlatList.displayName = 'MVCPFlatList';
+MVCPFlatList.propTypes = {
+ maintainVisibleContentPosition: PropTypes.shape({
+ minIndexForVisible: PropTypes.number.isRequired,
+ autoscrollToTopThreshold: PropTypes.number,
+ }),
+ horizontal: PropTypes.bool,
+};
+
+MVCPFlatList.defaultProps = {
+ maintainVisibleContentPosition: null,
+ horizontal: false,
+};
+
+export default MVCPFlatList;
diff --git a/src/components/FlatList/index.web.js b/src/components/FlatList/index.web.js
new file mode 100644
index 000000000000..7299776db9bc
--- /dev/null
+++ b/src/components/FlatList/index.web.js
@@ -0,0 +1,3 @@
+import MVCPFlatList from './MVCPFlatList';
+
+export default MVCPFlatList;
diff --git a/src/components/FloatingActionButton.js b/src/components/FloatingActionButton.tsx
similarity index 81%
rename from src/components/FloatingActionButton.js
rename to src/components/FloatingActionButton.tsx
index 59e741001063..5f75bf535319 100644
--- a/src/components/FloatingActionButton.js
+++ b/src/components/FloatingActionButton.tsx
@@ -1,5 +1,6 @@
-import PropTypes from 'prop-types';
-import React, {useEffect, useRef} from 'react';
+import type {ForwardedRef} from 'react';
+import React, {forwardRef, useEffect, useRef} from 'react';
+import type {GestureResponderEvent, Role} from 'react-native';
import {Platform, View} from 'react-native';
import Animated, {createAnimatedPropAdapter, Easing, interpolateColor, processColor, useAnimatedProps, useAnimatedStyle, useSharedValue, withTiming} from 'react-native-reanimated';
import Svg, {Path} from 'react-native-svg';
@@ -16,8 +17,18 @@ AnimatedPath.displayName = 'AnimatedPath';
const AnimatedPressable = Animated.createAnimatedComponent(PressableWithFeedback);
AnimatedPressable.displayName = 'AnimatedPressable';
+type AdapterPropsRecord = {
+ type: number;
+ payload?: number | null;
+};
+
+type AdapterProps = {
+ fill?: string | AdapterPropsRecord;
+ stroke?: string | AdapterPropsRecord;
+};
+
const adapter = createAnimatedPropAdapter(
- (props) => {
+ (props: AdapterProps) => {
// eslint-disable-next-line rulesdir/prefer-underscore-method
if (Object.keys(props).includes('fill')) {
// eslint-disable-next-line no-param-reassign
@@ -31,31 +42,27 @@ const adapter = createAnimatedPropAdapter(
},
['fill', 'stroke'],
);
-adapter.propTypes = {
- fill: PropTypes.string,
- stroke: PropTypes.string,
-};
-const propTypes = {
+type FloatingActionButtonProps = {
/* Callback to fire on request to toggle the FloatingActionButton */
- onPress: PropTypes.func.isRequired,
+ onPress: (event: GestureResponderEvent | KeyboardEvent | undefined) => void;
/* Current state (active or not active) of the component */
- isActive: PropTypes.bool.isRequired,
+ isActive: boolean;
/* An accessibility label for the button */
- accessibilityLabel: PropTypes.string.isRequired,
+ accessibilityLabel: string;
/* An accessibility role for the button */
- role: PropTypes.string.isRequired,
+ role: Role;
};
-const FloatingActionButton = React.forwardRef(({onPress, isActive, accessibilityLabel, role}, ref) => {
+function FloatingActionButton({onPress, isActive, accessibilityLabel, role}: FloatingActionButtonProps, ref: ForwardedRef) {
const {success, buttonDefaultBG, textLight, textDark} = useTheme();
const styles = useThemeStyles();
const borderRadius = styles.floatingActionButton.borderRadius;
const {translate} = useLocalize();
- const fabPressable = useRef(null);
+ const fabPressable = useRef(null);
const sharedValue = useSharedValue(isActive ? 1 : 0);
const buttonRef = ref;
@@ -94,7 +101,8 @@ const FloatingActionButton = React.forwardRef(({onPress, isActive, accessibility
{
fabPressable.current = el;
- if (buttonRef) {
+
+ if (buttonRef && 'current' in buttonRef) {
buttonRef.current = el;
}
}}
@@ -103,7 +111,7 @@ const FloatingActionButton = React.forwardRef(({onPress, isActive, accessibility
pressDimmingValue={1}
onPress={(e) => {
// Drop focus to avoid blue focus ring.
- fabPressable.current.blur();
+ fabPressable.current?.blur();
onPress(e);
}}
onLongPress={() => {}}
@@ -122,9 +130,8 @@ const FloatingActionButton = React.forwardRef(({onPress, isActive, accessibility
);
-});
+}
-FloatingActionButton.propTypes = propTypes;
FloatingActionButton.displayName = 'FloatingActionButton';
-export default FloatingActionButton;
+export default forwardRef(FloatingActionButton);
diff --git a/src/components/Form.js b/src/components/Form.js
deleted file mode 100644
index 7b6f587e7bd1..000000000000
--- a/src/components/Form.js
+++ /dev/null
@@ -1,592 +0,0 @@
-import lodashGet from 'lodash/get';
-import PropTypes from 'prop-types';
-import React, {forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
-import {Keyboard, ScrollView, StyleSheet} from 'react-native';
-import {withOnyx} from 'react-native-onyx';
-import _ from 'underscore';
-import useThemeStyles from '@hooks/useThemeStyles';
-import compose from '@libs/compose';
-import * as ErrorUtils from '@libs/ErrorUtils';
-import FormUtils from '@libs/FormUtils';
-import * as ValidationUtils from '@libs/ValidationUtils';
-import Visibility from '@libs/Visibility';
-import stylePropTypes from '@styles/stylePropTypes';
-import * as FormActions from '@userActions/FormActions';
-import CONST from '@src/CONST';
-import FormAlertWithSubmitButton from './FormAlertWithSubmitButton';
-import FormSubmit from './FormSubmit';
-import networkPropTypes from './networkPropTypes';
-import {withNetwork} from './OnyxProvider';
-import SafeAreaConsumer from './SafeAreaConsumer';
-import ScrollViewWithContext from './ScrollViewWithContext';
-import withLocalize, {withLocalizePropTypes} from './withLocalize';
-
-const propTypes = {
- /** A unique Onyx key identifying the form */
- formID: PropTypes.string.isRequired,
-
- /** Text to be displayed in the submit button */
- submitButtonText: PropTypes.string,
-
- /** Controls the submit button's visibility */
- isSubmitButtonVisible: PropTypes.bool,
-
- /** Callback to validate the form */
- validate: PropTypes.func,
-
- /** Callback to submit the form */
- onSubmit: PropTypes.func.isRequired,
-
- /** Children to render. */
- children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]).isRequired,
-
- /* Onyx Props */
-
- /** Contains the form state that must be accessed outside of the component */
- formState: PropTypes.shape({
- /** Controls the loading state of the form */
- isLoading: PropTypes.bool,
-
- /** Server side errors keyed by microtime */
- errors: PropTypes.objectOf(PropTypes.string),
-
- /** Field-specific server side errors keyed by microtime */
- errorFields: PropTypes.objectOf(PropTypes.objectOf(PropTypes.string)),
- }),
-
- /** Contains draft values for each input in the form */
- // eslint-disable-next-line react/forbid-prop-types
- draftValues: PropTypes.object,
-
- /** Should the button be enabled when offline */
- enabledWhenOffline: PropTypes.bool,
-
- /** Whether the form submit action is dangerous */
- isSubmitActionDangerous: PropTypes.bool,
-
- /** Whether the validate() method should run on input changes */
- shouldValidateOnChange: PropTypes.bool,
-
- /** Whether the validate() method should run on blur */
- shouldValidateOnBlur: PropTypes.bool,
-
- /** Whether ScrollWithContext should be used instead of regular ScrollView.
- * Set to true when there's a nested Picker component in Form.
- */
- scrollContextEnabled: PropTypes.bool,
-
- /** Container styles */
- style: stylePropTypes,
-
- /** Submit button container styles */
- // eslint-disable-next-line react/forbid-prop-types
- submitButtonStyles: PropTypes.arrayOf(PropTypes.object),
-
- /** Custom content to display in the footer after submit button */
- footerContent: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
-
- /** Information about the network */
- network: networkPropTypes.isRequired,
-
- /** Style for the error message for submit button */
- errorMessageStyle: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.object), PropTypes.object]),
-
- ...withLocalizePropTypes,
-};
-
-const defaultProps = {
- isSubmitButtonVisible: true,
- formState: {
- isLoading: false,
- },
- draftValues: {},
- enabledWhenOffline: false,
- isSubmitActionDangerous: false,
- scrollContextEnabled: false,
- shouldValidateOnChange: true,
- shouldValidateOnBlur: true,
- footerContent: null,
- style: [],
- errorMessageStyle: [],
- submitButtonStyles: [],
- validate: () => ({}),
- submitButtonText: '',
-};
-
-const Form = forwardRef((props, forwardedRef) => {
- const styles = useThemeStyles();
- const [errors, setErrors] = useState({});
- const [inputValues, setInputValues] = useState(() => ({...props.draftValues}));
- const formRef = useRef(null);
- const formContentRef = useRef(null);
- const inputRefs = useRef({});
- const touchedInputs = useRef({});
- const focusedInput = useRef(null);
- const isFirstRender = useRef(true);
-
- const {validate, onSubmit, children} = props;
-
- const hasServerError = useMemo(() => Boolean(props.formState) && !_.isEmpty(props.formState.errors), [props.formState]);
-
- /**
- * @param {Object} values - An object containing the value of each inputID, e.g. {inputID1: value1, inputID2: value2}
- * @returns {Object} - An object containing the errors for each inputID, e.g. {inputID1: error1, inputID2: error2}
- */
- const onValidate = useCallback(
- (values, shouldClearServerError = true) => {
- // Trim all string values
- const trimmedStringValues = ValidationUtils.prepareValues(values);
-
- if (shouldClearServerError) {
- FormActions.setErrors(props.formID, null);
- }
- FormActions.setErrorFields(props.formID, null);
-
- // Run any validations passed as a prop
- const validationErrors = validate(trimmedStringValues);
-
- // Validate the input for html tags. It should supercede any other error
- _.each(trimmedStringValues, (inputValue, inputID) => {
- // If the input value is empty OR is non-string, we don't need to validate it for HTML tags
- if (!inputValue || !_.isString(inputValue)) {
- return;
- }
- const foundHtmlTagIndex = inputValue.search(CONST.VALIDATE_FOR_HTML_TAG_REGEX);
- const leadingSpaceIndex = inputValue.search(CONST.VALIDATE_FOR_LEADINGSPACES_HTML_TAG_REGEX);
-
- // Return early if there are no HTML characters
- if (leadingSpaceIndex === -1 && foundHtmlTagIndex === -1) {
- return;
- }
-
- const matchedHtmlTags = inputValue.match(CONST.VALIDATE_FOR_HTML_TAG_REGEX);
- let isMatch = _.some(CONST.WHITELISTED_TAGS, (r) => r.test(inputValue));
- // Check for any matches that the original regex (foundHtmlTagIndex) matched
- if (matchedHtmlTags) {
- // Check if any matched inputs does not match in WHITELISTED_TAGS list and return early if needed.
- for (let i = 0; i < matchedHtmlTags.length; i++) {
- const htmlTag = matchedHtmlTags[i];
- isMatch = _.some(CONST.WHITELISTED_TAGS, (r) => r.test(htmlTag));
- if (!isMatch) {
- break;
- }
- }
- }
-
- if (isMatch && leadingSpaceIndex === -1) {
- return;
- }
-
- // Add a validation error here because it is a string value that contains HTML characters
- validationErrors[inputID] = 'common.error.invalidCharacter';
- });
-
- if (!_.isObject(validationErrors)) {
- throw new Error('Validate callback must return an empty object or an object with shape {inputID: error}');
- }
-
- const touchedInputErrors = _.pick(validationErrors, (inputValue, inputID) => Boolean(touchedInputs.current[inputID]));
-
- if (!_.isEqual(errors, touchedInputErrors)) {
- setErrors(touchedInputErrors);
- }
-
- return touchedInputErrors;
- },
- [props.formID, validate, errors],
- );
-
- useEffect(() => {
- // We want to skip Form validation on initial render.
- // This also avoids a bug where we immediately clear server errors when the loading indicator unmounts and Form remounts with server errors.
- if (isFirstRender.current) {
- isFirstRender.current = false;
- return;
- }
-
- onValidate(inputValues);
-
- // eslint-disable-next-line react-hooks/exhaustive-deps -- we just want to revalidate the form on update if the preferred locale changed on another device so that errors get translated
- }, [props.preferredLocale]);
-
- const errorMessage = useMemo(() => {
- const latestErrorMessage = ErrorUtils.getLatestErrorMessage(props.formState);
- return typeof latestErrorMessage === 'string' ? latestErrorMessage : '';
- }, [props.formState]);
-
- /**
- * @param {String} inputID - The inputID of the input being touched
- */
- const setTouchedInput = useCallback(
- (inputID) => {
- touchedInputs.current[inputID] = true;
- },
- [touchedInputs],
- );
-
- const submit = useCallback(() => {
- // Return early if the form is already submitting to avoid duplicate submission
- if (props.formState.isLoading) {
- return;
- }
-
- // Trim all string values
- const trimmedStringValues = ValidationUtils.prepareValues(inputValues);
-
- // Touches all form inputs so we can validate the entire form
- _.each(inputRefs.current, (inputRef, inputID) => (touchedInputs.current[inputID] = true));
-
- // Validate form and return early if any errors are found
- if (!_.isEmpty(onValidate(trimmedStringValues))) {
- return;
- }
-
- // Do not submit form if network is offline and the form is not enabled when offline
- if (props.network.isOffline && !props.enabledWhenOffline) {
- return;
- }
-
- // Call submit handler
- onSubmit(trimmedStringValues);
- }, [props.formState.isLoading, props.network.isOffline, props.enabledWhenOffline, inputValues, onValidate, onSubmit]);
-
- /**
- * Resets the form
- */
- const resetForm = useCallback(
- (optionalValue) => {
- _.each(inputValues, (inputRef, inputID) => {
- setInputValues((prevState) => {
- const copyPrevState = _.clone(prevState);
-
- touchedInputs.current[inputID] = false;
- copyPrevState[inputID] = optionalValue[inputID] || '';
-
- return copyPrevState;
- });
- });
- setErrors({});
- },
- [inputValues],
- );
-
- useImperativeHandle(forwardedRef, () => ({
- resetForm,
- }));
-
- /**
- * Loops over Form's children and automatically supplies Form props to them
- *
- * @param {Array | Function | Node} children - An array containing all Form children
- * @returns {React.Component}
- */
- const childrenWrapperWithProps = useCallback(
- (childNodes) => {
- const childrenElements = React.Children.map(childNodes, (child) => {
- // Just render the child if it is not a valid React element, e.g. text within a component
- if (!React.isValidElement(child)) {
- return child;
- }
-
- // Depth first traversal of the render tree as the input element is likely to be the last node
- if (child.props.children) {
- return React.cloneElement(child, {
- children: childrenWrapperWithProps(child.props.children),
- });
- }
-
- // Look for any inputs nested in a custom component, e.g AddressForm or IdentityForm
- if (_.isFunction(child.type)) {
- const childNode = new child.type(child.props);
-
- // If the custom component has a render method, use it to get the nested children
- const nestedChildren = _.isFunction(childNode.render) ? childNode.render() : childNode;
-
- // Render the custom component if it's a valid React element
- // If the custom component has nested children, Loop over them and supply From props
- if (React.isValidElement(nestedChildren) || lodashGet(nestedChildren, 'props.children')) {
- return childrenWrapperWithProps(nestedChildren);
- }
-
- // Just render the child if it's custom component not a valid React element, or if it hasn't children
- return child;
- }
-
- // We check if the child has the inputID prop.
- // We don't want to pass form props to non form components, e.g. View, Text, etc
- if (!child.props.inputID) {
- return child;
- }
-
- // We clone the child passing down all form props
- const inputID = child.props.inputID;
- let defaultValue;
-
- // We need to make sure that checkboxes have correct
- // value assigned from the list of draft values
- // https://github.com/Expensify/App/issues/16885#issuecomment-1520846065
- if (_.isBoolean(props.draftValues[inputID])) {
- defaultValue = props.draftValues[inputID];
- } else {
- defaultValue = props.draftValues[inputID] || child.props.defaultValue;
- }
-
- // We want to initialize the input value if it's undefined
- if (_.isUndefined(inputValues[inputID])) {
- // eslint-disable-next-line es/no-nullish-coalescing-operators
- inputValues[inputID] = defaultValue ?? '';
- }
-
- // We force the form to set the input value from the defaultValue props if there is a saved valid value
- if (child.props.shouldUseDefaultValue) {
- inputValues[inputID] = child.props.defaultValue;
- }
-
- if (!_.isUndefined(child.props.value)) {
- inputValues[inputID] = child.props.value;
- }
-
- const errorFields = lodashGet(props.formState, 'errorFields', {});
- const fieldErrorMessage =
- _.chain(errorFields[inputID])
- .keys()
- .sortBy()
- .reverse()
- .map((key) => errorFields[inputID][key])
- .first()
- .value() || '';
-
- return React.cloneElement(child, {
- ref: (node) => {
- inputRefs.current[inputID] = node;
-
- const {ref} = child;
- if (_.isFunction(ref)) {
- ref(node);
- }
- },
- value: inputValues[inputID],
- // As the text input is controlled, we never set the defaultValue prop
- // as this is already happening by the value prop.
- defaultValue: undefined,
- errorText: errors[inputID] || fieldErrorMessage,
- onFocus: (event) => {
- focusedInput.current = inputID;
- if (_.isFunction(child.props.onFocus)) {
- child.props.onFocus(event);
- }
- },
- onBlur: (event) => {
- // Only run validation when user proactively blurs the input.
- if (Visibility.isVisible() && Visibility.hasFocus()) {
- const relatedTargetId = lodashGet(event, 'nativeEvent.relatedTarget.id');
- // We delay the validation in order to prevent Checkbox loss of focus when
- // the user are focusing a TextInput and proceeds to toggle a CheckBox in
- // web and mobile web platforms.
-
- setTimeout(() => {
- if (
- relatedTargetId &&
- _.includes([CONST.OVERLAY.BOTTOM_BUTTON_NATIVE_ID, CONST.OVERLAY.TOP_BUTTON_NATIVE_ID, CONST.BACK_BUTTON_NATIVE_ID], relatedTargetId)
- ) {
- return;
- }
- setTouchedInput(inputID);
- if (props.shouldValidateOnBlur) {
- onValidate(inputValues, !hasServerError);
- }
- }, 200);
- }
-
- if (_.isFunction(child.props.onBlur)) {
- child.props.onBlur(event);
- }
- },
- onTouched: () => {
- setTouchedInput(inputID);
- },
- onInputChange: (value, key) => {
- const inputKey = key || inputID;
-
- if (focusedInput.current && focusedInput.current !== inputKey) {
- setTouchedInput(focusedInput.current);
- }
-
- setInputValues((prevState) => {
- const newState = {
- ...prevState,
- [inputKey]: value,
- };
-
- if (props.shouldValidateOnChange) {
- onValidate(newState);
- }
- return newState;
- });
-
- if (child.props.shouldSaveDraft) {
- FormActions.setDraftValues(props.formID, {[inputKey]: value});
- }
-
- if (child.props.onValueChange) {
- child.props.onValueChange(value, inputKey);
- }
- },
- });
- });
-
- return childrenElements;
- },
- [
- errors,
- inputRefs,
- inputValues,
- onValidate,
- props.draftValues,
- props.formID,
- props.formState,
- setTouchedInput,
- props.shouldValidateOnBlur,
- props.shouldValidateOnChange,
- hasServerError,
- ],
- );
-
- const scrollViewContent = useCallback(
- (safeAreaPaddingBottomStyle) => (
-
- {childrenWrapperWithProps(_.isFunction(children) ? children({inputValues}) : children)}
- {props.isSubmitButtonVisible && (
- 0 || Boolean(errorMessage) || !_.isEmpty(props.formState.errorFields)}
- isLoading={props.formState.isLoading}
- message={_.isEmpty(props.formState.errorFields) ? errorMessage : null}
- onSubmit={submit}
- footerContent={props.footerContent}
- onFixTheErrorsLinkPressed={() => {
- const errorFields = !_.isEmpty(errors) ? errors : props.formState.errorFields;
- const focusKey = _.find(_.keys(inputRefs.current), (key) => _.keys(errorFields).includes(key));
- const focusInput = inputRefs.current[focusKey];
-
- // Dismiss the keyboard for non-text fields by checking if the component has the isFocused method, as only TextInput has this method.
- if (typeof focusInput.isFocused !== 'function') {
- Keyboard.dismiss();
- }
-
- // We subtract 10 to scroll slightly above the input
- if (focusInput.measureLayout && typeof focusInput.measureLayout === 'function') {
- // We measure relative to the content root, not the scroll view, as that gives
- // consistent results across mobile and web
- focusInput.measureLayout(formContentRef.current, (x, y) => formRef.current.scrollTo({y: y - 10, animated: false}));
- }
-
- // Focus the input after scrolling, as on the Web it gives a slightly better visual result
- if (focusInput.focus && typeof focusInput.focus === 'function') {
- focusInput.focus();
- }
- }}
- containerStyles={[styles.mh0, styles.mt5, styles.flex1, ...props.submitButtonStyles]}
- enabledWhenOffline={props.enabledWhenOffline}
- isSubmitActionDangerous={props.isSubmitActionDangerous}
- useSmallerSubmitButtonSize={props.useSmallerSubmitButtonSize}
- disablePressOnEnter
- errorMessageStyle={props.errorMessageStyle}
- />
- )}
-
- ),
-
- [
- props.style,
- props.isSubmitButtonVisible,
- props.submitButtonText,
- props.useSmallerSubmitButtonSize,
- props.errorMessageStyle,
- props.formState.errorFields,
- props.formState.isLoading,
- props.footerContent,
- props.submitButtonStyles,
- props.enabledWhenOffline,
- props.isSubmitActionDangerous,
- submit,
- childrenWrapperWithProps,
- children,
- inputValues,
- errors,
- errorMessage,
- styles.mh0,
- styles.mt5,
- styles.flex1,
- ],
- );
-
- useEffect(() => {
- _.each(inputRefs.current, (inputRef, inputID) => {
- if (inputRef) {
- return;
- }
-
- delete inputRefs.current[inputID];
- delete touchedInputs.current[inputID];
-
- setInputValues((prevState) => {
- const copyPrevState = _.clone(prevState);
-
- delete copyPrevState[inputID];
-
- return copyPrevState;
- });
- });
- // We need to verify that all references and values are still actual.
- // We should not store it when e.g. some input has been unmounted.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [children]);
-
- return (
-
- {({safeAreaPaddingBottomStyle}) =>
- props.scrollContextEnabled ? (
-
- {scrollViewContent(safeAreaPaddingBottomStyle)}
-
- ) : (
-
- {scrollViewContent(safeAreaPaddingBottomStyle)}
-
- )
- }
-
- );
-});
-
-Form.displayName = 'Form';
-Form.propTypes = propTypes;
-Form.defaultProps = defaultProps;
-
-export default compose(
- withLocalize,
- withNetwork(),
- withOnyx({
- formState: {
- key: (props) => props.formID,
- },
- draftValues: {
- key: (props) => FormUtils.getDraftKey(props.formID),
- },
- }),
-)(Form);
diff --git a/src/components/HeaderWithBackButton/index.tsx b/src/components/HeaderWithBackButton/index.tsx
index 209803f2a5d1..6cbfde0645de 100755
--- a/src/components/HeaderWithBackButton/index.tsx
+++ b/src/components/HeaderWithBackButton/index.tsx
@@ -61,7 +61,6 @@ function HeaderWithBackButton({
const StyleUtils = useStyleUtils();
const [isDownloadButtonActive, temporarilyDisableDownloadButton] = useThrottledButtonState();
const {translate} = useLocalize();
- // @ts-expect-error TODO: Remove this once useKeyboardState (https://github.com/Expensify/App/issues/24941) is migrated to TypeScript.
const {isKeyboardShown} = useKeyboardState();
const waitForNavigate = useWaitForNavigation();
diff --git a/src/components/Hoverable/ActiveHoverable.tsx b/src/components/Hoverable/ActiveHoverable.tsx
new file mode 100644
index 000000000000..028fdd30cf35
--- /dev/null
+++ b/src/components/Hoverable/ActiveHoverable.tsx
@@ -0,0 +1,127 @@
+import type {Ref} from 'react';
+import {cloneElement, forwardRef, useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import {DeviceEventEmitter} from 'react-native';
+import mergeRefs from '@libs/mergeRefs';
+import {getReturnValue} from '@libs/ValueUtils';
+import CONST from '@src/CONST';
+import type HoverableProps from './types';
+
+type ActiveHoverableProps = Omit;
+
+function ActiveHoverable({onHoverIn, onHoverOut, shouldHandleScroll, children}: ActiveHoverableProps, outerRef: Ref) {
+ const [isHovered, setIsHovered] = useState(false);
+
+ const elementRef = useRef(null);
+ const isScrollingRef = useRef(false);
+ const isHoveredRef = useRef(false);
+
+ const updateIsHovered = useCallback(
+ (hovered: boolean) => {
+ isHoveredRef.current = hovered;
+ if (shouldHandleScroll && isScrollingRef.current) {
+ return;
+ }
+ setIsHovered(hovered);
+ },
+ [shouldHandleScroll],
+ );
+
+ useEffect(() => {
+ if (isHovered) {
+ onHoverIn?.();
+ } else {
+ onHoverOut?.();
+ }
+ }, [isHovered, onHoverIn, onHoverOut]);
+
+ useEffect(() => {
+ if (!shouldHandleScroll) {
+ return;
+ }
+
+ const scrollingListener = DeviceEventEmitter.addListener(CONST.EVENTS.SCROLLING, (scrolling) => {
+ isScrollingRef.current = scrolling;
+ if (!isScrollingRef.current) {
+ setIsHovered(isHoveredRef.current);
+ }
+ });
+
+ return () => scrollingListener.remove();
+ }, [shouldHandleScroll]);
+
+ useEffect(() => {
+ // Do not mount a listener if the component is not hovered
+ if (!isHovered) {
+ return;
+ }
+
+ /**
+ * Checks the hover state of a component and updates it based on the event target.
+ * This is necessary to handle cases where the hover state might get stuck due to an unreliable mouseleave trigger,
+ * such as when an element is removed before the mouseleave event is triggered.
+ * @param event The hover event object.
+ */
+ const unsetHoveredIfOutside = (event: MouseEvent) => {
+ if (!elementRef.current || elementRef.current.contains(event.target as Node)) {
+ return;
+ }
+
+ setIsHovered(false);
+ };
+
+ document.addEventListener('mouseover', unsetHoveredIfOutside);
+
+ return () => document.removeEventListener('mouseover', unsetHoveredIfOutside);
+ }, [isHovered, elementRef]);
+
+ useEffect(() => {
+ const unsetHoveredWhenDocumentIsHidden = () => document.visibilityState === 'hidden' && setIsHovered(false);
+
+ document.addEventListener('visibilitychange', unsetHoveredWhenDocumentIsHidden);
+
+ return () => document.removeEventListener('visibilitychange', unsetHoveredWhenDocumentIsHidden);
+ }, []);
+
+ const child = useMemo(() => getReturnValue(children, !isScrollingRef.current && isHovered), [children, isHovered]);
+
+ const childOnMouseEnter = child.props.onMouseEnter;
+ const childOnMouseLeave = child.props.onMouseLeave;
+
+ const hoverAndForwardOnMouseEnter = useCallback(
+ (e: MouseEvent) => {
+ updateIsHovered(true);
+ childOnMouseEnter?.(e);
+ },
+ [updateIsHovered, childOnMouseEnter],
+ );
+
+ const unhoverAndForwardOnMouseLeave = useCallback(
+ (e: MouseEvent) => {
+ updateIsHovered(false);
+ childOnMouseLeave?.(e);
+ },
+ [updateIsHovered, childOnMouseLeave],
+ );
+
+ const unhoverAndForwardOnBlur = useCallback(
+ (event: MouseEvent) => {
+ // Check if the blur event occurred due to clicking outside the element
+ // and the wrapperView contains the element that caused the blur and reset isHovered
+ if (!elementRef.current?.contains(event.target as Node) && !elementRef.current?.contains(event.relatedTarget as Node)) {
+ setIsHovered(false);
+ }
+
+ child.props.onBlur?.(event);
+ },
+ [child.props],
+ );
+
+ return cloneElement(child, {
+ ref: mergeRefs(elementRef, outerRef, child.ref),
+ onMouseEnter: hoverAndForwardOnMouseEnter,
+ onMouseLeave: unhoverAndForwardOnMouseLeave,
+ onBlur: unhoverAndForwardOnBlur,
+ });
+}
+
+export default forwardRef(ActiveHoverable);
diff --git a/src/components/Hoverable/index.tsx b/src/components/Hoverable/index.tsx
index c82ba659593a..3729ee380b34 100644
--- a/src/components/Hoverable/index.tsx
+++ b/src/components/Hoverable/index.tsx
@@ -1,213 +1,29 @@
-import type {ForwardedRef, MutableRefObject, ReactElement, RefAttributes} from 'react';
-import React, {forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
-import {DeviceEventEmitter} from 'react-native';
-import * as DeviceCapabilities from '@libs/DeviceCapabilities';
-import CONST from '@src/CONST';
+import type {Ref} from 'react';
+import React, {cloneElement, forwardRef} from 'react';
+import {hasHoverSupport} from '@libs/DeviceCapabilities';
+import {getReturnValue} from '@libs/ValueUtils';
+import ActiveHoverable from './ActiveHoverable';
import type HoverableProps from './types';
-/**
- * Maps the children of a Hoverable component to
- * - a function that is called with the parameter
- * - the child itself if it is the only child
- * @param children The children to map.
- * @param callbackParam The parameter to pass to the children function.
- * @returns The mapped children.
- */
-function mapChildren(children: ((isHovered: boolean) => ReactElement) | ReactElement | ReactElement[], callbackParam: boolean): ReactElement & RefAttributes {
- if (Array.isArray(children)) {
- return children[0];
- }
-
- if (typeof children === 'function') {
- return children(callbackParam);
- }
-
- return children;
-}
-
-/**
- * Assigns a ref to an element, either by setting the current property of the ref object or by calling the ref function
- * @param ref The ref object or function.
- * @param element The element to assign the ref to.
- */
-function assignRef(ref: ((instance: HTMLElement | null) => void) | MutableRefObject, element: HTMLElement) {
- if (!ref) {
- return;
- }
- if (typeof ref === 'function') {
- ref(element);
- } else if ('current' in ref) {
- // eslint-disable-next-line no-param-reassign
- ref.current = element;
- }
-}
-
/**
* It is necessary to create a Hoverable component instead of relying solely on Pressable support for hover state,
* because nesting Pressables causes issues where the hovered state of the child cannot be easily propagated to the
* parent. https://github.com/necolas/react-native-web/issues/1875
*/
-function Hoverable(
- {disabled = false, onHoverIn = () => {}, onHoverOut = () => {}, onMouseEnter = () => {}, onMouseLeave = () => {}, children, shouldHandleScroll = false}: HoverableProps,
- outerRef: ForwardedRef,
-) {
- const [isHovered, setIsHovered] = useState(false);
-
- const isScrolling = useRef(false);
- const isHoveredRef = useRef(false);
- const ref = useRef(null);
-
- const updateIsHoveredOnScrolling = useCallback(
- (hovered: boolean) => {
- if (disabled) {
- return;
- }
-
- isHoveredRef.current = hovered;
-
- if (shouldHandleScroll && isScrolling.current) {
- return;
- }
- setIsHovered(hovered);
- },
- [disabled, shouldHandleScroll],
- );
-
- useEffect(() => {
- const unsetHoveredWhenDocumentIsHidden = () => document.visibilityState === 'hidden' && setIsHovered(false);
-
- document.addEventListener('visibilitychange', unsetHoveredWhenDocumentIsHidden);
-
- return () => document.removeEventListener('visibilitychange', unsetHoveredWhenDocumentIsHidden);
- }, []);
-
- useEffect(() => {
- if (!shouldHandleScroll) {
- return;
- }
-
- const scrollingListener = DeviceEventEmitter.addListener(CONST.EVENTS.SCROLLING, (scrolling) => {
- isScrolling.current = scrolling;
- if (!scrolling) {
- setIsHovered(isHoveredRef.current);
- }
- });
-
- return () => scrollingListener.remove();
- }, [shouldHandleScroll]);
-
- useEffect(() => {
- if (!DeviceCapabilities.hasHoverSupport()) {
- return;
- }
-
- /**
- * Checks the hover state of a component and updates it based on the event target.
- * This is necessary to handle cases where the hover state might get stuck due to an unreliable mouseleave trigger,
- * such as when an element is removed before the mouseleave event is triggered.
- * @param event The hover event object.
- */
- const unsetHoveredIfOutside = (event: MouseEvent) => {
- if (!ref.current || !isHovered) {
- return;
- }
-
- if (ref.current.contains(event.target as Node)) {
- return;
- }
-
- setIsHovered(false);
- };
-
- document.addEventListener('mouseover', unsetHoveredIfOutside);
-
- return () => document.removeEventListener('mouseover', unsetHoveredIfOutside);
- }, [isHovered]);
-
- useEffect(() => {
- if (!disabled || !isHovered) {
- return;
- }
- setIsHovered(false);
- }, [disabled, isHovered]);
-
- useEffect(() => {
- if (disabled) {
- return;
- }
- if (onHoverIn && isHovered) {
- return onHoverIn();
- }
- if (onHoverOut && !isHovered) {
- return onHoverOut();
- }
- }, [disabled, isHovered, onHoverIn, onHoverOut]);
-
- // Expose inner ref to parent through outerRef. This enable us to use ref both in parent and child.
- useImperativeHandle(outerRef, () => ref.current, []);
-
- const child = useMemo(() => React.Children.only(mapChildren(children as ReactElement, isHovered)), [children, isHovered]);
-
- const enableHoveredOnMouseEnter = useCallback(
- (event: MouseEvent) => {
- updateIsHoveredOnScrolling(true);
- onMouseEnter(event);
-
- if (typeof child.props.onMouseEnter === 'function') {
- child.props.onMouseEnter(event);
- }
- },
- [child.props, onMouseEnter, updateIsHoveredOnScrolling],
- );
-
- const disableHoveredOnMouseLeave = useCallback(
- (event: MouseEvent) => {
- updateIsHoveredOnScrolling(false);
- onMouseLeave(event);
-
- if (typeof child.props.onMouseLeave === 'function') {
- child.props.onMouseLeave(event);
- }
- },
- [child.props, onMouseLeave, updateIsHoveredOnScrolling],
- );
-
- const disableHoveredOnBlur = useCallback(
- (event: MouseEvent) => {
- // Check if the blur event occurred due to clicking outside the element
- // and the wrapperView contains the element that caused the blur and reset isHovered
- if (!ref.current?.contains(event.target as Node) && !ref.current?.contains(event.relatedTarget as Node)) {
- setIsHovered(false);
- }
-
- if (typeof child.props.onBlur === 'function') {
- child.props.onBlur(event);
- }
- },
- [child.props],
- );
-
- // We need to access the ref of a children from both parent and current component
- // So we pass it to current ref and assign it once again to the child ref prop
- const hijackRef = (el: HTMLElement) => {
- ref.current = el;
- if (child.ref) {
- assignRef(child.ref, el);
- }
- };
-
- if (!DeviceCapabilities.hasHoverSupport()) {
- return React.cloneElement(child, {
- ref: hijackRef,
- });
+function Hoverable({isDisabled, ...props}: HoverableProps, ref: Ref) {
+ // If Hoverable is disabled, just render the child without additional logic or event listeners.
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
+ if (isDisabled || !hasHoverSupport()) {
+ return cloneElement(getReturnValue(props.children, false), {ref});
}
- return React.cloneElement(child, {
- ref: hijackRef,
- onMouseEnter: enableHoveredOnMouseEnter,
- onMouseLeave: disableHoveredOnMouseLeave,
- onBlur: disableHoveredOnBlur,
- });
+ return (
+
+ );
}
export default forwardRef(Hoverable);
diff --git a/src/components/Hoverable/types.ts b/src/components/Hoverable/types.ts
index 921772743ab4..6963e3b5178c 100644
--- a/src/components/Hoverable/types.ts
+++ b/src/components/Hoverable/types.ts
@@ -1,11 +1,14 @@
-import type {ReactNode} from 'react';
+import type {ReactElement, RefAttributes} from 'react';
+
+type HoverableChild = ReactElement & RefAttributes;
+type HoverableChildren = ((isHovered: boolean) => HoverableChild) | HoverableChild;
type HoverableProps = {
/** Children to wrap with Hoverable. */
- children: ((isHovered: boolean) => ReactNode) | ReactNode;
+ children: HoverableChildren;
/** Whether to disable the hover action */
- disabled?: boolean;
+ isDisabled?: boolean;
/** Function that executes when the mouse moves over the children. */
onHoverIn?: () => void;
@@ -13,14 +16,10 @@ type HoverableProps = {
/** Function that executes when the mouse leaves the children. */
onHoverOut?: () => void;
- /** Direct pass-through of React's onMouseEnter event. */
- onMouseEnter?: (event: MouseEvent) => void;
-
- /** Direct pass-through of React's onMouseLeave event. */
- onMouseLeave?: (event: MouseEvent) => void;
-
/** Decides whether to handle the scroll behaviour to show hover once the scroll ends */
shouldHandleScroll?: boolean;
};
export default HoverableProps;
+
+export type {HoverableChild};
diff --git a/src/components/InvertedFlatList/BaseInvertedFlatList.tsx b/src/components/InvertedFlatList/BaseInvertedFlatList.tsx
index 9e3991828625..e28400505280 100644
--- a/src/components/InvertedFlatList/BaseInvertedFlatList.tsx
+++ b/src/components/InvertedFlatList/BaseInvertedFlatList.tsx
@@ -3,8 +3,8 @@ import React, {forwardRef} from 'react';
import type {FlatListProps} from 'react-native';
import FlatList from '@components/FlatList';
-const AUTOSCROLL_TO_TOP_THRESHOLD = 128;
const WINDOW_SIZE = 15;
+const AUTOSCROLL_TO_TOP_THRESHOLD = 128;
function BaseInvertedFlatList(props: FlatListProps, ref: ForwardedRef) {
return (
diff --git a/src/components/InvertedFlatList/index.tsx b/src/components/InvertedFlatList/index.tsx
index a96058a3046f..2b4d98733cc4 100644
--- a/src/components/InvertedFlatList/index.tsx
+++ b/src/components/InvertedFlatList/index.tsx
@@ -4,6 +4,7 @@ import type {FlatList, FlatListProps, NativeScrollEvent, NativeSyntheticEvent} f
import {DeviceEventEmitter} from 'react-native';
import CONST from '@src/CONST';
import BaseInvertedFlatList from './BaseInvertedFlatList';
+import CellRendererComponent from './CellRendererComponent';
// This is adapted from https://codesandbox.io/s/react-native-dsyse
// It's a HACK alert since FlatList has inverted scrolling on web
@@ -87,6 +88,7 @@ function InvertedFlatList({onScroll: onScrollProp = () => {}, ...props}: Flat
{...props}
ref={ref}
onScroll={handleScroll}
+ CellRendererComponent={CellRendererComponent}
/>
);
}
diff --git a/src/components/MapView/MapView.tsx b/src/components/MapView/MapView.tsx
index 6321b461f21e..a3178f642852 100644
--- a/src/components/MapView/MapView.tsx
+++ b/src/components/MapView/MapView.tsx
@@ -105,7 +105,7 @@ const MapView = forwardRef(
if (waypoints.length === 1) {
cameraRef.current?.setCamera({
- zoomLevel: 15,
+ zoomLevel: CONST.MAPBOX.SINGLE_MARKER_ZOOM,
animationDuration: 1500,
centerCoordinate: waypoints[0].coordinate,
});
diff --git a/src/components/MapView/MapView.website.tsx b/src/components/MapView/MapView.website.tsx
index 05d86e8ec999..289f7d0d62a8 100644
--- a/src/components/MapView/MapView.website.tsx
+++ b/src/components/MapView/MapView.website.tsx
@@ -117,7 +117,7 @@ const MapView = forwardRef(
if (waypoints.length === 1) {
mapRef.flyTo({
center: waypoints[0].coordinate,
- zoom: CONST.MAPBOX.DEFAULT_ZOOM,
+ zoom: CONST.MAPBOX.SINGLE_MARKER_ZOOM,
});
return;
}
diff --git a/src/components/MenuItem.tsx b/src/components/MenuItem.tsx
index 86e77ae4bfc3..334fa9895205 100644
--- a/src/components/MenuItem.tsx
+++ b/src/components/MenuItem.tsx
@@ -66,7 +66,7 @@ type MenuItemProps = (IconProps | AvatarProps | NoIcon) & {
badgeText?: string;
/** Used to apply offline styles to child text components */
- style?: ViewStyle;
+ style?: StyleProp;
/** Any additional styles to apply */
wrapperStyle?: StyleProp;
@@ -291,7 +291,7 @@ function MenuItem(
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
- const combinedStyle = StyleUtils.combineStyles(style ?? {}, styles.popoverMenuItem);
+ const combinedStyle = [style, styles.popoverMenuItem];
const {isSmallScreenWidth} = useWindowDimensions();
const [html, setHtml] = useState('');
const titleRef = useRef('');
@@ -523,7 +523,6 @@ function MenuItem(
src={furtherDetailsIcon}
height={variables.iconSizeNormal}
width={variables.iconSizeNormal}
- fill={theme.icon}
inline
/>
)}
diff --git a/src/components/MoneyRequestHeader.js b/src/components/MoneyRequestHeader.js
index 488630dd0590..be42abc797dd 100644
--- a/src/components/MoneyRequestHeader.js
+++ b/src/components/MoneyRequestHeader.js
@@ -100,7 +100,16 @@ function MoneyRequestHeader({session, parentReport, report, parentReportAction,
threeDotsMenuItems.push({
icon: Expensicons.Receipt,
text: translate('receipt.addReceipt'),
- onSelected: () => Navigation.navigate(ROUTES.EDIT_REQUEST.getRoute(report.reportID, CONST.EDIT_REQUEST_FIELD.RECEIPT)),
+ onSelected: () =>
+ Navigation.navigate(
+ ROUTES.MONEY_REQUEST_STEP_SCAN.getRoute(
+ CONST.IOU.ACTION.EDIT,
+ CONST.IOU.TYPE.REQUEST,
+ transaction.transactionID,
+ report.reportID,
+ Navigation.getActiveRouteWithoutParams(),
+ ),
+ ),
});
}
threeDotsMenuItems.push({
diff --git a/src/components/MoneyTemporaryForRefactorRequestConfirmationList.js b/src/components/MoneyTemporaryForRefactorRequestConfirmationList.js
index 2fee67a3d632..36d424ea28f2 100755
--- a/src/components/MoneyTemporaryForRefactorRequestConfirmationList.js
+++ b/src/components/MoneyTemporaryForRefactorRequestConfirmationList.js
@@ -726,26 +726,6 @@ function MoneyTemporaryForRefactorRequestConfirmationList({
)}
{shouldShowAllFields && (
<>
- {shouldShowDate && (
- {
- if (isEditingSplitBill) {
- Navigation.navigate(ROUTES.EDIT_SPLIT_BILL.getRoute(reportID, reportActionID, CONST.EDIT_REQUEST_FIELD.DATE));
- return;
- }
- Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_DATE.getRoute(iouType, transaction.transactionID, reportID, Navigation.getActiveRouteWithoutParams()));
- }}
- disabled={didConfirm}
- interactive={!isReadOnly}
- brickRoadIndicator={shouldDisplayFieldError && TransactionUtils.isCreatedMissing(transaction) ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : ''}
- error={shouldDisplayFieldError && TransactionUtils.isCreatedMissing(transaction) ? translate('common.error.enterDate') : ''}
- />
- )}
{isDistanceRequest && (
)}
+ {shouldShowDate && (
+ {
+ if (isEditingSplitBill) {
+ Navigation.navigate(ROUTES.EDIT_SPLIT_BILL.getRoute(reportID, reportActionID, CONST.EDIT_REQUEST_FIELD.DATE));
+ return;
+ }
+ Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_DATE.getRoute(iouType, transaction.transactionID, reportID, Navigation.getActiveRouteWithoutParams()));
+ }}
+ disabled={didConfirm}
+ interactive={!isReadOnly}
+ brickRoadIndicator={shouldDisplayFieldError && TransactionUtils.isCreatedMissing(transaction) ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : ''}
+ error={shouldDisplayFieldError && TransactionUtils.isCreatedMissing(transaction) ? translate('common.error.enterDate') : ''}
+ />
+ )}
{shouldShowCategories && (
{
+ if (pinchEnabled) {
+ return;
+ }
+ setPinchEnabled(true);
+ }, [pinchEnabled]);
+
const pinchGesture = Gesture.Pinch()
+ .enabled(pinchEnabled)
.onTouchesDown((evt, state) => {
// we don't want to activate pinch gesture when we are scrolling pager
if (!isScrolling.value) {
@@ -466,6 +476,11 @@ function MultiGestureCanvas({canvasSize, isActive = true, onScaleChanged, childr
origin.y.value = adjustFocal.y;
})
.onChange((evt) => {
+ if (evt.numberOfPointers !== 2) {
+ runOnJS(setPinchEnabled)(false);
+ return;
+ }
+
const newZoomScale = pinchScaleOffset.value * evt.scale;
if (zoomScale.value >= zoomRange.min * zoomScaleBounceFactors.min && zoomScale.value <= zoomRange.max * zoomScaleBounceFactors.max) {
diff --git a/src/components/OfflineWithFeedback.tsx b/src/components/OfflineWithFeedback.tsx
index fa0ae5162346..c7d038888c39 100644
--- a/src/components/OfflineWithFeedback.tsx
+++ b/src/components/OfflineWithFeedback.tsx
@@ -4,6 +4,7 @@ import {View} from 'react-native';
import useNetwork from '@hooks/useNetwork';
import useStyleUtils from '@hooks/useStyleUtils';
import useThemeStyles from '@hooks/useThemeStyles';
+import mapChildrenFlat from '@libs/mapChildrenFlat';
import shouldRenderOffscreen from '@libs/shouldRenderOffscreen';
import CONST from '@src/CONST';
import type * as OnyxCommon from '@src/types/onyx/OnyxCommon';
@@ -97,8 +98,8 @@ function OfflineWithFeedback({
* This method applies the strikethrough to all the children passed recursively
*/
const applyStrikeThrough = useCallback(
- (childrenProp: React.ReactNode): React.ReactNode =>
- React.Children.map(childrenProp, (child) => {
+ (childrenProp: React.ReactNode): React.ReactNode => {
+ const strikedThroughChildren = mapChildrenFlat(childrenProp, (child) => {
if (!React.isValidElement(child)) {
return child;
}
@@ -112,7 +113,10 @@ function OfflineWithFeedback({
}
return React.cloneElement(child, props);
- }),
+ });
+
+ return strikedThroughChildren;
+ },
[StyleUtils, styles],
);
diff --git a/src/components/PopoverMenu.tsx b/src/components/PopoverMenu.tsx
index 502bdbf83b53..2d6f74f7cd46 100644
--- a/src/components/PopoverMenu.tsx
+++ b/src/components/PopoverMenu.tsx
@@ -127,6 +127,14 @@ function PopoverMenu({
{isActive: isVisible},
);
+ const onModalHide = () => {
+ setFocusedIndex(-1);
+ if (selectedItemIndex.current !== null) {
+ menuItems[selectedItemIndex.current].onSelected();
+ selectedItemIndex.current = null;
+ }
+ };
+
return (
{
- setFocusedIndex(-1);
- if (selectedItemIndex.current !== null) {
- menuItems[selectedItemIndex.current].onSelected();
- selectedItemIndex.current = null;
- }
- }}
+ onModalHide={onModalHide}
animationIn={animationIn}
animationOut={animationOut}
animationInTiming={animationInTiming}
diff --git a/src/components/QRCode.tsx b/src/components/QRCode.tsx
index 89c367bab222..3accb19acfaf 100644
--- a/src/components/QRCode.tsx
+++ b/src/components/QRCode.tsx
@@ -1,13 +1,13 @@
-import type {Ref} from 'react';
import React from 'react';
import type {ImageSourcePropType} from 'react-native';
import QRCodeLibrary from 'react-native-qrcode-svg';
+import type {Svg} from 'react-native-svg';
import useTheme from '@hooks/useTheme';
import CONST from '@src/CONST';
-type LogoRatio = typeof CONST.QR.DEFAULT_LOGO_SIZE_RATIO | typeof CONST.QR.EXPENSIFY_LOGO_SIZE_RATIO;
+type QRCodeLogoRatio = typeof CONST.QR.DEFAULT_LOGO_SIZE_RATIO | typeof CONST.QR.EXPENSIFY_LOGO_SIZE_RATIO;
-type LogoMarginRatio = typeof CONST.QR.DEFAULT_LOGO_MARGIN_RATIO | typeof CONST.QR.EXPENSIFY_LOGO_MARGIN_RATIO;
+type QRCodeLogoMarginRatio = typeof CONST.QR.DEFAULT_LOGO_MARGIN_RATIO | typeof CONST.QR.EXPENSIFY_LOGO_MARGIN_RATIO;
type QRCodeProps = {
/** The QR code URL */
@@ -20,10 +20,10 @@ type QRCodeProps = {
logo?: ImageSourcePropType;
/** The size ratio of logo to QR code */
- logoRatio?: LogoRatio;
+ logoRatio?: QRCodeLogoRatio;
/** The size ratio of margin around logo to QR code */
- logoMarginRatio?: LogoMarginRatio;
+ logoMarginRatio?: QRCodeLogoMarginRatio;
/** The QRCode size */
size?: number;
@@ -38,7 +38,7 @@ type QRCodeProps = {
* Function to retrieve the internal component ref and be able to call it's
* methods
*/
- getRef?: (ref: Ref) => Ref;
+ getRef?: (ref: Svg) => Svg;
};
function QRCode({url, logo, getRef, size = 120, color, backgroundColor, logoRatio = CONST.QR.DEFAULT_LOGO_SIZE_RATIO, logoMarginRatio = CONST.QR.DEFAULT_LOGO_MARGIN_RATIO}: QRCodeProps) {
@@ -62,3 +62,4 @@ function QRCode({url, logo, getRef, size = 120, color, backgroundColor, logoRati
QRCode.displayName = 'QRCode';
export default QRCode;
+export type {QRCodeLogoMarginRatio, QRCodeLogoRatio};
diff --git a/src/components/QRShare/QRShareWithDownload/index.native.js b/src/components/QRShare/QRShareWithDownload/index.native.js
deleted file mode 100644
index e64c7b69df4a..000000000000
--- a/src/components/QRShare/QRShareWithDownload/index.native.js
+++ /dev/null
@@ -1,46 +0,0 @@
-import React, {forwardRef, useImperativeHandle, useRef} from 'react';
-import ViewShot from 'react-native-view-shot';
-import getQrCodeFileName from '@components/QRShare/getQrCodeDownloadFileName';
-import {qrShareDefaultProps, qrSharePropTypes} from '@components/QRShare/propTypes';
-import useNetwork from '@hooks/useNetwork';
-import fileDownload from '@libs/fileDownload';
-import QRShare from '..';
-
-function QRShareWithDownload({innerRef, ...props}) {
- const {isOffline} = useNetwork();
- const qrCodeScreenshotRef = useRef(null);
-
- useImperativeHandle(
- innerRef,
- () => ({
- download: () => qrCodeScreenshotRef.current.capture().then((uri) => fileDownload(uri, getQrCodeFileName(props.title))),
- }),
- [props.title],
- );
-
- return (
-
-
-
- );
-}
-
-QRShareWithDownload.propTypes = qrSharePropTypes;
-QRShareWithDownload.defaultProps = qrShareDefaultProps;
-QRShareWithDownload.displayName = 'QRShareWithDownload';
-
-const QRShareWithDownloadWithRef = forwardRef((props, ref) => (
-
-));
-
-QRShareWithDownloadWithRef.displayName = 'QRShareWithDownloadWithRef';
-
-export default QRShareWithDownloadWithRef;
diff --git a/src/components/QRShare/QRShareWithDownload/index.native.tsx b/src/components/QRShare/QRShareWithDownload/index.native.tsx
new file mode 100644
index 000000000000..d1d9f13147f1
--- /dev/null
+++ b/src/components/QRShare/QRShareWithDownload/index.native.tsx
@@ -0,0 +1,36 @@
+import type {ForwardedRef} from 'react';
+import React, {forwardRef, useImperativeHandle, useRef} from 'react';
+import ViewShot from 'react-native-view-shot';
+import getQrCodeFileName from '@components/QRShare/getQrCodeDownloadFileName';
+import type {QRShareProps} from '@components/QRShare/types';
+import useNetwork from '@hooks/useNetwork';
+import fileDownload from '@libs/fileDownload';
+import QRShare from '..';
+import type QRShareWithDownloadHandle from './types';
+
+function QRShareWithDownload(props: QRShareProps, ref: ForwardedRef) {
+ const {isOffline} = useNetwork();
+ const qrCodeScreenshotRef = useRef(null);
+
+ useImperativeHandle(
+ ref,
+ () => ({
+ download: () => qrCodeScreenshotRef.current?.capture?.().then((uri) => fileDownload(uri, getQrCodeFileName(props.title))),
+ }),
+ [props.title],
+ );
+
+ return (
+
+
+
+ );
+}
+
+QRShareWithDownload.displayName = 'QRShareWithDownload';
+
+export default forwardRef(QRShareWithDownload);
diff --git a/src/components/QRShare/QRShareWithDownload/index.js b/src/components/QRShare/QRShareWithDownload/index.tsx
similarity index 59%
rename from src/components/QRShare/QRShareWithDownload/index.js
rename to src/components/QRShare/QRShareWithDownload/index.tsx
index bf18a8eedaa4..4a327e9c9249 100644
--- a/src/components/QRShare/QRShareWithDownload/index.js
+++ b/src/components/QRShare/QRShareWithDownload/index.tsx
@@ -1,22 +1,24 @@
+import type {ForwardedRef} from 'react';
import React, {forwardRef, useImperativeHandle, useRef} from 'react';
import getQrCodeFileName from '@components/QRShare/getQrCodeDownloadFileName';
-import {qrShareDefaultProps, qrSharePropTypes} from '@components/QRShare/propTypes';
+import type {QRShareHandle, QRShareProps} from '@components/QRShare/types';
import useNetwork from '@hooks/useNetwork';
import fileDownload from '@libs/fileDownload';
import QRShare from '..';
+import type QRShareWithDownloadHandle from './types';
-function QRShareWithDownload({innerRef, ...props}) {
+function QRShareWithDownload(props: QRShareProps, ref: ForwardedRef) {
const {isOffline} = useNetwork();
- const qrShareRef = useRef(null);
+ const qrShareRef = useRef(null);
useImperativeHandle(
- innerRef,
+ ref,
() => ({
download: () =>
new Promise((resolve, reject) => {
// eslint-disable-next-line es/no-optional-chaining
const svg = qrShareRef.current?.getSvg();
- if (svg == null) {
+ if (!svg) {
return reject();
}
@@ -31,23 +33,11 @@ function QRShareWithDownload({innerRef, ...props}) {
ref={qrShareRef}
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
- logo={isOffline ? null : props.logo}
+ logo={isOffline ? undefined : props.logo}
/>
);
}
-QRShareWithDownload.propTypes = qrSharePropTypes;
-QRShareWithDownload.defaultProps = qrShareDefaultProps;
QRShareWithDownload.displayName = 'QRShareWithDownload';
-const QRShareWithDownloadWithRef = forwardRef((props, ref) => (
-
-));
-
-QRShareWithDownloadWithRef.displayName = 'QRShareWithDownloadWithRef';
-
-export default QRShareWithDownloadWithRef;
+export default forwardRef(QRShareWithDownload);
diff --git a/src/components/QRShare/QRShareWithDownload/types.ts b/src/components/QRShare/QRShareWithDownload/types.ts
new file mode 100644
index 000000000000..c5df9cba55e2
--- /dev/null
+++ b/src/components/QRShare/QRShareWithDownload/types.ts
@@ -0,0 +1,5 @@
+type QRShareWithDownloadHandle = {
+ download: () => Promise | undefined;
+};
+
+export default QRShareWithDownloadHandle;
diff --git a/src/components/QRShare/getQrCodeDownloadFileName.js b/src/components/QRShare/getQrCodeDownloadFileName.js
deleted file mode 100644
index c1e73a1794fb..000000000000
--- a/src/components/QRShare/getQrCodeDownloadFileName.js
+++ /dev/null
@@ -1,3 +0,0 @@
-const getQrCodeDownloadFileName = (title) => `${title}-ShareCode.png`;
-
-export default getQrCodeDownloadFileName;
diff --git a/src/components/QRShare/getQrCodeDownloadFileName.ts b/src/components/QRShare/getQrCodeDownloadFileName.ts
new file mode 100644
index 000000000000..7041eac2b4b4
--- /dev/null
+++ b/src/components/QRShare/getQrCodeDownloadFileName.ts
@@ -0,0 +1,3 @@
+const getQrCodeDownloadFileName = (title: string): string => `${title}-ShareCode.png`;
+
+export default getQrCodeDownloadFileName;
diff --git a/src/components/QRShare/index.js b/src/components/QRShare/index.tsx
similarity index 76%
rename from src/components/QRShare/index.js
rename to src/components/QRShare/index.tsx
index b1fc4c6fa2d8..c7e9e7637a6c 100644
--- a/src/components/QRShare/index.js
+++ b/src/components/QRShare/index.tsx
@@ -1,6 +1,8 @@
+import type {ForwardedRef} from 'react';
import React, {forwardRef, useImperativeHandle, useRef, useState} from 'react';
+import type {LayoutChangeEvent} from 'react-native';
import {View} from 'react-native';
-import _ from 'underscore';
+import type {Svg} from 'react-native-svg';
import ExpensifyWordmark from '@assets/images/expensify-wordmark.svg';
import ImageSVG from '@components/ImageSVG';
import QRCode from '@components/QRCode';
@@ -8,24 +10,24 @@ import Text from '@components/Text';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import variables from '@styles/variables';
-import {qrShareDefaultProps, qrSharePropTypes} from './propTypes';
+import type {QRShareHandle, QRShareProps} from './types';
-function QRShare({innerRef, url, title, subtitle, logo, logoRatio, logoMarginRatio}) {
+function QRShare({url, title, subtitle, logo, logoRatio, logoMarginRatio}: QRShareProps, ref: ForwardedRef) {
const styles = useThemeStyles();
const theme = useTheme();
const [qrCodeSize, setQrCodeSize] = useState(1);
- const svgRef = useRef(null);
+ const svgRef = useRef();
useImperativeHandle(
- innerRef,
+ ref,
() => ({
getSvg: () => svgRef.current,
}),
[],
);
- const onLayout = (event) => {
+ const onLayout = (event: LayoutChangeEvent) => {
const containerWidth = event.nativeEvent.layout.width - variables.qrShareHorizontalPadding * 2 || 0;
setQrCodeSize(Math.max(1, containerWidth));
};
@@ -61,7 +63,7 @@ function QRShare({innerRef, url, title, subtitle, logo, logoRatio, logoMarginRat
{title}
- {!_.isEmpty(subtitle) && (
+ {!!subtitle && (
(
-
-));
-
-QRShareWithRef.displayName = 'QRShareWithRef';
-
-export default QRShareWithRef;
+export default forwardRef(QRShare);
diff --git a/src/components/QRShare/propTypes.js b/src/components/QRShare/propTypes.js
deleted file mode 100644
index 28275bc724b1..000000000000
--- a/src/components/QRShare/propTypes.js
+++ /dev/null
@@ -1,45 +0,0 @@
-import PropTypes from 'prop-types';
-
-const qrSharePropTypes = {
- /**
- * The QR code URL
- */
- url: PropTypes.string.isRequired,
-
- /**
- * The title that is displayed below the QR Code (usually the user or report name)
- */
- title: PropTypes.string.isRequired,
-
- /**
- * The subtitle which will be shown below the title (usually user email or workspace name)
- * */
- subtitle: PropTypes.string,
-
- /**
- * The logo which will be display in the middle of the QR code
- */
- logo: PropTypes.oneOfType([PropTypes.shape({uri: PropTypes.string}), PropTypes.number, PropTypes.string]),
-
- /**
- * The size ratio of logo to QR code
- */
- logoRatio: PropTypes.number,
-
- /**
- * The size ratio of margin around logo to QR code
- */
- logoMarginRatio: PropTypes.number,
-
- /**
- * Forwarded ref
- */
- innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
-};
-
-const qrShareDefaultProps = {
- subtitle: undefined,
- logo: undefined,
-};
-
-export {qrSharePropTypes, qrShareDefaultProps};
diff --git a/src/components/QRShare/types.ts b/src/components/QRShare/types.ts
new file mode 100644
index 000000000000..db9afdf73c2a
--- /dev/null
+++ b/src/components/QRShare/types.ts
@@ -0,0 +1,41 @@
+import type {ImageSourcePropType} from 'react-native';
+import type {Svg} from 'react-native-svg';
+import type {QRCodeLogoMarginRatio, QRCodeLogoRatio} from '@components/QRCode';
+
+type QRShareProps = {
+ /**
+ * The QR code URL
+ */
+ url: string;
+
+ /**
+ * The title that is displayed below the QR Code (usually the user or report name)
+ */
+ title: string;
+
+ /**
+ * The subtitle which will be shown below the title (usually user email or workspace name)
+ * */
+ subtitle?: string;
+
+ /**
+ * The logo which will be display in the middle of the QR code
+ */
+ logo?: ImageSourcePropType;
+
+ /**
+ * The size ratio of logo to QR code
+ */
+ logoRatio?: QRCodeLogoRatio;
+
+ /**
+ * The size ratio of margin around logo to QR code
+ */
+ logoMarginRatio?: QRCodeLogoMarginRatio;
+};
+
+type QRShareHandle = {
+ getSvg: () => Svg | undefined;
+};
+
+export type {QRShareHandle, QRShareProps};
diff --git a/src/components/Reactions/ReportActionItemEmojiReactions.tsx b/src/components/Reactions/ReportActionItemEmojiReactions.tsx
index d1a2cf56b6a5..69779dc316e1 100644
--- a/src/components/Reactions/ReportActionItemEmojiReactions.tsx
+++ b/src/components/Reactions/ReportActionItemEmojiReactions.tsx
@@ -67,7 +67,7 @@ type FormattedReaction = {
reactionEmojiName: string;
/** The type of action that's pending */
- pendingAction: PendingAction;
+ pendingAction?: PendingAction;
};
function ReportActionItemEmojiReactions({
diff --git a/src/components/ReportActionItem/MoneyRequestView.js b/src/components/ReportActionItem/MoneyRequestView.js
index 37ff163f23c8..036b64af1e4b 100644
--- a/src/components/ReportActionItem/MoneyRequestView.js
+++ b/src/components/ReportActionItem/MoneyRequestView.js
@@ -179,6 +179,19 @@ function MoneyRequestView({report, parentReport, parentReportActions, policyCate
let amountDescription = `${translate('iou.amount')}`;
+ const saveBillable = useCallback(
+ (newBillable) => {
+ // If the value hasn't changed, don't request to save changes on the server and just close the modal
+ if (newBillable === TransactionUtils.getBillable(transaction)) {
+ Navigation.dismissModal();
+ return;
+ }
+ IOU.updateMoneyRequestBillable(transaction.transactionID, report.reportID, newBillable);
+ Navigation.dismissModal();
+ },
+ [transaction, report],
+ );
+
if (isCardTransaction) {
if (formattedOriginalAmount) {
amountDescription += ` • ${translate('iou.original')} ${formattedOriginalAmount}`;
@@ -209,7 +222,7 @@ function MoneyRequestView({report, parentReport, parentReportActions, policyCate
let hasErrors = false;
if (hasReceipt) {
receiptURIs = ReceiptUtils.getThumbnailAndImageURIs(transaction);
- hasErrors = canEditReceipt && TransactionUtils.hasMissingSmartscanFields(transaction);
+ hasErrors = canEdit && TransactionUtils.hasMissingSmartscanFields(transaction);
}
const pendingAction = lodashGet(transaction, 'pendingAction');
@@ -236,7 +249,17 @@ function MoneyRequestView({report, parentReport, parentReportActions, policyCate
{!hasReceipt && canEditReceipt && canUseViolations && (
Navigation.navigate(ROUTES.EDIT_REQUEST.getRoute(report.reportID, CONST.EDIT_REQUEST_FIELD.RECEIPT))}
+ onPress={() =>
+ Navigation.navigate(
+ ROUTES.MONEY_REQUEST_STEP_SCAN.getRoute(
+ CONST.IOU.ACTION.EDIT,
+ CONST.IOU.TYPE.REQUEST,
+ transaction.transactionID,
+ report.reportID,
+ Navigation.getActiveRouteWithoutParams(),
+ ),
+ )
+ }
/>
)}
{canUseViolations && }
@@ -354,7 +377,7 @@ function MoneyRequestView({report, parentReport, parentReportActions, policyCate
IOU.editMoneyRequest(transaction, report.reportID, {billable: value})}
+ onToggle={saveBillable}
/>
{hasViolations('billable') && (
diff --git a/src/components/ReportActionItem/ReportPreview.js b/src/components/ReportActionItem/ReportPreview.js
index 27447a10a32b..abc7e3954200 100644
--- a/src/components/ReportActionItem/ReportPreview.js
+++ b/src/components/ReportActionItem/ReportPreview.js
@@ -15,7 +15,6 @@ import {showContextMenuForReport} from '@components/ShowContextMenuContext';
import Text from '@components/Text';
import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import useLocalize from '@hooks/useLocalize';
-import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import compose from '@libs/compose';
@@ -30,7 +29,6 @@ import * as ReportUtils from '@libs/ReportUtils';
import * as TransactionUtils from '@libs/TransactionUtils';
import reportActionPropTypes from '@pages/home/report/reportActionPropTypes';
import reportPropTypes from '@pages/reportPropTypes';
-import variables from '@styles/variables';
import * as IOU from '@userActions/IOU';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
@@ -128,7 +126,6 @@ const defaultProps = {
function ReportPreview(props) {
const theme = useTheme();
const styles = useThemeStyles();
- const {getLineHeightStyle} = useStyleUtils();
const {translate} = useLocalize();
const [hasMissingSmartscanFields, sethasMissingSmartscanFields] = useState(false);
@@ -286,7 +283,7 @@ function ReportPreview(props) {
- {getPreviewMessage()}
+ {getPreviewMessage()}
{!iouSettled && hasErrors && (
translate(`reportActionsView.iouTypes.${item}`)).join(', ');
const navigateToReport = () => {
if (!report?.reportID) {
@@ -112,7 +113,9 @@ function ReportWelcomeText({report, policy, personalDetails}: ReportWelcomeTextP
))}
)}
- {(moneyRequestOptions.includes(CONST.IOU.TYPE.SEND) || moneyRequestOptions.includes(CONST.IOU.TYPE.REQUEST)) && {translate('reportActionsView.usePlusButton')} }
+ {(moneyRequestOptions.includes(CONST.IOU.TYPE.SEND) || moneyRequestOptions.includes(CONST.IOU.TYPE.REQUEST)) && (
+ {translate('reportActionsView.usePlusButton', {additionalText})}
+ )}
>
);
diff --git a/src/components/SelectionList/BaseSelectionList.js b/src/components/SelectionList/BaseSelectionList.js
index 88c4018f823c..bebb77a43fd4 100644
--- a/src/components/SelectionList/BaseSelectionList.js
+++ b/src/components/SelectionList/BaseSelectionList.js
@@ -14,7 +14,7 @@ import SectionList from '@components/SectionList';
import Text from '@components/Text';
import TextInput from '@components/TextInput';
import withKeyboardState, {keyboardStatePropTypes} from '@components/withKeyboardState';
-import useActiveElement from '@hooks/useActiveElement';
+import useActiveElementRole from '@hooks/useActiveElementRole';
import useKeyboardShortcut from '@hooks/useKeyboardShortcut';
import useLocalize from '@hooks/useLocalize';
import useStyleUtils from '@hooks/useStyleUtils';
@@ -40,6 +40,7 @@ function BaseSelectionList({
textInputLabel = '',
textInputPlaceholder = '',
textInputValue = '',
+ textInputHint = '',
textInputMaxLength,
inputMode = CONST.INPUT_MODE.TEXT,
onChangeText,
@@ -73,7 +74,7 @@ function BaseSelectionList({
const focusTimeoutRef = useRef(null);
const shouldShowTextInput = Boolean(textInputLabel);
const shouldShowSelectAll = Boolean(onSelectAll);
- const activeElement = useActiveElement();
+ const activeElementRole = useActiveElementRole();
const isFocused = useIsFocused();
const [maxToRenderPerBatch, setMaxToRenderPerBatch] = useState(shouldUseDynamicMaxToRenderPerBatch ? 0 : CONST.MAX_TO_RENDER_PER_BATCH.DEFAULT);
const [isInitialSectionListRender, setIsInitialSectionListRender] = useState(true);
@@ -155,7 +156,7 @@ function BaseSelectionList({
const [focusedIndex, setFocusedIndex] = useState(() => _.findIndex(flattenedSections.allOptions, (option) => option.keyForList === initiallyFocusedOptionKey));
// Disable `Enter` shortcut if the active element is a button or checkbox
- const disableEnterShortcut = activeElement && [CONST.ROLE.BUTTON, CONST.ROLE.CHECKBOX].includes(activeElement.role);
+ const disableEnterShortcut = activeElementRole && [CONST.ROLE.BUTTON, CONST.ROLE.CHECKBOX].includes(activeElementRole);
/**
* Scrolls to the desired item index in the section list
@@ -413,6 +414,7 @@ function BaseSelectionList({
}}
label={textInputLabel}
accessibilityLabel={textInputLabel}
+ hint={textInputHint}
role={CONST.ROLE.PRESENTATION}
value={textInputValue}
placeholder={textInputPlaceholder}
diff --git a/src/components/SignInButtons/AppleAuthWrapper/index.ios.js b/src/components/SignInButtons/AppleAuthWrapper/index.ios.tsx
similarity index 81%
rename from src/components/SignInButtons/AppleAuthWrapper/index.ios.js
rename to src/components/SignInButtons/AppleAuthWrapper/index.ios.tsx
index 69882d89b1fe..12ead0267db3 100644
--- a/src/components/SignInButtons/AppleAuthWrapper/index.ios.js
+++ b/src/components/SignInButtons/AppleAuthWrapper/index.ios.tsx
@@ -5,19 +5,18 @@ import * as Session from '@userActions/Session';
/**
* Apple Sign In wrapper for iOS
* revokes the session if the credential is revoked.
- *
- * @returns {null}
*/
function AppleAuthWrapper() {
useEffect(() => {
if (!appleAuth.isSupported) {
return;
}
- const listener = appleAuth.onCredentialRevoked(() => {
+ const removeListener = appleAuth.onCredentialRevoked(() => {
Session.signOut();
});
+
return () => {
- listener.remove();
+ removeListener();
};
}, []);
diff --git a/src/components/SignInButtons/AppleAuthWrapper/index.js b/src/components/SignInButtons/AppleAuthWrapper/index.tsx
similarity index 100%
rename from src/components/SignInButtons/AppleAuthWrapper/index.js
rename to src/components/SignInButtons/AppleAuthWrapper/index.tsx
diff --git a/src/components/SignInButtons/AppleSignIn/index.android.js b/src/components/SignInButtons/AppleSignIn/index.android.tsx
similarity index 92%
rename from src/components/SignInButtons/AppleSignIn/index.android.js
rename to src/components/SignInButtons/AppleSignIn/index.android.tsx
index 9dc736789c61..cfd1c48ee8b5 100644
--- a/src/components/SignInButtons/AppleSignIn/index.android.js
+++ b/src/components/SignInButtons/AppleSignIn/index.android.tsx
@@ -18,9 +18,9 @@ const config = {
/**
* Apple Sign In method for Android that returns authToken.
- * @returns {Promise}
+ * @returns Promise that returns a string when resolved
*/
-function appleSignInRequest() {
+function appleSignInRequest(): Promise {
appleAuthAndroid.configure(config);
return appleAuthAndroid
.signIn()
@@ -32,7 +32,6 @@ function appleSignInRequest() {
/**
* Apple Sign In button for Android.
- * @returns {React.Component}
*/
function AppleSignIn() {
const handleSignIn = () => {
diff --git a/src/components/SignInButtons/AppleSignIn/index.desktop.js b/src/components/SignInButtons/AppleSignIn/index.desktop.tsx
similarity index 96%
rename from src/components/SignInButtons/AppleSignIn/index.desktop.js
rename to src/components/SignInButtons/AppleSignIn/index.desktop.tsx
index cc7ae5b623a5..792c16ed0b4a 100644
--- a/src/components/SignInButtons/AppleSignIn/index.desktop.js
+++ b/src/components/SignInButtons/AppleSignIn/index.desktop.tsx
@@ -10,7 +10,6 @@ const appleSignInWebRouteForDesktopFlow = `${CONFIG.EXPENSIFY.NEW_EXPENSIFY_URL}
/**
* Apple Sign In button for desktop flow
- * @returns {React.Component}
*/
function AppleSignIn() {
const styles = useThemeStyles();
diff --git a/src/components/SignInButtons/AppleSignIn/index.ios.js b/src/components/SignInButtons/AppleSignIn/index.ios.tsx
similarity index 91%
rename from src/components/SignInButtons/AppleSignIn/index.ios.js
rename to src/components/SignInButtons/AppleSignIn/index.ios.tsx
index f5c6333dcf7b..3fb1179d0365 100644
--- a/src/components/SignInButtons/AppleSignIn/index.ios.js
+++ b/src/components/SignInButtons/AppleSignIn/index.ios.tsx
@@ -7,9 +7,9 @@ import CONST from '@src/CONST';
/**
* Apple Sign In method for iOS that returns identityToken.
- * @returns {Promise}
+ * @returns Promise that returns a string when resolved
*/
-function appleSignInRequest() {
+function appleSignInRequest(): Promise {
return appleAuth
.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
@@ -20,7 +20,7 @@ function appleSignInRequest() {
.then((response) =>
appleAuth.getCredentialStateForUser(response.user).then((credentialState) => {
if (credentialState !== appleAuth.State.AUTHORIZED) {
- Log.alert('[Apple Sign In] Authentication failed. Original response: ', response);
+ Log.alert('[Apple Sign In] Authentication failed. Original response: ', {response});
throw new Error('Authentication failed');
}
return response.identityToken;
@@ -30,7 +30,6 @@ function appleSignInRequest() {
/**
* Apple Sign In button for iOS.
- * @returns {React.Component}
*/
function AppleSignIn() {
const handleSignIn = () => {
diff --git a/src/components/SignInButtons/AppleSignIn/index.website.js b/src/components/SignInButtons/AppleSignIn/index.website.tsx
similarity index 75%
rename from src/components/SignInButtons/AppleSignIn/index.website.js
rename to src/components/SignInButtons/AppleSignIn/index.website.tsx
index adae0a691e13..9d7322878c98 100644
--- a/src/components/SignInButtons/AppleSignIn/index.website.js
+++ b/src/components/SignInButtons/AppleSignIn/index.website.tsx
@@ -1,45 +1,39 @@
-import get from 'lodash/get';
-import PropTypes from 'prop-types';
import React, {useEffect, useState} from 'react';
+import type {NativeConfig} from 'react-native-config';
import Config from 'react-native-config';
import getUserLanguage from '@components/SignInButtons/GetUserLanguage';
+import type {WithNavigationFocusProps} from '@components/withNavigationFocus';
import withNavigationFocus from '@components/withNavigationFocus';
import Log from '@libs/Log';
import * as Session from '@userActions/Session';
import CONFIG from '@src/CONFIG';
import CONST from '@src/CONST';
+import type {AppleIDSignInOnFailureEvent, AppleIDSignInOnSuccessEvent} from '@src/types/modules/dom';
// react-native-config doesn't trim whitespace on iOS for some reason so we
// add a trim() call to lodashGet here to prevent headaches.
-const lodashGet = (config, key, defaultValue) => get(config, key, defaultValue).trim();
+const getConfig = (config: NativeConfig, key: string, defaultValue: string) => (config?.[key] ?? defaultValue).trim();
-const requiredPropTypes = {
- isDesktopFlow: PropTypes.bool.isRequired,
+type AppleSignInDivProps = {
+ isDesktopFlow: boolean;
};
-const singletonPropTypes = {
- ...requiredPropTypes,
-
- // From withNavigationFocus
- isFocused: PropTypes.bool.isRequired,
+type SingletonAppleSignInButtonProps = AppleSignInDivProps & {
+ isFocused: boolean;
};
-const propTypes = {
- // Prop to indicate if this is the desktop flow or not.
- isDesktopFlow: PropTypes.bool,
-};
-const defaultProps = {
- isDesktopFlow: false,
+type AppleSignInProps = WithNavigationFocusProps & {
+ isDesktopFlow?: boolean;
};
/**
* Apple Sign In Configuration for Web.
*/
const config = {
- clientId: lodashGet(Config, 'ASI_CLIENTID_OVERRIDE', CONFIG.APPLE_SIGN_IN.SERVICE_ID),
+ clientId: getConfig(Config, 'ASI_CLIENTID_OVERRIDE', CONFIG.APPLE_SIGN_IN.SERVICE_ID),
scope: 'name email',
// never used, but required for configuration
- redirectURI: lodashGet(Config, 'ASI_REDIRECTURI_OVERRIDE', CONFIG.APPLE_SIGN_IN.REDIRECT_URI),
+ redirectURI: getConfig(Config, 'ASI_REDIRECTURI_OVERRIDE', CONFIG.APPLE_SIGN_IN.REDIRECT_URI),
state: '',
nonce: '',
usePopup: true,
@@ -49,23 +43,22 @@ const config = {
* Apple Sign In success and failure listeners.
*/
-const successListener = (event) => {
+const successListener = (event: AppleIDSignInOnSuccessEvent) => {
const token = event.detail.authorization.id_token;
Session.beginAppleSignIn(token);
};
-const failureListener = (event) => {
+const failureListener = (event: AppleIDSignInOnFailureEvent) => {
if (!event.detail || event.detail.error === 'popup_closed_by_user') {
return null;
}
- Log.warn(`Apple sign-in failed: ${event.detail}`);
+ Log.warn(`Apple sign-in failed: ${event.detail.error}`);
};
/**
* Apple Sign In button for Web.
- * @returns {React.Component}
*/
-function AppleSignInDiv({isDesktopFlow}) {
+function AppleSignInDiv({isDesktopFlow}: AppleSignInDivProps) {
useEffect(() => {
// `init` renders the button, so it must be called after the div is
// first mounted.
@@ -108,24 +101,20 @@ function AppleSignInDiv({isDesktopFlow}) {
);
}
-AppleSignInDiv.propTypes = requiredPropTypes;
-
// The Sign in with Apple script may fail to render button if there are multiple
// of these divs present in the app, as it matches based on div id. So we'll
// only mount the div when it should be visible.
-function SingletonAppleSignInButton({isFocused, isDesktopFlow}) {
+function SingletonAppleSignInButton({isFocused, isDesktopFlow}: SingletonAppleSignInButtonProps) {
if (!isFocused) {
return null;
}
return ;
}
-SingletonAppleSignInButton.propTypes = singletonPropTypes;
-
// withNavigationFocus is used to only render the button when it is visible.
const SingletonAppleSignInButtonWithFocus = withNavigationFocus(SingletonAppleSignInButton);
-function AppleSignIn({isDesktopFlow}) {
+function AppleSignIn({isDesktopFlow = false}: AppleSignInProps) {
const [scriptLoaded, setScriptLoaded] = useState(false);
useEffect(() => {
if (window.appleAuthScriptLoaded) {
@@ -148,7 +137,5 @@ function AppleSignIn({isDesktopFlow}) {
return ;
}
-AppleSignIn.propTypes = propTypes;
-AppleSignIn.defaultProps = defaultProps;
-
+AppleSignIn.displayName = 'AppleSignIn';
export default withNavigationFocus(AppleSignIn);
diff --git a/src/components/SignInButtons/GetUserLanguage.js b/src/components/SignInButtons/GetUserLanguage.ts
similarity index 50%
rename from src/components/SignInButtons/GetUserLanguage.js
rename to src/components/SignInButtons/GetUserLanguage.ts
index 7f45f1fa1e89..a1101e92f656 100644
--- a/src/components/SignInButtons/GetUserLanguage.js
+++ b/src/components/SignInButtons/GetUserLanguage.ts
@@ -1,11 +1,16 @@
+import type {ValueOf} from 'type-fest';
+
const localeCodes = {
en: 'en_US',
es: 'es_ES',
-};
+} as const;
+
+type LanguageCode = keyof typeof localeCodes;
+type LocaleCode = ValueOf;
-const GetUserLanguage = () => {
+const GetUserLanguage = (): LocaleCode => {
const userLanguage = navigator.language || navigator.userLanguage;
- const languageCode = userLanguage.split('-')[0];
+ const languageCode = userLanguage.split('-')[0] as LanguageCode;
return localeCodes[languageCode] || 'en_US';
};
diff --git a/src/components/SignInButtons/GoogleSignIn/index.desktop.js b/src/components/SignInButtons/GoogleSignIn/index.desktop.tsx
similarity index 78%
rename from src/components/SignInButtons/GoogleSignIn/index.desktop.js
rename to src/components/SignInButtons/GoogleSignIn/index.desktop.tsx
index 9284a5332e3d..3c2abb1679f0 100644
--- a/src/components/SignInButtons/GoogleSignIn/index.desktop.js
+++ b/src/components/SignInButtons/GoogleSignIn/index.desktop.tsx
@@ -1,19 +1,15 @@
import React from 'react';
import {View} from 'react-native';
import IconButton from '@components/SignInButtons/IconButton';
-import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import CONFIG from '@src/CONFIG';
import CONST from '@src/CONST';
import ROUTES from '@src/ROUTES';
-const propTypes = {...withLocalizePropTypes};
-
const googleSignInWebRouteForDesktopFlow = `${CONFIG.EXPENSIFY.NEW_EXPENSIFY_URL}${ROUTES.GOOGLE_SIGN_IN}`;
/**
* Google Sign In button for desktop flow.
- * @returns {React.Component}
*/
function GoogleSignIn() {
const styles = useThemeStyles();
@@ -30,6 +26,5 @@ function GoogleSignIn() {
}
GoogleSignIn.displayName = 'GoogleSignIn';
-GoogleSignIn.propTypes = propTypes;
-export default withLocalize(GoogleSignIn);
+export default GoogleSignIn;
diff --git a/src/components/SignInButtons/GoogleSignIn/index.native.js b/src/components/SignInButtons/GoogleSignIn/index.native.tsx
similarity index 98%
rename from src/components/SignInButtons/GoogleSignIn/index.native.js
rename to src/components/SignInButtons/GoogleSignIn/index.native.tsx
index c7ac763cfb73..2744d8958080 100644
--- a/src/components/SignInButtons/GoogleSignIn/index.native.js
+++ b/src/components/SignInButtons/GoogleSignIn/index.native.tsx
@@ -43,7 +43,6 @@ function googleSignInRequest() {
/**
* Google Sign In button for iOS.
- * @returns {React.Component}
*/
function GoogleSignIn() {
return (
diff --git a/src/components/SignInButtons/GoogleSignIn/index.website.js b/src/components/SignInButtons/GoogleSignIn/index.website.tsx
similarity index 83%
rename from src/components/SignInButtons/GoogleSignIn/index.website.js
rename to src/components/SignInButtons/GoogleSignIn/index.website.tsx
index 8f8a977bdb09..3cc4cdebffa6 100644
--- a/src/components/SignInButtons/GoogleSignIn/index.website.js
+++ b/src/components/SignInButtons/GoogleSignIn/index.website.tsx
@@ -1,28 +1,21 @@
-import PropTypes from 'prop-types';
import React, {useCallback} from 'react';
import {View} from 'react-native';
-import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
+import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import * as Session from '@userActions/Session';
import CONFIG from '@src/CONFIG';
import CONST from '@src/CONST';
+import type Response from '@src/types/modules/google';
-const propTypes = {
- /** Whether we're rendering in the Desktop Flow, if so show a different button. */
- isDesktopFlow: PropTypes.bool,
-
- ...withLocalizePropTypes,
-};
-
-const defaultProps = {
- isDesktopFlow: false,
+type GoogleSignInProps = {
+ isDesktopFlow?: boolean;
};
/** Div IDs for styling the two different Google Sign-In buttons. */
const mainId = 'google-sign-in-main';
const desktopId = 'google-sign-in-desktop';
-const signIn = (response) => {
+const signIn = (response: Response) => {
Session.beginGoogleSignIn(response.credential);
};
@@ -31,12 +24,15 @@ const signIn = (response) => {
* We have to load the gis script and then determine if the page is focused before rendering the button.
* @returns {React.Component}
*/
-function GoogleSignIn({translate, isDesktopFlow}) {
+
+function GoogleSignIn({isDesktopFlow = false}: GoogleSignInProps) {
+ const {translate} = useLocalize();
const styles = useThemeStyles();
const loadScript = useCallback(() => {
const google = window.google;
if (google) {
google.accounts.id.initialize({
+ // eslint-disable-next-line @typescript-eslint/naming-convention
client_id: CONFIG.GOOGLE_SIGN_IN.WEB_CLIENT_ID,
callback: signIn,
});
@@ -92,7 +88,5 @@ function GoogleSignIn({translate, isDesktopFlow}) {
}
GoogleSignIn.displayName = 'GoogleSignIn';
-GoogleSignIn.propTypes = propTypes;
-GoogleSignIn.defaultProps = defaultProps;
-export default withLocalize(GoogleSignIn);
+export default GoogleSignIn;
diff --git a/src/components/SignInButtons/IconButton.js b/src/components/SignInButtons/IconButton.tsx
similarity index 65%
rename from src/components/SignInButtons/IconButton.js
rename to src/components/SignInButtons/IconButton.tsx
index 19a5bd9b27b8..7ef476cff18a 100644
--- a/src/components/SignInButtons/IconButton.js
+++ b/src/components/SignInButtons/IconButton.tsx
@@ -1,25 +1,13 @@
-import PropTypes from 'prop-types';
import React from 'react';
+import type {ValueOf} from 'type-fest';
import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';
import PressableWithoutFeedback from '@components/Pressable/PressableWithoutFeedback';
-import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
+import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import CONST from '@src/CONST';
-
-const propTypes = {
- /** The on press method */
- onPress: PropTypes.func,
-
- /** Which provider you are using to sign in */
- provider: PropTypes.string.isRequired,
-
- ...withLocalizePropTypes,
-};
-
-const defaultProps = {
- onPress: () => {},
-};
+import type {TranslationPaths} from '@src/languages/types';
+import type IconAsset from '@src/types/utils/IconAsset';
const providerData = {
[CONST.SIGN_IN_METHOD.APPLE]: {
@@ -30,9 +18,21 @@ const providerData = {
icon: Expensicons.GoogleLogo,
accessibilityLabel: 'common.signInWithGoogle',
},
+} satisfies Record<
+ ValueOf,
+ {
+ icon: IconAsset;
+ accessibilityLabel: TranslationPaths;
+ }
+>;
+
+type IconButtonProps = {
+ onPress?: () => void;
+ provider: ValueOf;
};
-function IconButton({onPress, translate, provider}) {
+function IconButton({onPress = () => {}, provider}: IconButtonProps) {
+ const {translate} = useLocalize();
const styles = useThemeStyles();
return (
{},
label: undefined,
+ onBlur: () => {},
};
-function StatePicker({value, errorText, onInputChange, forwardedRef, label}) {
+function StatePicker({value, errorText, onInputChange, forwardedRef, label, onBlur}) {
const styles = useThemeStyles();
const {translate} = useLocalize();
const [isPickerVisible, setIsPickerVisible] = useState(false);
@@ -45,7 +49,10 @@ function StatePicker({value, errorText, onInputChange, forwardedRef, label}) {
setIsPickerVisible(true);
};
- const hidePickerModal = () => {
+ const hidePickerModal = (shouldBlur = true) => {
+ if (shouldBlur) {
+ onBlur();
+ }
setIsPickerVisible(false);
};
@@ -53,7 +60,9 @@ function StatePicker({value, errorText, onInputChange, forwardedRef, label}) {
if (state.value !== value) {
onInputChange(state.value);
}
- hidePickerModal();
+ // If the user selects any state, call the hidePickerModal function with shouldBlur = false
+ // to prevent the onBlur function from being called.
+ hidePickerModal(false);
};
const title = value && _.keys(COMMON_CONST.STATES).includes(value) ? translate(`allStates.${value}.stateName`) : '';
diff --git a/src/components/TextInput/BaseTextInput/index.native.tsx b/src/components/TextInput/BaseTextInput/index.native.tsx
index f4cc1ee9e0ba..d19d835d68bb 100644
--- a/src/components/TextInput/BaseTextInput/index.native.tsx
+++ b/src/components/TextInput/BaseTextInput/index.native.tsx
@@ -37,6 +37,7 @@ function BaseTextInput(
errorText = '',
icon = null,
textInputContainerStyles,
+ touchableInputWrapperStyle,
containerStyles,
inputStyle,
forceActiveLabel = false,
@@ -273,7 +274,7 @@ function BaseTextInput(
style={[
autoGrowHeight && styles.autoGrowHeightInputContainer(textInputHeight, variables.componentSizeLarge, typeof maxHeight === 'number' ? maxHeight : 0),
!isMultiline && styles.componentHeightLarge,
- containerStyles,
+ touchableInputWrapperStyle,
]}
>
;
diff --git a/src/components/Tooltip/BaseTooltip/index.tsx b/src/components/Tooltip/BaseTooltip/index.tsx
index cf249a936f0b..2487cbbfe092 100644
--- a/src/components/Tooltip/BaseTooltip/index.tsx
+++ b/src/components/Tooltip/BaseTooltip/index.tsx
@@ -10,9 +10,9 @@ import useLocalize from '@hooks/useLocalize';
import usePrevious from '@hooks/usePrevious';
import useWindowDimensions from '@hooks/useWindowDimensions';
import * as DeviceCapabilities from '@libs/DeviceCapabilities';
+import StringUtils from '@libs/StringUtils';
import variables from '@styles/variables';
import CONST from '@src/CONST';
-import StringUtils from '@src/libs/StringUtils';
import callOrReturn from '@src/types/utils/callOrReturn';
const hasHoverSupport = DeviceCapabilities.hasHoverSupport();
@@ -185,6 +185,16 @@ function Tooltip(
setIsVisible(false);
}, []);
+ const updateTargetPositionOnMouseEnter = useCallback(
+ (e: MouseEvent) => {
+ updateTargetAndMousePosition(e);
+ if (React.isValidElement(children)) {
+ children.props.onMouseEnter?.(e);
+ }
+ },
+ [children, updateTargetAndMousePosition],
+ );
+
// Skip the tooltip and return the children if the text is empty,
// we don't have a render function or the device does not support hovering
if ((StringUtils.isEmptyString(text) && renderTooltipContent == null) || !hasHoverSupport) {
@@ -212,20 +222,30 @@ function Tooltip(
key={[text, ...renderTooltipContentKey, preferredLocale].join('-')}
/>
)}
-
-
- {children}
-
-
+
+ {
+ // Checks if valid element so we can wrap the BoundsObserver around it
+ // If not, we just return the primitive children
+ React.isValidElement(children) ? (
+
+
+ {React.cloneElement(children as React.ReactElement, {
+ onMouseEnter: updateTargetPositionOnMouseEnter,
+ })}
+
+
+ ) : (
+ children
+ )
+ }
>
);
}
diff --git a/src/components/ValidateCode/ValidateCodeModal.tsx b/src/components/ValidateCode/ValidateCodeModal.tsx
index 9c83a80b0d24..1e42773c2dc2 100644
--- a/src/components/ValidateCode/ValidateCodeModal.tsx
+++ b/src/components/ValidateCode/ValidateCodeModal.tsx
@@ -40,7 +40,6 @@ function ValidateCodeModal({code, accountID, session = {}}: ValidateCodeModalPro
diff --git a/src/components/withKeyboardState.tsx b/src/components/withKeyboardState.tsx
index 2a74fd3e738e..74d10945fbcb 100755
--- a/src/components/withKeyboardState.tsx
+++ b/src/components/withKeyboardState.tsx
@@ -16,7 +16,9 @@ const keyboardStatePropTypes = {
isKeyboardShown: PropTypes.bool.isRequired,
};
-const KeyboardStateContext = createContext(null);
+const KeyboardStateContext = createContext({
+ isKeyboardShown: false,
+});
function KeyboardStateProvider({children}: ChildrenProps): ReactElement | null {
const [isKeyboardShown, setIsKeyboardShown] = useState(false);
diff --git a/src/components/withNavigationFocus.tsx b/src/components/withNavigationFocus.tsx
index 90a674a2e56e..bd7a39620114 100644
--- a/src/components/withNavigationFocus.tsx
+++ b/src/components/withNavigationFocus.tsx
@@ -25,3 +25,5 @@ export default function withNavigationFocus null;
-
-export default useActiveElement;
diff --git a/src/hooks/useActiveElement/types.ts b/src/hooks/useActiveElement/types.ts
deleted file mode 100644
index f3b5193975a5..000000000000
--- a/src/hooks/useActiveElement/types.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-type UseActiveElement = () => Element | null;
-
-export default UseActiveElement;
diff --git a/src/hooks/useActiveElementRole/index.native.ts b/src/hooks/useActiveElementRole/index.native.ts
new file mode 100644
index 000000000000..4278014f02a8
--- /dev/null
+++ b/src/hooks/useActiveElementRole/index.native.ts
@@ -0,0 +1,8 @@
+import type UseActiveElementRole from './types';
+
+/**
+ * Native doesn't have the DOM, so we just return null.
+ */
+const useActiveElementRole: UseActiveElementRole = () => null;
+
+export default useActiveElementRole;
diff --git a/src/hooks/useActiveElement/index.ts b/src/hooks/useActiveElementRole/index.ts
similarity index 59%
rename from src/hooks/useActiveElement/index.ts
rename to src/hooks/useActiveElementRole/index.ts
index 6026b4f5eb80..a98999105ac8 100644
--- a/src/hooks/useActiveElement/index.ts
+++ b/src/hooks/useActiveElementRole/index.ts
@@ -1,19 +1,19 @@
-import {useEffect, useState} from 'react';
-import type UseActiveElement from './types';
+import {useEffect, useRef} from 'react';
+import type UseActiveElementRole from './types';
/**
* Listens for the focusin and focusout events and sets the DOM activeElement to the state.
* On native, we just return null.
*/
-const useActiveElement: UseActiveElement = () => {
- const [active, setActive] = useState(document.activeElement);
+const useActiveElementRole: UseActiveElementRole = () => {
+ const activeRoleRef = useRef(document?.activeElement?.role);
const handleFocusIn = () => {
- setActive(document.activeElement);
+ activeRoleRef.current = document?.activeElement?.role;
};
const handleFocusOut = () => {
- setActive(null);
+ activeRoleRef.current = null;
};
useEffect(() => {
@@ -26,7 +26,7 @@ const useActiveElement: UseActiveElement = () => {
};
}, []);
- return active;
+ return activeRoleRef.current;
};
-export default useActiveElement;
+export default useActiveElementRole;
diff --git a/src/hooks/useActiveElementRole/types.ts b/src/hooks/useActiveElementRole/types.ts
new file mode 100644
index 000000000000..c31b8ab7ddbf
--- /dev/null
+++ b/src/hooks/useActiveElementRole/types.ts
@@ -0,0 +1,3 @@
+type UseActiveElementRole = () => string | null | undefined;
+
+export default UseActiveElementRole;
diff --git a/src/hooks/useDebouncedState.ts b/src/hooks/useDebouncedState.ts
new file mode 100644
index 000000000000..3677c85f3081
--- /dev/null
+++ b/src/hooks/useDebouncedState.ts
@@ -0,0 +1,35 @@
+import debounce from 'lodash/debounce';
+import {useEffect, useRef, useState} from 'react';
+import CONST from '@src/CONST';
+
+/**
+ * A React hook that provides a state and its debounced version.
+ *
+ * @param initialValue - The initial value of the state.
+ * @param delay - The debounce delay in milliseconds. Defaults to SEARCH_OPTION_LIST_DEBOUNCE_TIME = 300ms.
+ * @returns A tuple containing:
+ * - The current state value.
+ * - The debounced state value.
+ * - A function to set both the current and debounced state values.
+ *
+ * @template T The type of the state value.
+ *
+ * @example
+ * const [value, debouncedValue, setValue] = useDebouncedState("", 300);
+ */
+function useDebouncedState(initialValue: T, delay = CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME): [T, T, (value: T) => void] {
+ const [value, setValue] = useState(initialValue);
+ const [debouncedValue, setDebouncedValue] = useState(initialValue);
+ const debouncedSetDebouncedValue = useRef(debounce(setDebouncedValue, delay)).current;
+
+ useEffect(() => () => debouncedSetDebouncedValue.cancel(), [debouncedSetDebouncedValue]);
+
+ const handleSetValue = (newValue: T) => {
+ setValue(newValue);
+ debouncedSetDebouncedValue(newValue);
+ };
+
+ return [value, debouncedValue, handleSetValue];
+}
+
+export default useDebouncedState;
diff --git a/src/hooks/useKeyboardState.ts b/src/hooks/useKeyboardState.ts
index 439f626ddcdd..60ad3b8975b1 100644
--- a/src/hooks/useKeyboardState.ts
+++ b/src/hooks/useKeyboardState.ts
@@ -6,6 +6,6 @@ import {KeyboardStateContext} from '@components/withKeyboardState';
* Hook for getting current state of keyboard
* whether the keyboard is open
*/
-export default function useKeyboardState(): KeyboardStateContextValue | null {
+export default function useKeyboardState(): KeyboardStateContextValue {
return useContext(KeyboardStateContext);
}
diff --git a/src/languages/en.ts b/src/languages/en.ts
index 0b8983a8361b..c57b1ce310b5 100755
--- a/src/languages/en.ts
+++ b/src/languages/en.ts
@@ -73,6 +73,7 @@ import type {
UntilTimeParams,
UpdatedTheDistanceParams,
UpdatedTheRequestParams,
+ UsePlusButtonParams,
UserIsAlreadyMemberParams,
ViolationsAutoReportedRejectedExpenseParams,
ViolationsCashExpenseWithNoReceiptParams,
@@ -481,7 +482,12 @@ export default {
chatWithAccountManager: 'Chat with your account manager here',
sayHello: 'Say hello!',
welcomeToRoom: ({roomName}: WelcomeToRoomParams) => `Welcome to ${roomName}!`,
- usePlusButton: '\n\nYou can also use the + button to send money, request money, or assign a task!',
+ usePlusButton: ({additionalText}: UsePlusButtonParams) => `\n\nYou can also use the + button to ${additionalText}, or assign a task!`,
+ iouTypes: {
+ send: 'send money',
+ split: 'split a bill',
+ request: 'request money',
+ },
},
reportAction: {
asCopilot: 'as copilot for',
@@ -635,6 +641,7 @@ export default {
genericDeleteFailureMessage: 'Unexpected error deleting the money request, please try again later',
genericEditFailureMessage: 'Unexpected error editing the money request, please try again later',
genericSmartscanFailureMessage: 'Transaction is missing fields',
+ duplicateWaypointsErrorMessage: 'Please remove duplicate waypoints',
atLeastTwoDifferentWaypoints: 'Please enter at least two different addresses',
splitBillMultipleParticipantsErrorMessage: 'Split bill is only allowed between a single workspace or individual users. Please update your selection.',
invalidMerchant: 'Please enter a correct merchant.',
@@ -1557,7 +1564,7 @@ export default {
noVBACopy: 'Connect a bank account to issue Expensify Cards to your workspace members, and access these incredible benefits and more:',
VBANoECardCopy: 'Add a work email address to issue unlimited Expensify Cards for your workspace members, as well as all of these incredible benefits:',
VBAWithECardCopy: 'Access these incredible benefits and more:',
- benefit1: 'Up to 4% cash back',
+ benefit1: 'Up to 2% cash back',
benefit2: 'Digital and physical cards',
benefit3: 'No personal liability',
benefit4: 'Customizable limits',
@@ -2029,30 +2036,30 @@ export default {
buttonText1: 'Start a chat, ',
buttonText2: `get $${CONST.REFERRAL_PROGRAM.REVENUE}.`,
header: `Start a chat, get $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- body: `Get paid to talk to your friends! Start a chat with a new Expensify account and get $${CONST.REFERRAL_PROGRAM.REVENUE} if they become an Expensify customer.`,
+ body: `Get paid to talk to your friends! Start a chat with a new Expensify account and get $${CONST.REFERRAL_PROGRAM.REVENUE} when they become a customer.`,
},
[CONST.REFERRAL_PROGRAM.CONTENT_TYPES.MONEY_REQUEST]: {
buttonText1: 'Request money, ',
buttonText2: `get $${CONST.REFERRAL_PROGRAM.REVENUE}.`,
header: `Request money, get $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- body: `It pays to get paid! Request money from a new Expensify account and get $${CONST.REFERRAL_PROGRAM.REVENUE} if they become an Expensify customer.`,
+ body: `It pays to get paid! Request money from a new Expensify account and get $${CONST.REFERRAL_PROGRAM.REVENUE} when they become a customer.`,
},
[CONST.REFERRAL_PROGRAM.CONTENT_TYPES.SEND_MONEY]: {
buttonText1: 'Send money, ',
buttonText2: `get $${CONST.REFERRAL_PROGRAM.REVENUE}.`,
header: `Send money, get $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- body: `You gotta send money to make money! Send money to a new Expensify account and get $${CONST.REFERRAL_PROGRAM.REVENUE} if they become an Expensify customer.`,
+ body: `You gotta send money to make money! Send money to a new Expensify account and get $${CONST.REFERRAL_PROGRAM.REVENUE} when they become a customer.`,
},
[CONST.REFERRAL_PROGRAM.CONTENT_TYPES.REFER_FRIEND]: {
buttonText1: 'Invite a friend, ',
buttonText2: `get $${CONST.REFERRAL_PROGRAM.REVENUE}.`,
header: `Get $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- body: `Start a chat, send or request money, split a bill, or share your invite link below with a new Expensify account and get $${CONST.REFERRAL_PROGRAM.REVENUE} if they become an Expensify customer. Learn more ways to earn below.`,
+ body: `Be the first to chat, send or request money, split a bill, or share your invite link with a friend, and you'll get $${CONST.REFERRAL_PROGRAM.REVENUE} when they become a customer. You can post your invite link on social media, too!`,
},
[CONST.REFERRAL_PROGRAM.CONTENT_TYPES.SHARE_CODE]: {
buttonText1: `Get $${CONST.REFERRAL_PROGRAM.REVENUE}`,
header: `Get $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- body: `Start a chat, send or request money, split a bill, or share your invite link below with a new Expensify account and get $${CONST.REFERRAL_PROGRAM.REVENUE} if they become an Expensify customer. Learn more ways to earn below.`,
+ body: `Be the first to chat, send or request money, split a bill, or share your invite link with a friend, and you'll get $${CONST.REFERRAL_PROGRAM.REVENUE} when they become a customer. You can post your invite link on social media, too!`,
},
copyReferralLink: 'Copy invite link',
},
diff --git a/src/languages/es.ts b/src/languages/es.ts
index a1afde53482b..8969ce91a9a5 100644
--- a/src/languages/es.ts
+++ b/src/languages/es.ts
@@ -72,6 +72,7 @@ import type {
UntilTimeParams,
UpdatedTheDistanceParams,
UpdatedTheRequestParams,
+ UsePlusButtonParams,
UserIsAlreadyMemberParams,
ViolationsAutoReportedRejectedExpenseParams,
ViolationsCashExpenseWithNoReceiptParams,
@@ -474,7 +475,12 @@ export default {
chatWithAccountManager: 'Chatea con tu gestor de cuenta aquĂ',
sayHello: '¡Saluda!',
welcomeToRoom: ({roomName}: WelcomeToRoomParams) => `¡Bienvenido a ${roomName}!`,
- usePlusButton: '\n\n¡También puedes usar el botón + de abajo para enviar dinero, pedir dinero, o asignar una tarea!',
+ usePlusButton: ({additionalText}: UsePlusButtonParams) => `\n\n¡También puedes usar el botón + de abajo para ${additionalText}, o asignar una tarea!`,
+ iouTypes: {
+ send: 'enviar dinero',
+ split: 'dividir una factura',
+ request: 'pedir dinero',
+ },
},
reportAction: {
asCopilot: 'como copiloto de',
@@ -630,6 +636,7 @@ export default {
genericDeleteFailureMessage: 'Error inesperado eliminando la solicitud de dinero. Por favor, inténtalo más tarde',
genericEditFailureMessage: 'Error inesperado al guardar la solicitud de dinero. Por favor, inténtalo más tarde',
genericSmartscanFailureMessage: 'La transacciĂłn tiene campos vacĂos',
+ duplicateWaypointsErrorMessage: 'Por favor elimina los puntos de ruta duplicados',
atLeastTwoDifferentWaypoints: 'Por favor introduce al menos dos direcciones diferentes',
splitBillMultipleParticipantsErrorMessage: 'Solo puedes dividir una cuenta entre un Ăşnico espacio de trabajo o con usuarios individuales. Por favor actualiza tu selecciĂłn.',
invalidMerchant: 'Por favor ingrese un comerciante correcto.',
@@ -1581,7 +1588,7 @@ export default {
VBANoECardCopy:
'Añade tu correo electrĂłnico de trabajo para emitir Tarjetas Expensify ilimitadas para los miembros de tu espacio de trabajo y acceder a todas estas increĂbles ventajas:',
VBAWithECardCopy: 'Acceda a estos increĂbles beneficios y más:',
- benefit1: 'Hasta un 4% de devoluciĂłn en tus gastos',
+ benefit1: 'Hasta un 2% de devoluciĂłn en tus gastos',
benefit2: 'Tarjetas digitales y fĂsicas',
benefit3: 'Sin responsabilidad personal',
benefit4: 'LĂmites personalizables',
@@ -1771,7 +1778,7 @@ export default {
messages: {
created: ({title}: TaskCreatedActionParams) => `tarea para ${title}`,
completed: 'marcada como completa',
- canceled: 'tarea eliminado',
+ canceled: 'tarea eliminada',
reopened: 'marcada como incompleta',
error: 'No tiene permiso para realizar la acciĂłn solicitada.',
},
@@ -2409,7 +2416,7 @@ export default {
deletedMessage: '[Mensaje eliminado]',
deletedRequest: '[Pedido eliminado]',
reversedTransaction: '[TransacciĂłn anulada]',
- deletedTask: '[Tarea eliminado]',
+ deletedTask: '[Tarea eliminada]',
hiddenMessage: '[Mensaje oculto]',
},
threads: {
@@ -2516,30 +2523,30 @@ export default {
buttonText1: 'Inicia un chat y ',
buttonText2: `recibe $${CONST.REFERRAL_PROGRAM.REVENUE}`,
header: `Inicia un chat y recibe $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- body: `¡Gana dinero por hablar con tus amigos! Inicia un chat con una cuenta nueva de Expensify y obtiene $${CONST.REFERRAL_PROGRAM.REVENUE} si se convierten en clientes de Expensify.`,
+ body: `¡Gana dinero por hablar con tus amigos! Inicia un chat con una cuenta nueva de Expensify y recibe $${CONST.REFERRAL_PROGRAM.REVENUE} cuando se conviertan en clientes.`,
},
[CONST.REFERRAL_PROGRAM.CONTENT_TYPES.MONEY_REQUEST]: {
buttonText1: 'Pide dinero, ',
buttonText2: `recibe $${CONST.REFERRAL_PROGRAM.REVENUE}`,
header: `Pide dinero y recibe $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- body: `¡Vale la pena cobrar! Pide dinero a una cuenta nueva de Expensify y obtiene $${CONST.REFERRAL_PROGRAM.REVENUE} si se convierten en clientes de Expensify.`,
+ body: `¡Vale la pena cobrar! Pide dinero a una cuenta nueva de Expensify y recibe $${CONST.REFERRAL_PROGRAM.REVENUE} cuando se conviertan en clientes.`,
},
[CONST.REFERRAL_PROGRAM.CONTENT_TYPES.SEND_MONEY]: {
buttonText1: 'EnvĂa dinero, ',
buttonText2: `recibe $${CONST.REFERRAL_PROGRAM.REVENUE}`,
header: `EnvĂa dinero y recibe $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- body: `¡Hay que enviar dinero para ganar dinero! EnvĂa dinero a una cuenta nueva de Expensify y obtiene $${CONST.REFERRAL_PROGRAM.REVENUE} si se convierten en clientes de Expensify.`,
+ body: `¡Hay que enviar dinero para ganar dinero! EnvĂa dinero a una cuenta nueva de Expensify y recibe $${CONST.REFERRAL_PROGRAM.REVENUE} cuando se conviertan en clientes.`,
},
[CONST.REFERRAL_PROGRAM.CONTENT_TYPES.REFER_FRIEND]: {
buttonText1: 'Invita a un amigo y ',
buttonText2: `recibe $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- header: `Invita a un amigo y obtiene $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- body: `SĂ© el primero en invitar a un amigo (o a cualquier otra persona) a Expensify y obtiene $${CONST.REFERRAL_PROGRAM.REVENUE} si se convierte en cliente de Expensify. Comparte tu enlace de invitaciĂłn por SMS, email o publĂcalo en las redes sociales.`,
+ header: `Recibe $${CONST.REFERRAL_PROGRAM.REVENUE}`,
+ body: `Sé el primero en chatear, enviar o pedir dinero, dividir una factura o compartir tu enlace de invitación con un amigo, y recibirás $${CONST.REFERRAL_PROGRAM.REVENUE} cuando se convierta en cliente. También puedes publicar tu enlace de invitación en las redes sociales.`,
},
[CONST.REFERRAL_PROGRAM.CONTENT_TYPES.SHARE_CODE]: {
buttonText1: `Recibe $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- header: `Invita a un amigo y obtiene $${CONST.REFERRAL_PROGRAM.REVENUE}`,
- body: `SĂ© el primero en invitar a un amigo (o a cualquier otra persona) a Expensify y obtiene $${CONST.REFERRAL_PROGRAM.REVENUE} si se convierte en cliente de Expensify. Comparte tu enlace de invitaciĂłn por SMS, email o publĂcalo en las redes sociales.`,
+ header: `Recibe $${CONST.REFERRAL_PROGRAM.REVENUE}`,
+ body: `Sé el primero en chatear, enviar o pedir dinero, dividir una factura o compartir tu enlace de invitación con un amigo, y recibirás $${CONST.REFERRAL_PROGRAM.REVENUE} cuando se convierta en cliente. También puedes publicar tu enlace de invitación en las redes sociales.`,
},
copyReferralLink: 'Copiar enlace de invitaciĂłn',
},
diff --git a/src/languages/types.ts b/src/languages/types.ts
index 5b6e56a38689..3185b7a8f6f1 100644
--- a/src/languages/types.ts
+++ b/src/languages/types.ts
@@ -74,6 +74,10 @@ type WelcomeToRoomParams = {
roomName: string;
};
+type UsePlusButtonParams = {
+ additionalText: string;
+};
+
type ReportArchiveReasonsClosedParams = {
displayName: string;
};
@@ -376,6 +380,7 @@ export type {
ViolationsTaxOutOfPolicyParams,
WaitingOnBankAccountParams,
WalletProgramParams,
+ UsePlusButtonParams,
WeSentYouMagicSignInLinkParams,
WelcomeEnterMagicCodeParams,
WelcomeNoteParams,
diff --git a/src/libs/API.ts b/src/libs/API.ts
index d5cfd56cd4af..4305469eafd5 100644
--- a/src/libs/API.ts
+++ b/src/libs/API.ts
@@ -27,7 +27,7 @@ Request.use(Middleware.Reauthentication);
// If an optimistic ID is not used by the server, this will update the remaining serialized requests using that optimistic ID to use the correct ID instead.
Request.use(Middleware.HandleUnusedOptimisticID);
-// SaveResponseInOnyx - Merges either the successData or failureData into Onyx depending on if the call was successful or not. This needs to be the LAST middleware we use, don't add any
+// SaveResponseInOnyx - Merges either the successData or failureData (or finallyData, if included in place of the former two values) into Onyx depending on if the call was successful or not. This needs to be the LAST middleware we use, don't add any
// middlewares after this, because the SequentialQueue depends on the result of this middleware to pause the queue (if needed) to bring the app to an up-to-date state.
Request.use(Middleware.SaveResponseInOnyx);
@@ -35,12 +35,13 @@ type OnyxData = {
optimisticData?: OnyxUpdate[];
successData?: OnyxUpdate[];
failureData?: OnyxUpdate[];
+ finallyData?: OnyxUpdate[];
};
type ApiRequestType = ValueOf;
/**
- * All calls to API.write() will be persisted to disk as JSON with the params, successData, and failureData.
+ * All calls to API.write() will be persisted to disk as JSON with the params, successData, and failureData (or finallyData, if included in place of the former two values).
* This is so that if the network is unavailable or the app is closed, we can send the WRITE request later.
*
* @param command - Name of API command to call.
@@ -51,6 +52,7 @@ type ApiRequestType = ValueOf;
* @param [onyxData.optimisticData] - Onyx instructions that will be passed to Onyx.update() before the request is made.
* @param [onyxData.successData] - Onyx instructions that will be passed to Onyx.update() when the response has jsonCode === 200.
* @param [onyxData.failureData] - Onyx instructions that will be passed to Onyx.update() when the response has jsonCode !== 200.
+ * @param [onyxData.finallyData] - Onyx instructions that will be passed to Onyx.update() when the response has jsonCode === 200 or jsonCode !== 200.
*/
function write(command: string, apiCommandParameters: Record = {}, onyxData: OnyxData = {}) {
Log.info('Called API write', false, {command, ...apiCommandParameters});
@@ -105,6 +107,7 @@ function write(command: string, apiCommandParameters: Record =
* @param [onyxData.optimisticData] - Onyx instructions that will be passed to Onyx.update() before the request is made.
* @param [onyxData.successData] - Onyx instructions that will be passed to Onyx.update() when the response has jsonCode === 200.
* @param [onyxData.failureData] - Onyx instructions that will be passed to Onyx.update() when the response has jsonCode !== 200.
+ * @param [onyxData.finallyData] - Onyx instructions that will be passed to Onyx.update() when the response has jsonCode === 200 or jsonCode !== 200.
* @param [apiRequestType] - Can be either 'read', 'write', or 'makeRequestWithSideEffects'. We use this to either return the chained
* response back to the caller or to trigger reconnection callbacks when re-authentication is required.
* @returns
@@ -152,6 +155,7 @@ function makeRequestWithSideEffects(
* @param [onyxData.optimisticData] - Onyx instructions that will be passed to Onyx.update() before the request is made.
* @param [onyxData.successData] - Onyx instructions that will be passed to Onyx.update() when the response has jsonCode === 200.
* @param [onyxData.failureData] - Onyx instructions that will be passed to Onyx.update() when the response has jsonCode !== 200.
+ * @param [onyxData.finallyData] - Onyx instructions that will be passed to Onyx.update() when the response has jsonCode === 200 or jsonCode !== 200.
*/
function read(command: string, apiCommandParameters: Record, onyxData: OnyxData = {}) {
// Ensure all write requests on the sequential queue have finished responding before running read requests.
diff --git a/src/libs/BrickRoadsUtils.ts b/src/libs/BrickRoadsUtils.ts
new file mode 100644
index 000000000000..db7cc40a7940
--- /dev/null
+++ b/src/libs/BrickRoadsUtils.ts
@@ -0,0 +1,74 @@
+import type {OnyxCollection} from 'react-native-onyx';
+import Onyx from 'react-native-onyx';
+import type {ValueOf} from 'type-fest';
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import type {Report} from '@src/types/onyx';
+import * as OptionsListUtils from './OptionsListUtils';
+import * as ReportActionsUtils from './ReportActionsUtils';
+import * as ReportUtils from './ReportUtils';
+
+let allReports: OnyxCollection;
+
+type BrickRoad = ValueOf | undefined;
+
+Onyx.connect({
+ key: ONYXKEYS.COLLECTION.REPORT,
+ waitForCollectionCallback: true,
+ callback: (value) => (allReports = value),
+});
+
+/**
+ * @param report
+ * @returns BrickRoad for the policy passed as a param
+ */
+const getBrickRoadForPolicy = (report: Report): BrickRoad => {
+ const reportActions = ReportActionsUtils.getAllReportActions(report.reportID);
+ const reportErrors = OptionsListUtils.getAllReportErrors(report, reportActions);
+ const doesReportContainErrors = Object.keys(reportErrors ?? {}).length !== 0 ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined;
+ if (doesReportContainErrors) {
+ return CONST.BRICK_ROAD.RBR;
+ }
+
+ // To determine if the report requires attention from the current user, we need to load the parent report action
+ let itemParentReportAction = {};
+ if (report.parentReportID) {
+ const itemParentReportActions = ReportActionsUtils.getAllReportActions(report.parentReportID);
+ itemParentReportAction = report.parentReportActionID ? itemParentReportActions[report.parentReportActionID] : {};
+ }
+ const reportOption = {...report, isUnread: ReportUtils.isUnread(report), isUnreadWithMention: ReportUtils.isUnreadWithMention(report)};
+ const shouldShowGreenDotIndicator = ReportUtils.requiresAttentionFromCurrentUser(reportOption, itemParentReportAction);
+ return shouldShowGreenDotIndicator ? CONST.BRICK_ROAD.GBR : undefined;
+};
+
+/**
+ * @returns a map where the keys are policyIDs and the values are BrickRoads for each policy
+ */
+function getWorkspacesBrickRoads(): Record {
+ if (!allReports) {
+ return {};
+ }
+
+ // The key in this map is the workspace id
+ const workspacesBrickRoadsMap: Record = {};
+
+ Object.keys(allReports).forEach((report) => {
+ const policyID = allReports?.[report]?.policyID;
+ const policyReport = allReports ? allReports[report] : null;
+ if (!policyID || !policyReport || workspacesBrickRoadsMap[policyID] === CONST.BRICK_ROAD.RBR) {
+ return;
+ }
+ const workspaceBrickRoad = getBrickRoadForPolicy(policyReport);
+
+ if (!workspaceBrickRoad && !!workspacesBrickRoadsMap[policyID]) {
+ return;
+ }
+
+ workspacesBrickRoadsMap[policyID] = workspaceBrickRoad;
+ });
+
+ return workspacesBrickRoadsMap;
+}
+
+export {getBrickRoadForPolicy, getWorkspacesBrickRoads};
+export type {BrickRoad};
diff --git a/src/libs/EmojiUtils.ts b/src/libs/EmojiUtils.ts
index 02d1b34c69c1..e34fa0b90fc6 100644
--- a/src/libs/EmojiUtils.ts
+++ b/src/libs/EmojiUtils.ts
@@ -306,7 +306,7 @@ function getAddedEmojis(currentEmojis: Emoji[], formerEmojis: Emoji[]): Emoji[]
* Replace any emoji name in a text with the emoji icon.
* If we're on mobile, we also add a space after the emoji granted there's no text after it.
*/
-function replaceEmojis(text: string, preferredSkinTone = CONST.EMOJI_DEFAULT_SKIN_TONE, lang: 'en' | 'es' = CONST.LOCALES.DEFAULT): ReplacedEmoji {
+function replaceEmojis(text: string, preferredSkinTone: number = CONST.EMOJI_DEFAULT_SKIN_TONE, lang: Locale = CONST.LOCALES.DEFAULT): ReplacedEmoji {
// emojisTrie is importing the emoji JSON file on the app starting and we want to avoid it
const emojisTrie = require('./EmojiTrie').default;
@@ -370,7 +370,7 @@ function replaceEmojis(text: string, preferredSkinTone = CONST.EMOJI_DEFAULT_SKI
/**
* Find all emojis in a text and replace them with their code.
*/
-function replaceAndExtractEmojis(text: string, preferredSkinTone = CONST.EMOJI_DEFAULT_SKIN_TONE, lang = CONST.LOCALES.DEFAULT): ReplacedEmoji {
+function replaceAndExtractEmojis(text: string, preferredSkinTone: number = CONST.EMOJI_DEFAULT_SKIN_TONE, lang: Locale = CONST.LOCALES.DEFAULT): ReplacedEmoji {
const {text: convertedText = '', emojis = [], cursorPosition} = replaceEmojis(text, preferredSkinTone, lang);
return {
diff --git a/src/libs/GroupChatUtils.ts b/src/libs/GroupChatUtils.ts
index ba14bc9c9c3d..26b3665ca4ce 100644
--- a/src/libs/GroupChatUtils.ts
+++ b/src/libs/GroupChatUtils.ts
@@ -1,26 +1,18 @@
-import type {OnyxEntry} from 'react-native-onyx';
-import Onyx from 'react-native-onyx';
-import ONYXKEYS from '@src/ONYXKEYS';
-import type {PersonalDetailsList, Report} from '@src/types/onyx';
-import * as OptionsListUtils from './OptionsListUtils';
+import type {Report} from '@src/types/onyx';
import * as ReportUtils from './ReportUtils';
-let allPersonalDetails: OnyxEntry = {};
-Onyx.connect({
- key: ONYXKEYS.PERSONAL_DETAILS_LIST,
- callback: (val) => (allPersonalDetails = val),
-});
-
/**
* Returns the report name if the report is a group chat
*/
function getGroupChatName(report: Report): string | undefined {
const participants = report.participantAccountIDs ?? [];
const isMultipleParticipantReport = participants.length > 1;
- const participantPersonalDetails = OptionsListUtils.getPersonalDetailsForAccountIDs(participants, allPersonalDetails ?? {});
- // @ts-expect-error Error will gone when OptionsListUtils will be migrated to Typescript
- const displayNamesWithTooltips = ReportUtils.getDisplayNamesWithTooltips(participantPersonalDetails, isMultipleParticipantReport);
- return ReportUtils.getDisplayNamesStringFromTooltips(displayNamesWithTooltips);
+
+ return participants
+ .map((participant) => ReportUtils.getDisplayNameForParticipant(participant, isMultipleParticipantReport))
+ .sort((first, second) => first?.localeCompare(second ?? '') ?? 0)
+ .filter(Boolean)
+ .join(', ');
}
export {
diff --git a/src/libs/IOUUtils.ts b/src/libs/IOUUtils.ts
index 09cdfd15cbba..11dd0f5badda 100644
--- a/src/libs/IOUUtils.ts
+++ b/src/libs/IOUUtils.ts
@@ -3,6 +3,7 @@ import type {ValueOf} from 'type-fest';
import CONST from '@src/CONST';
import ROUTES from '@src/ROUTES';
import type {Report, Transaction} from '@src/types/onyx';
+import * as IOU from './actions/IOU';
import * as CurrencyUtils from './CurrencyUtils';
import * as FileUtils from './fileDownload/FileUtils';
import Navigation from './Navigation/Navigation';
@@ -38,7 +39,14 @@ function navigateToStartStepIfScanFileCannotBeRead(
return;
}
- const onFailure = () => navigateToStartMoneyRequestStep(requestType, iouType, transactionID, reportID);
+ const onFailure = () => {
+ IOU.setMoneyRequestReceipt(transactionID, '', '', true);
+ if (requestType === CONST.IOU.REQUEST_TYPE.MANUAL) {
+ Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_SCAN.getRoute(CONST.IOU.ACTION.CREATE, iouType, transactionID, reportID, Navigation.getActiveRouteWithoutParams()));
+ return;
+ }
+ navigateToStartMoneyRequestStep(requestType, iouType, transactionID, reportID);
+ };
FileUtils.readFileAsync(receiptPath, receiptFilename, onSuccess, onFailure);
}
@@ -82,19 +90,20 @@ function updateIOUOwnerAndTotal(iouReport: OnyxEntry, actorAccountID: nu
// Make a copy so we don't mutate the original object
const iouReportUpdate: Report = {...iouReport};
- if (iouReportUpdate.total) {
- if (actorAccountID === iouReport.ownerAccountID) {
- iouReportUpdate.total += isDeleting ? -amount : amount;
- } else {
- iouReportUpdate.total += isDeleting ? amount : -amount;
- }
+ // Let us ensure a valid value before updating the total amount.
+ iouReportUpdate.total = iouReportUpdate.total ?? 0;
- if (iouReportUpdate.total < 0) {
- // The total sign has changed and hence we need to flip the manager and owner of the report.
- iouReportUpdate.ownerAccountID = iouReport.managerID;
- iouReportUpdate.managerID = iouReport.ownerAccountID;
- iouReportUpdate.total = -iouReportUpdate.total;
- }
+ if (actorAccountID === iouReport.ownerAccountID) {
+ iouReportUpdate.total += isDeleting ? -amount : amount;
+ } else {
+ iouReportUpdate.total += isDeleting ? amount : -amount;
+ }
+
+ if (iouReportUpdate.total < 0) {
+ // The total sign has changed and hence we need to flip the manager and owner of the report.
+ iouReportUpdate.ownerAccountID = iouReport.managerID;
+ iouReportUpdate.managerID = iouReport.ownerAccountID;
+ iouReportUpdate.total = -iouReportUpdate.total;
}
return iouReportUpdate;
diff --git a/src/libs/IntlPolyfill/index.native.ts b/src/libs/IntlPolyfill/index.native.ts
index 0819479b50ec..ca1c8f4c250e 100644
--- a/src/libs/IntlPolyfill/index.native.ts
+++ b/src/libs/IntlPolyfill/index.native.ts
@@ -1,3 +1,4 @@
+import polyfillDateTimeFormat from './polyfillDateTimeFormat';
import polyfillListFormat from './polyfillListFormat';
import polyfillNumberFormat from './polyfillNumberFormat';
import type IntlPolyfill from './types';
@@ -10,8 +11,8 @@ const intlPolyfill: IntlPolyfill = () => {
require('@formatjs/intl-getcanonicallocales/polyfill');
require('@formatjs/intl-locale/polyfill');
require('@formatjs/intl-pluralrules/polyfill');
- require('@formatjs/intl-datetimeformat');
polyfillNumberFormat();
+ polyfillDateTimeFormat();
polyfillListFormat();
};
diff --git a/src/libs/IntlPolyfill/index.ts b/src/libs/IntlPolyfill/index.ts
index 42664477409f..4f05fdbefd51 100644
--- a/src/libs/IntlPolyfill/index.ts
+++ b/src/libs/IntlPolyfill/index.ts
@@ -1,3 +1,4 @@
+import polyfillDateTimeFormat from './polyfillDateTimeFormat';
import polyfillNumberFormat from './polyfillNumberFormat';
import type IntlPolyfill from './types';
@@ -6,8 +7,7 @@ import type IntlPolyfill from './types';
* This ensures that the currency data is consistent across platforms and browsers.
*/
const intlPolyfill: IntlPolyfill = () => {
- // Just need to polyfill Intl.NumberFormat for web based platforms
polyfillNumberFormat();
- require('@formatjs/intl-datetimeformat');
+ polyfillDateTimeFormat();
};
export default intlPolyfill;
diff --git a/src/libs/IntlPolyfill/polyfillDateTimeFormat.ts b/src/libs/IntlPolyfill/polyfillDateTimeFormat.ts
new file mode 100644
index 000000000000..13eaaabbd8f4
--- /dev/null
+++ b/src/libs/IntlPolyfill/polyfillDateTimeFormat.ts
@@ -0,0 +1,42 @@
+import type {DateTimeFormatConstructor} from '@formatjs/intl-datetimeformat';
+import DateUtils from '@libs/DateUtils';
+
+/* eslint-disable @typescript-eslint/naming-convention */
+const tzLinks: Record = {
+ 'Africa/Abidjan': 'Africa/Accra',
+ CET: 'Europe/Paris',
+ CST6CDT: 'America/Chicago',
+ EET: 'Europe/Sofia',
+ EST: 'America/Cancun',
+ EST5EDT: 'America/New_York',
+ 'Etc/GMT': 'UTC',
+ 'Etc/UTC': 'UTC',
+ Factory: 'UTC',
+ GMT: 'UTC',
+ HST: 'Pacific/Honolulu',
+ MET: 'Europe/Paris',
+ MST: 'America/Phoenix',
+ MST7MDT: 'America/Denver',
+ PST8PDT: 'America/Los_Angeles',
+ WET: 'Europe/Lisbon',
+};
+/* eslint-enable @typescript-eslint/naming-convention */
+
+export default function () {
+ // Because JS Engines do not expose default timezone, the polyfill cannot detect local timezone that a browser is in.
+ // We must manually do this by getting the local timezone before adding polyfill.
+ let currentTimezone = DateUtils.getCurrentTimezone().selected as string;
+ if (currentTimezone in tzLinks) {
+ currentTimezone = tzLinks[currentTimezone];
+ }
+
+ require('@formatjs/intl-datetimeformat/polyfill-force');
+ require('@formatjs/intl-datetimeformat/locale-data/en');
+ require('@formatjs/intl-datetimeformat/locale-data/es');
+ require('@formatjs/intl-datetimeformat/add-all-tz');
+
+ if ('__setDefaultTimeZone' in Intl.DateTimeFormat) {
+ // eslint-disable-next-line no-underscore-dangle
+ (Intl.DateTimeFormat as DateTimeFormatConstructor).__setDefaultTimeZone(currentTimezone);
+ }
+}
diff --git a/src/libs/LocalePhoneNumber.ts b/src/libs/LocalePhoneNumber.ts
index e50f3be87c84..933aa7937560 100644
--- a/src/libs/LocalePhoneNumber.ts
+++ b/src/libs/LocalePhoneNumber.ts
@@ -1,7 +1,7 @@
-import {parsePhoneNumber} from 'awesome-phonenumber';
import Str from 'expensify-common/lib/str';
import Onyx from 'react-native-onyx';
import ONYXKEYS from '@src/ONYXKEYS';
+import {parsePhoneNumber} from './PhoneNumber';
let countryCodeByIP: number;
Onyx.connect({
diff --git a/src/libs/LoginUtils.ts b/src/libs/LoginUtils.ts
index 742f9bfe16ce..dca84b9b11e0 100644
--- a/src/libs/LoginUtils.ts
+++ b/src/libs/LoginUtils.ts
@@ -1,9 +1,9 @@
-import {parsePhoneNumber} from 'awesome-phonenumber';
import {PUBLIC_DOMAINS} from 'expensify-common/lib/CONST';
import Str from 'expensify-common/lib/str';
import Onyx from 'react-native-onyx';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
+import {parsePhoneNumber} from './PhoneNumber';
let countryCodeByIP: number;
Onyx.connect({
diff --git a/src/libs/Middleware/SaveResponseInOnyx.ts b/src/libs/Middleware/SaveResponseInOnyx.ts
index 9ed93c4ce393..a9182745098b 100644
--- a/src/libs/Middleware/SaveResponseInOnyx.ts
+++ b/src/libs/Middleware/SaveResponseInOnyx.ts
@@ -12,9 +12,9 @@ const SaveResponseInOnyx: Middleware = (requestResponse, request) =>
requestResponse.then((response = {}) => {
const onyxUpdates = response?.onyxData ?? [];
- // Sometimes we call requests that are successfull but they don't have any response or any success/failure data to set. Let's return early since
+ // Sometimes we call requests that are successfull but they don't have any response or any success/failure/finally data to set. Let's return early since
// we don't need to store anything here.
- if (!onyxUpdates && !request.successData && !request.failureData) {
+ if (!onyxUpdates && !request.successData && !request.failureData && !request.finallyData) {
return Promise.resolve(response);
}
diff --git a/src/libs/ModifiedExpenseMessage.ts b/src/libs/ModifiedExpenseMessage.ts
index 600cfb48a1c1..61e7ce04ab71 100644
--- a/src/libs/ModifiedExpenseMessage.ts
+++ b/src/libs/ModifiedExpenseMessage.ts
@@ -38,8 +38,10 @@ function buildMessageFragmentForValue(
const newValueToDisplay = valueInQuotes ? `"${newValue}"` : newValue;
const oldValueToDisplay = valueInQuotes ? `"${oldValue}"` : oldValue;
const displayValueName = shouldConvertToLowercase ? valueName.toLowerCase() : valueName;
+ const isOldValuePartialMerchant = valueName === Localize.translateLocal('common.merchant') && oldValue === CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT;
- if (!oldValue) {
+ // In case of a partial merchant value, we want to avoid user seeing the "(none)" value in the message.
+ if (!oldValue || isOldValuePartialMerchant) {
const fragment = Localize.translateLocal('iou.setTheRequest', {valueName: displayValueName, newValueToDisplay});
setFragments.push(fragment);
} else if (!newValue) {
diff --git a/src/libs/Navigation/Navigation.ts b/src/libs/Navigation/Navigation.ts
index cc77cd1c4908..91285821fe9f 100644
--- a/src/libs/Navigation/Navigation.ts
+++ b/src/libs/Navigation/Navigation.ts
@@ -73,7 +73,7 @@ function getActiveRouteIndex(stateOrRoute: StateOrRoute, index?: number): number
* @param path - Path that you are looking for.
* @return - Returns distance to path or -1 if the path is not found in root navigator.
*/
-function getDistanceFromPathInRootNavigator(path: string): number {
+function getDistanceFromPathInRootNavigator(path?: string): number {
let currentState = navigationRef.getRootState();
for (let index = 0; index < 5; index++) {
@@ -125,7 +125,8 @@ function isActiveRoute(routePath: Route): boolean {
let activeRoute = getActiveRoute();
activeRoute = activeRoute.startsWith('/') ? activeRoute.substring(1) : activeRoute;
- return activeRoute === routePath;
+ // We remove redundant (consecutive and trailing) slashes from path before matching
+ return activeRoute === routePath.replace(CONST.REGEX.ROUTES.REDUNDANT_SLASHES, (match, p1) => (p1 ? '/' : ''));
}
/**
@@ -148,7 +149,7 @@ function navigate(route: Route = ROUTES.HOME, type?: string) {
* @param shouldEnforceFallback - Enforces navigation to fallback route
* @param shouldPopToTop - Should we navigate to LHN on back press
*/
-function goBack(fallbackRoute: Route, shouldEnforceFallback = false, shouldPopToTop = false) {
+function goBack(fallbackRoute?: Route, shouldEnforceFallback = false, shouldPopToTop = false) {
if (!canNavigate('goBack')) {
return;
}
diff --git a/src/libs/Navigation/OnyxTabNavigator.tsx b/src/libs/Navigation/OnyxTabNavigator.tsx
index 624aaec72bda..b5466a9bbc2f 100644
--- a/src/libs/Navigation/OnyxTabNavigator.tsx
+++ b/src/libs/Navigation/OnyxTabNavigator.tsx
@@ -7,6 +7,7 @@ import type {OnyxEntry} from 'react-native-onyx/lib/types';
import Tab from '@userActions/Tab';
import ONYXKEYS from '@src/ONYXKEYS';
import type ChildrenProps from '@src/types/utils/ChildrenProps';
+import {defaultScreenOptions} from './OnyxTabNavigatorConfig';
type OnyxTabNavigatorOnyxProps = {
selectedTab: OnyxEntry;
@@ -51,6 +52,7 @@ function OnyxTabNavigator({id, selectedTab = '', children, onTabSelected = () =>
},
...(screenListeners ?? {}),
}}
+ screenOptions={defaultScreenOptions}
>
{children}
diff --git a/src/libs/Navigation/OnyxTabNavigatorConfig/index.ts b/src/libs/Navigation/OnyxTabNavigatorConfig/index.ts
new file mode 100644
index 000000000000..8f61e38ca531
--- /dev/null
+++ b/src/libs/Navigation/OnyxTabNavigatorConfig/index.ts
@@ -0,0 +1,8 @@
+const defaultScreenOptions = {
+ animationEnabled: true,
+} as const;
+
+export {
+ // eslint-disable-next-line import/prefer-default-export
+ defaultScreenOptions,
+};
diff --git a/src/libs/Navigation/OnyxTabNavigatorConfig/index.website.ts b/src/libs/Navigation/OnyxTabNavigatorConfig/index.website.ts
new file mode 100644
index 000000000000..724e8be05123
--- /dev/null
+++ b/src/libs/Navigation/OnyxTabNavigatorConfig/index.website.ts
@@ -0,0 +1,8 @@
+const defaultScreenOptions = {
+ animationEnabled: false,
+} as const;
+
+export {
+ // eslint-disable-next-line import/prefer-default-export
+ defaultScreenOptions,
+};
diff --git a/src/libs/Network/SequentialQueue.ts b/src/libs/Network/SequentialQueue.ts
index f9a7cd0a996b..b22a9612a23f 100644
--- a/src/libs/Network/SequentialQueue.ts
+++ b/src/libs/Network/SequentialQueue.ts
@@ -176,7 +176,7 @@ function push(request: OnyxRequest) {
flush();
}
-function getCurrentRequest(): OnyxRequest | Promise {
+function getCurrentRequest(): Promise {
if (currentRequest === null) {
return Promise.resolve();
}
diff --git a/src/libs/Network/enhanceParameters.ts b/src/libs/Network/enhanceParameters.ts
index 3fadeea7447c..e14acda5ff56 100644
--- a/src/libs/Network/enhanceParameters.ts
+++ b/src/libs/Network/enhanceParameters.ts
@@ -1,3 +1,4 @@
+import * as Environment from '@libs/Environment/Environment';
import getPlatform from '@libs/getPlatform';
import CONFIG from '@src/CONFIG';
import * as NetworkStore from './NetworkStore';
@@ -37,6 +38,8 @@ export default function enhanceParameters(command: string, parameters: Record {
@@ -83,6 +84,18 @@ Onyx.connect({
const sortedReportActions = ReportActionUtils.getSortedReportActions(_.toArray(actions), true);
allSortedReportActions[reportID] = sortedReportActions;
lastReportActions[reportID] = _.first(sortedReportActions);
+
+ // The report is only visible if it is the last action not deleted that
+ // does not match a closed or created state.
+ const reportActionsForDisplay = _.filter(
+ sortedReportActions,
+ (reportAction, actionKey) =>
+ ReportActionUtils.shouldReportActionBeVisible(reportAction, actionKey) &&
+ !ReportActionUtils.isWhisperAction(reportAction) &&
+ reportAction.actionName !== CONST.REPORT.ACTIONS.TYPE.CREATED &&
+ reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
+ );
+ visibleReportActionItems[reportID] = reportActionsForDisplay[reportActionsForDisplay.length - 1];
},
});
@@ -116,7 +129,7 @@ Onyx.connect({
* @return {String}
*/
function addSMSDomainIfPhoneNumber(login) {
- const parsedPhoneNumber = parsePhoneNumber(login);
+ const parsedPhoneNumber = PhoneNumber.parsePhoneNumber(login);
if (parsedPhoneNumber.possible && !Str.isValidEmail(login)) {
return parsedPhoneNumber.number.e164 + CONST.SMS.DOMAIN;
}
@@ -519,7 +532,7 @@ function createOption(accountIDs, personalDetails, report, reportActions = {}, {
hasMultipleParticipants && lastActorDetails && lastActorDetails.accountID !== currentUserAccountID
? lastActorDetails.firstName || PersonalDetailsUtils.getDisplayNameOrDefault(lastActorDetails)
: '';
- let lastMessageText = lastActorDisplayName ? `${lastActorDisplayName}: ${lastMessageTextFromReport}` : lastMessageTextFromReport;
+ let lastMessageText = lastMessageTextFromReport;
if (result.isArchivedRoom) {
const archiveReason =
@@ -531,12 +544,19 @@ function createOption(accountIDs, personalDetails, report, reportActions = {}, {
});
}
+ const lastAction = visibleReportActionItems[report.reportID];
+ const shouldDisplayLastActorName = lastAction && lastAction.actionName !== CONST.REPORT.ACTIONS.TYPE.REPORTPREVIEW && lastAction.actionName !== CONST.REPORT.ACTIONS.TYPE.IOU;
+
+ if (shouldDisplayLastActorName && lastActorDisplayName && lastMessageTextFromReport) {
+ lastMessageText = `${lastActorDisplayName}: ${lastMessageTextFromReport}`;
+ }
+
if (result.isThread || result.isMoneyRequestReport) {
result.alternateText = lastMessageTextFromReport.length > 0 ? lastMessageText : Localize.translate(preferredLocale, 'report.noActivityYet');
} else if (result.isChatRoom || result.isPolicyExpenseChat) {
result.alternateText = showChatPreviewLine && !forcePolicyNamePreview && lastMessageText ? lastMessageText : subtitle;
} else if (result.isTaskReport) {
- result.alternateText = showChatPreviewLine && lastMessageText ? lastMessageTextFromReport : Localize.translate(preferredLocale, 'report.noActivityYet');
+ result.alternateText = showChatPreviewLine && lastMessageText ? lastMessageText : Localize.translate(preferredLocale, 'report.noActivityYet');
} else {
result.alternateText = showChatPreviewLine && lastMessageText ? lastMessageText : LocalePhoneNumber.formatPhoneNumber(personalDetail.login);
}
@@ -1313,7 +1333,7 @@ function getOptions(
let recentReportOptions = [];
let personalDetailsOptions = [];
const reportMapForAccountIDs = {};
- const parsedPhoneNumber = parsePhoneNumber(LoginUtils.appendCountryCode(Str.removeSMSDomain(searchInputValue)));
+ const parsedPhoneNumber = PhoneNumber.parsePhoneNumber(LoginUtils.appendCountryCode(Str.removeSMSDomain(searchInputValue)));
const searchValue = parsedPhoneNumber.possible ? parsedPhoneNumber.number.e164 : searchInputValue.toLowerCase();
// Filter out all the reports that shouldn't be displayed
@@ -1390,11 +1410,13 @@ function getOptions(
);
});
- // We're only picking personal details that have logins set
- // This is a temporary fix for all the logic that's been breaking because of the new privacy changes
- // See https://github.com/Expensify/Expensify/issues/293465 for more context
- // Moreover, we should not override the personalDetails object, otherwise the createOption util won't work properly, it returns incorrect tooltipText
- const havingLoginPersonalDetails = !includeP2P ? {} : _.pick(personalDetails, (detail) => Boolean(detail.login) && !detail.isOptimisticPersonalDetail);
+ /*
+ We're only picking personal details that have logins and accountIDs set (sometimes the __fake__ account with `ID = 0` is present in the personal details collection)
+ This is a temporary fix for all the logic that's been breaking because of the new privacy changes
+ See https://github.com/Expensify/Expensify/issues/293465, https://github.com/Expensify/App/issues/33415 for more context
+ Moreover, we should not override the personalDetails object, otherwise the createOption util won't work properly, it returns incorrect tooltipText
+ */
+ const havingLoginPersonalDetails = !includeP2P ? {} : _.pick(personalDetails, (detail) => !!detail.login && !!detail.accountID && !detail.isOptimisticPersonalDetail);
let allPersonalDetailsOptions = _.map(havingLoginPersonalDetails, (personalDetail) =>
createOption([personalDetail.accountID], personalDetails, reportMapForAccountIDs[personalDetail.accountID], reportActions, {
showChatPreviewLine,
@@ -1823,7 +1845,7 @@ function getHeaderMessage(hasSelectableOptions, hasUserToInvite, searchValue, ma
return Localize.translate(preferredLocale, 'common.maxParticipantsReached', {count: CONST.REPORT.MAXIMUM_PARTICIPANTS});
}
- const isValidPhone = parsePhoneNumber(LoginUtils.appendCountryCode(searchValue)).possible;
+ const isValidPhone = PhoneNumber.parsePhoneNumber(LoginUtils.appendCountryCode(searchValue)).possible;
const isValidEmail = Str.isValidEmail(searchValue);
diff --git a/src/libs/Permissions.ts b/src/libs/Permissions.ts
index 85e64651980e..ce5e0e674c59 100644
--- a/src/libs/Permissions.ts
+++ b/src/libs/Permissions.ts
@@ -22,15 +22,6 @@ function canUseReportFields(betas: OnyxEntry): boolean {
return !!betas?.includes(CONST.BETAS.REPORT_FIELDS) || canUseAllBetas(betas);
}
-/**
- * We're requiring you to be added to the policy rooms beta on dev,
- * since contributors have been reporting a number of false issues related to the feature being under development.
- * See https://expensify.slack.com/archives/C01GTK53T8Q/p1641921996319400?thread_ts=1641598356.166900&cid=C01GTK53T8Q
- */
-function canUsePolicyRooms(betas: OnyxEntry): boolean {
- return !!betas?.includes(CONST.BETAS.POLICY_ROOMS) || canUseAllBetas(betas);
-}
-
function canUseViolations(betas: OnyxEntry): boolean {
return !!betas?.includes(CONST.BETAS.VIOLATIONS) || canUseAllBetas(betas);
}
@@ -46,7 +37,6 @@ export default {
canUseChronos,
canUseDefaultRooms,
canUseCommentLinking,
- canUsePolicyRooms,
canUseLinkPreviews,
canUseViolations,
canUseReportFields,
diff --git a/src/libs/PhoneNumber.ts b/src/libs/PhoneNumber.ts
new file mode 100644
index 000000000000..f92aade2c892
--- /dev/null
+++ b/src/libs/PhoneNumber.ts
@@ -0,0 +1,43 @@
+// eslint-disable-next-line no-restricted-imports
+import {parsePhoneNumber as originalParsePhoneNumber} from 'awesome-phonenumber';
+import type {ParsedPhoneNumber, ParsedPhoneNumberInvalid, PhoneNumberParseOptions} from 'awesome-phonenumber';
+import CONST from '@src/CONST';
+
+/**
+ * Wraps awesome-phonenumber's parsePhoneNumber function to handle the case where we want to treat
+ * a US phone number that's technically valid as invalid. eg: +115005550009.
+ * See https://github.com/Expensify/App/issues/28492
+ */
+function parsePhoneNumber(phoneNumber: string, options?: PhoneNumberParseOptions): ParsedPhoneNumber {
+ const parsedPhoneNumber = originalParsePhoneNumber(phoneNumber, options);
+ if (!parsedPhoneNumber.possible) {
+ return parsedPhoneNumber;
+ }
+
+ const phoneNumberWithoutSpecialChars = phoneNumber.replace(CONST.REGEX.SPECIAL_CHARS_WITHOUT_NEWLINE, '');
+ if (!/^\+11[0-9]{10}$/.test(phoneNumberWithoutSpecialChars)) {
+ return parsedPhoneNumber;
+ }
+
+ const countryCode = phoneNumberWithoutSpecialChars.substring(0, 2);
+ const phoneNumberWithoutCountryCode = phoneNumberWithoutSpecialChars.substring(2);
+
+ return {
+ ...parsedPhoneNumber,
+ valid: false,
+ possible: false,
+ number: {
+ ...parsedPhoneNumber.number,
+
+ // mimic the behavior of awesome-phonenumber
+ e164: phoneNumberWithoutSpecialChars,
+ international: `${countryCode} ${phoneNumberWithoutCountryCode}`,
+ national: phoneNumberWithoutCountryCode,
+ rfc3966: `tel:${countryCode}-${phoneNumberWithoutCountryCode}`,
+ significant: phoneNumberWithoutCountryCode,
+ },
+ } as ParsedPhoneNumberInvalid;
+}
+
+// eslint-disable-next-line import/prefer-default-export
+export {parsePhoneNumber};
diff --git a/src/libs/ReportActionsUtils.ts b/src/libs/ReportActionsUtils.ts
index c8b7e673aed4..ee4fa201ee2f 100644
--- a/src/libs/ReportActionsUtils.ts
+++ b/src/libs/ReportActionsUtils.ts
@@ -378,10 +378,20 @@ function shouldReportActionBeVisible(reportAction: OnyxEntry, key:
// All other actions are displayed except thread parents, deleted, or non-pending actions
const isDeleted = isDeletedAction(reportAction);
- const isPending = !!reportAction.pendingAction && !(!isNetworkOffline && reportAction.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE);
+ const isPending = !!reportAction.pendingAction;
return !isDeleted || isPending || isDeletedParentAction(reportAction) || isReversedTransaction(reportAction);
}
+/**
+ * Checks if the new marker should be hidden for the report action.
+ */
+function shouldHideNewMarker(reportAction: OnyxEntry): boolean {
+ if (!reportAction) {
+ return true;
+ }
+ return !isNetworkOffline && reportAction.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
+}
+
/**
* Checks if a reportAction is fit for display as report last action, meaning that
* it satisfies shouldReportActionBeVisible, it's not whisper action and not deleted.
@@ -841,6 +851,7 @@ export {
isWhisperAction,
isReimbursementQueuedAction,
shouldReportActionBeVisible,
+ shouldHideNewMarker,
shouldReportActionBeVisibleAsLastAction,
hasRequestFromCurrentAccount,
getFirstVisibleReportActionID,
diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts
index 0e159cf69095..e619cb3c80dd 100644
--- a/src/libs/ReportUtils.ts
+++ b/src/libs/ReportUtils.ts
@@ -996,6 +996,12 @@ function hasSingleParticipant(report: OnyxEntry): boolean {
*/
function hasOnlyDistanceRequestTransactions(iouReportID: string | undefined): boolean {
const transactions = TransactionUtils.getAllReportTransactions(iouReportID);
+
+ // Early return false in case not having any transaction
+ if (!transactions || transactions.length === 0) {
+ return false;
+ }
+
return transactions.every((transaction) => TransactionUtils.isDistanceRequest(transaction));
}
@@ -1488,7 +1494,6 @@ function getDisplayNameForParticipant(accountID?: number, shouldUseShortForm = f
}
const personalDetails = getPersonalDetailsForAccountID(accountID);
- // console.log(personalDetails);
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const formattedLogin = LocalePhoneNumber.formatPhoneNumber(personalDetails.login || '');
// This is to check if account is an invite/optimistically created one
@@ -1550,17 +1555,6 @@ function getDisplayNamesWithTooltips(
});
}
-/**
- * Gets a joined string of display names from the list of display name with tooltip objects.
- *
- */
-function getDisplayNamesStringFromTooltips(displayNamesWithTooltips: DisplayNameWithTooltips | undefined) {
- return displayNamesWithTooltips
- ?.map(({displayName}) => displayName)
- .filter(Boolean)
- .join(', ');
-}
-
/**
* For a deleted parent report action within a chat report,
* let us return the appropriate display message
@@ -2426,6 +2420,7 @@ function buildOptimisticAddCommentReportAction(text?: string, file?: File): Opti
attachmentInfo,
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
shouldShow: true,
+ isOptimisticAction: true,
},
};
}
@@ -2921,10 +2916,10 @@ function buildOptimisticReportPreview(
accountID: iouReport?.managerID ?? 0,
// The preview is initially whispered if created with a receipt, so the actor is the current user as well
actorAccountID: hasReceipt ? currentUserAccountID : iouReport?.managerID ?? 0,
+ childReportID: childReportID ?? iouReport?.reportID,
childMoneyRequestCount: 1,
childLastMoneyRequestComment: comment,
childRecentReceiptTransactionIDs: hasReceipt && isNotEmptyObject(transaction) ? {[transaction?.transactionID ?? '']: created} : undefined,
- childReportID,
whisperedToAccountIDs: isReceiptBeingScanned ? [currentUserAccountID ?? -1] : [],
};
}
@@ -3769,6 +3764,7 @@ function canRequestMoney(report: OnyxEntry, policy: OnyxEntry, o
if (isOwnExpenseReport && PolicyUtils.isPaidGroupPolicy(policy)) {
return isDraftExpenseReport(report);
}
+
return (isOwnExpenseReport || isIOUReport(report)) && !isReportApproved(report) && !isSettled(report?.reportID);
}
@@ -3937,6 +3933,13 @@ function getAddWorkspaceRoomOrChatReportErrors(report: OnyxEntry): Recor
function canUserPerformWriteAction(report: OnyxEntry) {
const reportErrors = getAddWorkspaceRoomOrChatReportErrors(report);
+ // If the Money Request report is marked for deletion, let us prevent any further write action.
+ if (isMoneyRequestReport(report)) {
+ const parentReportAction = ReportActionsUtils.getReportAction(report?.parentReportID ?? '', report?.parentReportActionID ?? '');
+ if (parentReportAction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) {
+ return false;
+ }
+ }
return !isArchivedRoom(report) && isEmptyObject(reportErrors) && report && isAllowedToComment(report) && !isAnonymousUser;
}
@@ -4116,6 +4119,11 @@ function getTaskAssigneeChatOnyxData(
value: optimisticAssigneeReport,
},
);
+ successData.push({
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${assigneeChatReportID}`,
+ value: {[optimisticAssigneeAddComment.reportAction.reportActionID ?? '']: {isOptimisticAction: null}},
+ });
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${assigneeChatReportID}`,
@@ -4316,6 +4324,14 @@ function navigateToPrivateNotes(report: Report, session: Session) {
Navigation.navigate(ROUTES.PRIVATE_NOTES_LIST.getRoute(report.reportID));
}
+/**
+ * Checks if thread replies should be displayed
+ */
+function shouldDisplayThreadReplies(reportAction: ReportAction, reportID: string): boolean {
+ const hasReplies = (reportAction.childVisibleActionCount ?? 0) > 0;
+ return hasReplies && !!reportAction.childCommenterCount && !isThreadFirstChat(reportAction, reportID);
+}
+
/**
* Disable reply in thread action if:
*
@@ -4392,7 +4408,6 @@ export {
getIcons,
getRoomWelcomeMessage,
getDisplayNamesWithTooltips,
- getDisplayNamesStringFromTooltips,
getReportName,
getReport,
getReportNotificationPreference,
@@ -4516,7 +4531,8 @@ export {
canEditWriteCapability,
hasSmartscanError,
shouldAutoFocusOnKeyPress,
+ shouldDisplayThreadReplies,
shouldDisableThread,
};
-export type {ExpenseOriginalMessage, OptionData, OptimisticChatReport};
+export type {ExpenseOriginalMessage, OptionData, OptimisticChatReport, OptimisticCreatedReportAction};
diff --git a/src/libs/ValidationUtils.ts b/src/libs/ValidationUtils.ts
index 4b973d95d136..9ba11fb16d6a 100644
--- a/src/libs/ValidationUtils.ts
+++ b/src/libs/ValidationUtils.ts
@@ -1,4 +1,3 @@
-import {parsePhoneNumber} from 'awesome-phonenumber';
import {addYears, endOfMonth, format, isAfter, isBefore, isSameDay, isValid, isWithinInterval, parse, parseISO, startOfDay, subYears} from 'date-fns';
import {URL_REGEX_WITH_REQUIRED_PROTOCOL} from 'expensify-common/lib/Url';
import isDate from 'lodash/isDate';
@@ -10,6 +9,7 @@ import type * as OnyxCommon from '@src/types/onyx/OnyxCommon';
import * as CardUtils from './CardUtils';
import DateUtils from './DateUtils';
import * as LoginUtils from './LoginUtils';
+import {parsePhoneNumber} from './PhoneNumber';
import StringUtils from './StringUtils';
/**
@@ -35,7 +35,7 @@ function validateCardNumber(value: string): boolean {
* Validating that this is a valid address (PO boxes are not allowed)
*/
function isValidAddress(value: string): boolean {
- if (!CONST.REGEX.ANY_VALUE.test(value)) {
+ if (!CONST.REGEX.ANY_VALUE.test(value) || value.match(CONST.REGEX.EMOJIS)) {
return false;
}
@@ -306,6 +306,13 @@ function isValidRoutingNumber(routingNumber: string): boolean {
return false;
}
+/**
+ * Checks that the provided name doesn't contain any emojis
+ */
+function isValidCompanyName(name: string) {
+ return !name.match(CONST.REGEX.EMOJIS);
+}
+
/**
* Checks that the provided name doesn't contain any commas or semicolons
*/
@@ -317,7 +324,8 @@ function isValidDisplayName(name: string): boolean {
* Checks that the provided legal name doesn't contain special characters
*/
function isValidLegalName(name: string): boolean {
- return CONST.REGEX.ALPHABETIC_AND_LATIN_CHARS.test(name);
+ const hasAccentedChars = Boolean(name.match(CONST.REGEX.ACCENT_LATIN_CHARS));
+ return CONST.REGEX.ALPHABETIC_AND_LATIN_CHARS.test(name) && !hasAccentedChars;
}
/**
@@ -451,6 +459,7 @@ export {
isValidRoomName,
isValidTaxID,
isValidValidateCode,
+ isValidCompanyName,
isValidDisplayName,
isValidLegalName,
doesContainReservedWord,
diff --git a/src/libs/ValueUtils.ts b/src/libs/ValueUtils.ts
new file mode 100644
index 000000000000..002a8fb347d6
--- /dev/null
+++ b/src/libs/ValueUtils.ts
@@ -0,0 +1,4 @@
+const getReturnValue = (value: ((...p: P) => T) | T, ...p: P) => (typeof value === 'function' ? (value as (...p: P) => T)(...p) : value);
+const getFirstValue = (value: T | [T]) => (Array.isArray(value) ? value[0] : value);
+
+export {getReturnValue, getFirstValue};
diff --git a/src/libs/__mocks__/Permissions.ts b/src/libs/__mocks__/Permissions.ts
index 759392bde2c6..b175e9f40efc 100644
--- a/src/libs/__mocks__/Permissions.ts
+++ b/src/libs/__mocks__/Permissions.ts
@@ -11,5 +11,4 @@ import type Beta from '@src/types/onyx/Beta';
export default {
...jest.requireActual('../Permissions'),
canUseDefaultRooms: (betas: Beta[]) => betas.includes(CONST.BETAS.DEFAULT_ROOMS),
- canUsePolicyRooms: (betas: Beta[]) => betas.includes(CONST.BETAS.POLICY_ROOMS),
};
diff --git a/src/libs/actions/App.ts b/src/libs/actions/App.ts
index 798d94bfb0e0..3a2241bd5494 100644
--- a/src/libs/actions/App.ts
+++ b/src/libs/actions/App.ts
@@ -159,7 +159,7 @@ function getPolicyParamsForOpenOrReconnect(): Promise = {
+ const defaultData = {
optimisticData: [
{
onyxMethod: Onyx.METHOD.MERGE,
@@ -167,14 +167,7 @@ function getOnyxDataForOpenOrReconnect(isOpenApp = false): OnyxData {
value: true,
},
],
- successData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.IS_LOADING_REPORT_DATA,
- value: false,
- },
- ],
- failureData: [
+ finallyData: [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.IS_LOADING_REPORT_DATA,
@@ -194,16 +187,8 @@ function getOnyxDataForOpenOrReconnect(isOpenApp = false): OnyxData {
value: true,
},
],
- successData: [
- ...defaultData.successData,
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.IS_LOADING_APP,
- value: false,
- },
- ],
- failureData: [
- ...defaultData.failureData,
+ finallyData: [
+ ...defaultData.finallyData,
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.IS_LOADING_APP,
@@ -297,12 +282,12 @@ function finalReconnectAppAfterActivatingReliableUpdates(): Promise {
+function getMissingOnyxUpdates(updateIDFrom = 0, updateIDTo: number | string = 0): Promise {
console.debug(`[OnyxUpdates] Fetching missing updates updateIDFrom: ${updateIDFrom} and updateIDTo: ${updateIDTo}`);
type GetMissingOnyxMessagesParams = {
updateIDFrom: number;
- updateIDTo: number;
+ updateIDTo: number | string;
};
const parameters: GetMissingOnyxMessagesParams = {
diff --git a/src/libs/actions/CanvasSize.js b/src/libs/actions/CanvasSize.ts
similarity index 92%
rename from src/libs/actions/CanvasSize.js
rename to src/libs/actions/CanvasSize.ts
index b313763131b9..8e0a155f25eb 100644
--- a/src/libs/actions/CanvasSize.js
+++ b/src/libs/actions/CanvasSize.ts
@@ -11,12 +11,12 @@ function retrieveMaxCanvasArea() {
// More information at: https://github.com/jhildenbiddle/canvas-size/issues/13
canvasSize
.maxArea({
- max: Browser.isMobile() ? 8192 : null,
+ max: Browser.isMobile() ? 8192 : undefined,
usePromise: true,
useWorker: false,
})
.then(() => ({
- onSuccess: (width, height) => {
+ onSuccess: (width: number, height: number) => {
Onyx.merge(ONYXKEYS.MAX_CANVAS_AREA, width * height);
},
}));
diff --git a/src/libs/actions/Card.js b/src/libs/actions/Card.js
deleted file mode 100644
index 68642bd8fdf1..000000000000
--- a/src/libs/actions/Card.js
+++ /dev/null
@@ -1,176 +0,0 @@
-import Onyx from 'react-native-onyx';
-import * as API from '@libs/API';
-import * as Localize from '@libs/Localize';
-import CONST from '@src/CONST';
-import ONYXKEYS from '@src/ONYXKEYS';
-
-/**
- * @param {Number} cardID
- */
-function reportVirtualExpensifyCardFraud(cardID) {
- API.write(
- 'ReportVirtualExpensifyCardFraud',
- {
- cardID,
- },
- {
- optimisticData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.FORMS.REPORT_VIRTUAL_CARD_FRAUD,
- value: {
- isLoading: true,
- },
- },
- ],
- successData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.FORMS.REPORT_VIRTUAL_CARD_FRAUD,
- value: {
- isLoading: false,
- },
- },
- ],
- failureData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.FORMS.REPORT_VIRTUAL_CARD_FRAUD,
- value: {
- isLoading: false,
- },
- },
- ],
- },
- );
-}
-
-/**
- * Call the API to deactivate the card and request a new one
- * @param {String} cardId - id of the card that is going to be replaced
- * @param {String} reason - reason for replacement ('damaged' | 'stolen')
- */
-function requestReplacementExpensifyCard(cardId, reason) {
- API.write(
- 'RequestReplacementExpensifyCard',
- {
- cardId,
- reason,
- },
- {
- optimisticData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.FORMS.REPORT_PHYSICAL_CARD_FORM,
- value: {
- isLoading: true,
- errors: null,
- },
- },
- ],
- successData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.FORMS.REPORT_PHYSICAL_CARD_FORM,
- value: {
- isLoading: false,
- },
- },
- ],
- failureData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.FORMS.REPORT_PHYSICAL_CARD_FORM,
- value: {
- isLoading: false,
- },
- },
- ],
- },
- );
-}
-
-/**
- * Activates the physical Expensify card based on the last four digits of the card number
- *
- * @param {String} cardLastFourDigits
- * @param {Number} cardID
- */
-function activatePhysicalExpensifyCard(cardLastFourDigits, cardID) {
- API.write(
- 'ActivatePhysicalExpensifyCard',
- {cardLastFourDigits, cardID},
- {
- optimisticData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.CARD_LIST,
- value: {
- [cardID]: {
- errors: null,
- isLoading: true,
- },
- },
- },
- ],
- successData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.CARD_LIST,
- value: {
- [cardID]: {
- isLoading: false,
- },
- },
- },
- ],
- failureData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.CARD_LIST,
- value: {
- [cardID]: {
- isLoading: false,
- },
- },
- },
- ],
- },
- );
-}
-
-/**
- * Clears errors for a specific cardID
- *
- * @param {Number} cardID
- */
-function clearCardListErrors(cardID) {
- Onyx.merge(ONYXKEYS.CARD_LIST, {[cardID]: {errors: null, isLoading: false}});
-}
-
-/**
- * Makes an API call to get virtual card details (pan, cvv, expiration date, address)
- * This function purposefully uses `makeRequestWithSideEffects` method. For security reason
- * card details cannot be persisted in Onyx and have to be asked for each time a user want's to
- * reveal them.
- *
- * @param {String} cardID - virtual card ID
- *
- * @returns {Promise} - promise with card details object
- */
-function revealVirtualCardDetails(cardID) {
- return new Promise((resolve, reject) => {
- // eslint-disable-next-line rulesdir/no-api-side-effects-method
- API.makeRequestWithSideEffects('RevealExpensifyCardDetails', {cardID})
- .then((response) => {
- if (response.jsonCode !== CONST.JSON_CODE.SUCCESS) {
- reject(Localize.translateLocal('cardPage.cardDetailsLoadingFailure'));
- return;
- }
- resolve(response);
- })
- .catch(() => reject(Localize.translateLocal('cardPage.cardDetailsLoadingFailure')));
- });
-}
-
-export {requestReplacementExpensifyCard, activatePhysicalExpensifyCard, clearCardListErrors, reportVirtualExpensifyCardFraud, revealVirtualCardDetails};
diff --git a/src/libs/actions/Card.ts b/src/libs/actions/Card.ts
new file mode 100644
index 000000000000..172b0ac73ca6
--- /dev/null
+++ b/src/libs/actions/Card.ts
@@ -0,0 +1,193 @@
+import Onyx from 'react-native-onyx';
+import type {OnyxUpdate} from 'react-native-onyx';
+import * as API from '@libs/API';
+import * as Localize from '@libs/Localize';
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import type {Response} from '@src/types/onyx';
+
+type ReplacementReason = 'damaged' | 'stolen';
+
+function reportVirtualExpensifyCardFraud(cardID: number) {
+ const optimisticData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.FORMS.REPORT_VIRTUAL_CARD_FRAUD,
+ value: {
+ isLoading: true,
+ },
+ },
+ ];
+
+ const successData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.FORMS.REPORT_VIRTUAL_CARD_FRAUD,
+ value: {
+ isLoading: false,
+ },
+ },
+ ];
+
+ const failureData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.FORMS.REPORT_VIRTUAL_CARD_FRAUD,
+ value: {
+ isLoading: false,
+ },
+ },
+ ];
+
+ type ReportVirtualExpensifyCardFraudParams = {
+ cardID: number;
+ };
+
+ const parameters: ReportVirtualExpensifyCardFraudParams = {
+ cardID,
+ };
+
+ API.write('ReportVirtualExpensifyCardFraud', parameters, {optimisticData, successData, failureData});
+}
+
+/**
+ * Call the API to deactivate the card and request a new one
+ * @param cardId - id of the card that is going to be replaced
+ * @param reason - reason for replacement
+ */
+function requestReplacementExpensifyCard(cardId: number, reason: ReplacementReason) {
+ const optimisticData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.FORMS.REPORT_PHYSICAL_CARD_FORM,
+ value: {
+ isLoading: true,
+ errors: null,
+ },
+ },
+ ];
+
+ const successData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.FORMS.REPORT_PHYSICAL_CARD_FORM,
+ value: {
+ isLoading: false,
+ },
+ },
+ ];
+
+ const failureData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.FORMS.REPORT_PHYSICAL_CARD_FORM,
+ value: {
+ isLoading: false,
+ },
+ },
+ ];
+
+ type RequestReplacementExpensifyCardParams = {
+ cardId: number;
+ reason: string;
+ };
+
+ const parameters: RequestReplacementExpensifyCardParams = {
+ cardId,
+ reason,
+ };
+
+ API.write('RequestReplacementExpensifyCard', parameters, {optimisticData, successData, failureData});
+}
+
+/**
+ * Activates the physical Expensify card based on the last four digits of the card number
+ */
+function activatePhysicalExpensifyCard(cardLastFourDigits: string, cardID: number) {
+ const optimisticData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.CARD_LIST,
+ value: {
+ [cardID]: {
+ errors: null,
+ isLoading: true,
+ },
+ },
+ },
+ ];
+
+ const successData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.CARD_LIST,
+ value: {
+ [cardID]: {
+ isLoading: false,
+ },
+ },
+ },
+ ];
+
+ const failureData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.CARD_LIST,
+ value: {
+ [cardID]: {
+ isLoading: false,
+ },
+ },
+ },
+ ];
+
+ type ActivatePhysicalExpensifyCardParams = {
+ cardLastFourDigits: string;
+ cardID: number;
+ };
+
+ const parameters: ActivatePhysicalExpensifyCardParams = {
+ cardLastFourDigits,
+ cardID,
+ };
+
+ API.write('ActivatePhysicalExpensifyCard', parameters, {optimisticData, successData, failureData});
+}
+
+/**
+ * Clears errors for a specific cardID
+ */
+function clearCardListErrors(cardID: number) {
+ Onyx.merge(ONYXKEYS.CARD_LIST, {[cardID]: {errors: null, isLoading: false}});
+}
+
+/**
+ * Makes an API call to get virtual card details (pan, cvv, expiration date, address)
+ * This function purposefully uses `makeRequestWithSideEffects` method. For security reason
+ * card details cannot be persisted in Onyx and have to be asked for each time a user want's to
+ * reveal them.
+ *
+ * @param cardID - virtual card ID
+ *
+ * @returns promise with card details object
+ */
+function revealVirtualCardDetails(cardID: number): Promise {
+ return new Promise((resolve, reject) => {
+ type RevealExpensifyCardDetailsParams = {cardID: number};
+
+ const parameters: RevealExpensifyCardDetailsParams = {cardID};
+
+ // eslint-disable-next-line rulesdir/no-api-side-effects-method
+ API.makeRequestWithSideEffects('RevealExpensifyCardDetails', parameters)
+ .then((response) => {
+ if (response?.jsonCode !== CONST.JSON_CODE.SUCCESS) {
+ reject(Localize.translateLocal('cardPage.cardDetailsLoadingFailure'));
+ return;
+ }
+ resolve(response);
+ })
+ .catch(() => reject(Localize.translateLocal('cardPage.cardDetailsLoadingFailure')));
+ });
+}
+
+export {requestReplacementExpensifyCard, activatePhysicalExpensifyCard, clearCardListErrors, reportVirtualExpensifyCardFraud, revealVirtualCardDetails};
diff --git a/src/libs/actions/IOU.js b/src/libs/actions/IOU.js
index fb4e9f02f1b6..ac604019354b 100644
--- a/src/libs/actions/IOU.js
+++ b/src/libs/actions/IOU.js
@@ -264,9 +264,13 @@ function setMoneyRequestParticipants_temporaryForRefactor(transactionID, partici
* @param {String} transactionID
* @param {String} source
* @param {String} filename
+ * @param {Boolean} isDraft
*/
-function setMoneyRequestReceipt_temporaryForRefactor(transactionID, source, filename) {
- Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transactionID}`, {receipt: {source}, filename});
+function setMoneyRequestReceipt(transactionID, source, filename, isDraft) {
+ Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {
+ receipt: {source},
+ filename,
+ });
}
/**
@@ -1109,6 +1113,36 @@ function updateMoneyRequestDate(transactionID, transactionThreadReportID, val) {
API.write('UpdateMoneyRequestDate', params, onyxData);
}
+/**
+ * Updates the billable field of a money request
+ *
+ * @param {String} transactionID
+ * @param {Number} transactionThreadReportID
+ * @param {String} val
+ */
+function updateMoneyRequestBillable(transactionID, transactionThreadReportID, val) {
+ const transactionChanges = {
+ billable: val,
+ };
+ const {params, onyxData} = getUpdateMoneyRequestParams(transactionID, transactionThreadReportID, transactionChanges, true);
+ API.write('UpdateMoneyRequestBillable', params, onyxData);
+}
+
+/**
+ * Updates the merchant field of a money request
+ *
+ * @param {String} transactionID
+ * @param {Number} transactionThreadReportID
+ * @param {String} val
+ */
+function updateMoneyRequestMerchant(transactionID, transactionThreadReportID, val) {
+ const transactionChanges = {
+ merchant: val,
+ };
+ const {params, onyxData} = getUpdateMoneyRequestParams(transactionID, transactionThreadReportID, transactionChanges, true);
+ API.write('UpdateMoneyRequestMerchant', params, onyxData);
+}
+
/**
* Updates the created date of a money request
*
@@ -2467,38 +2501,37 @@ function deleteMoneyRequest(transactionID, reportAction, isSingleTransactionView
iouReportLastMessageText.length === 0 && !ReportActionsUtils.isDeletedParentAction(lastVisibleAction) && (!transactionThreadID || shouldDeleteTransactionThread);
// STEP 4: Update the iouReport and reportPreview with new totals and messages if it wasn't deleted
- let updatedIOUReport = null;
- let updatedReportPreviewAction = null;
- if (!shouldDeleteIOUReport) {
- if (ReportUtils.isExpenseReport(iouReport)) {
- updatedIOUReport = {...iouReport};
+ let updatedIOUReport = {...iouReport};
+ const updatedReportPreviewAction = {...reportPreviewAction};
+ updatedReportPreviewAction.pendingAction = shouldDeleteIOUReport ? CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE : CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE;
+ if (ReportUtils.isExpenseReport(iouReport)) {
+ updatedIOUReport = {...iouReport};
+
+ // Because of the Expense reports are stored as negative values, we add the total from the amount
+ updatedIOUReport.total += TransactionUtils.getAmount(transaction, true);
+ } else {
+ updatedIOUReport = IOUUtils.updateIOUOwnerAndTotal(
+ iouReport,
+ reportAction.actorAccountID,
+ TransactionUtils.getAmount(transaction, false),
+ TransactionUtils.getCurrency(transaction),
+ true,
+ );
+ }
- // Because of the Expense reports are stored as negative values, we add the total from the amount
- updatedIOUReport.total += TransactionUtils.getAmount(transaction, true);
- } else {
- updatedIOUReport = IOUUtils.updateIOUOwnerAndTotal(
- iouReport,
- reportAction.actorAccountID,
- TransactionUtils.getAmount(transaction, false),
- TransactionUtils.getCurrency(transaction),
- true,
- );
- }
+ updatedIOUReport.lastMessageText = iouReportLastMessageText;
+ updatedIOUReport.lastVisibleActionCreated = lodashGet(lastVisibleAction, 'created');
- updatedIOUReport.lastMessageText = iouReportLastMessageText;
- updatedIOUReport.lastVisibleActionCreated = lodashGet(lastVisibleAction, 'created');
+ const hasNonReimbursableTransactions = ReportUtils.hasNonReimbursableTransactions(iouReport);
+ const messageText = Localize.translateLocal(hasNonReimbursableTransactions ? 'iou.payerSpentAmount' : 'iou.payerOwesAmount', {
+ payer: ReportUtils.getPersonalDetailsForAccountID(updatedIOUReport.managerID).login || '',
+ amount: CurrencyUtils.convertToDisplayString(updatedIOUReport.total, updatedIOUReport.currency),
+ });
+ updatedReportPreviewAction.message[0].text = messageText;
+ updatedReportPreviewAction.message[0].html = messageText;
- updatedReportPreviewAction = {...reportPreviewAction};
- const hasNonReimbursableTransactions = ReportUtils.hasNonReimbursableTransactions(iouReport);
- const messageText = Localize.translateLocal(hasNonReimbursableTransactions ? 'iou.payerSpentAmount' : 'iou.payerOwesAmount', {
- payer: ReportUtils.getPersonalDetailsForAccountID(updatedIOUReport.managerID).login || '',
- amount: CurrencyUtils.convertToDisplayString(updatedIOUReport.total, updatedIOUReport.currency),
- });
- updatedReportPreviewAction.message[0].text = messageText;
- updatedReportPreviewAction.message[0].html = messageText;
- if (reportPreviewAction.childMoneyRequestCount > 0) {
- updatedReportPreviewAction.childMoneyRequestCount = reportPreviewAction.childMoneyRequestCount - 1;
- }
+ if (reportPreviewAction.childMoneyRequestCount > 0) {
+ updatedReportPreviewAction.childMoneyRequestCount = reportPreviewAction.childMoneyRequestCount - 1;
}
// STEP 5: Build Onyx data
@@ -2532,12 +2565,12 @@ function deleteMoneyRequest(transactionID, reportAction, isSingleTransactionView
]
: []),
{
- onyxMethod: shouldDeleteIOUReport ? Onyx.METHOD.SET : Onyx.METHOD.MERGE,
+ onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport.reportID}`,
- value: shouldDeleteIOUReport ? null : updatedReportAction,
+ value: updatedReportAction,
},
{
- onyxMethod: shouldDeleteIOUReport ? Onyx.METHOD.SET : Onyx.METHOD.MERGE,
+ onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`,
value: updatedIOUReport,
},
@@ -2580,9 +2613,34 @@ function deleteMoneyRequest(transactionID, reportAction, isSingleTransactionView
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport.reportID}`,
value: {
- [reportAction.reportActionID]: {pendingAction: null},
+ [reportAction.reportActionID]: shouldDeleteIOUReport
+ ? null
+ : {
+ pendingAction: null,
+ },
+ },
+ },
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport.reportID}`,
+ value: {
+ [reportPreviewAction.reportActionID]: shouldDeleteIOUReport
+ ? null
+ : {
+ pendingAction: null,
+ errors: null,
+ },
},
},
+ ...(shouldDeleteIOUReport
+ ? [
+ {
+ onyxMethod: Onyx.METHOD.SET,
+ key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport.reportID}`,
+ value: null,
+ },
+ ]
+ : []),
];
const failureData = [
@@ -2628,7 +2686,10 @@ function deleteMoneyRequest(transactionID, reportAction, isSingleTransactionView
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport.reportID}`,
value: {
- [reportPreviewAction.reportActionID]: reportPreviewAction,
+ [reportPreviewAction.reportActionID]: {
+ ...reportPreviewAction,
+ errors: ErrorUtils.getMicroSecondOnyxError('iou.error.genericDeleteFailureMessage'),
+ },
},
},
...(shouldDeleteIOUReport
@@ -3206,7 +3267,7 @@ function submitReport(expenseReport) {
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`,
value: {
- [expenseReport.reportActionID]: {
+ [optimisticSubmittedReportAction.reportActionID]: {
errors: ErrorUtils.getMicroSecondOnyxError('iou.error.other'),
},
},
@@ -3300,10 +3361,10 @@ function detachReceipt(transactionID) {
/**
* @param {String} transactionID
- * @param {Object} receipt
- * @param {String} filePath
+ * @param {Object} file
+ * @param {String} source
*/
-function replaceReceipt(transactionID, receipt, filePath) {
+function replaceReceipt(transactionID, file, source) {
const transaction = lodashGet(allTransactions, 'transactionID', {});
const oldReceipt = lodashGet(transaction, 'receipt', {});
@@ -3313,10 +3374,10 @@ function replaceReceipt(transactionID, receipt, filePath) {
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
value: {
receipt: {
- source: filePath,
+ source,
state: CONST.IOU.RECEIPT_STATE.OPEN,
},
- filename: receipt.name,
+ filename: file.name,
},
},
];
@@ -3332,7 +3393,7 @@ function replaceReceipt(transactionID, receipt, filePath) {
},
];
- API.write('ReplaceReceipt', {transactionID, receipt}, {optimisticData, failureData});
+ API.write('ReplaceReceipt', {transactionID, receipt: file}, {optimisticData, failureData});
}
/**
@@ -3458,14 +3519,6 @@ function setMoneyRequestParticipants(participants, isSplitRequest) {
Onyx.merge(ONYXKEYS.IOU, {participants, isSplitRequest});
}
-/**
- * @param {String} receiptPath
- * @param {String} receiptFilename
- */
-function setMoneyRequestReceipt(receiptPath, receiptFilename) {
- Onyx.merge(ONYXKEYS.IOU, {receiptPath, receiptFilename, merchant: ''});
-}
-
function setUpDistanceTransaction() {
const transactionID = NumberUtils.rand64();
Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {
@@ -3569,7 +3622,7 @@ export {
setMoneyRequestDescription_temporaryForRefactor,
setMoneyRequestMerchant_temporaryForRefactor,
setMoneyRequestParticipants_temporaryForRefactor,
- setMoneyRequestReceipt_temporaryForRefactor,
+ setMoneyRequestReceipt,
setMoneyRequestTag_temporaryForRefactor,
setMoneyRequestAmount,
setMoneyRequestBillable,
@@ -3580,13 +3633,14 @@ export {
setMoneyRequestId,
setMoneyRequestMerchant,
setMoneyRequestParticipantsFromReport,
- setMoneyRequestReceipt,
setMoneyRequestTag,
setMoneyRequestTaxAmount,
setMoneyRequestTaxRate,
setUpDistanceTransaction,
navigateToNextPage,
updateMoneyRequestDate,
+ updateMoneyRequestBillable,
+ updateMoneyRequestMerchant,
updateMoneyRequestTag,
updateMoneyRequestAmountAndCurrency,
replaceReceipt,
diff --git a/src/libs/actions/InputFocus/index.desktop.ts b/src/libs/actions/InputFocus/index.desktop.ts
index 86a562f0531e..2a8fe1b9fd01 100644
--- a/src/libs/actions/InputFocus/index.desktop.ts
+++ b/src/libs/actions/InputFocus/index.desktop.ts
@@ -1,13 +1,14 @@
import Onyx from 'react-native-onyx';
import ReportActionComposeFocusManager from '@libs/ReportActionComposeFocusManager';
import ONYXKEYS from '@src/ONYXKEYS';
+import type {Modal} from '@src/types/onyx';
function inputFocusChange(focus: boolean) {
Onyx.set(ONYXKEYS.INPUT_FOCUSED, focus);
}
let refSave: HTMLElement | undefined;
-function composerFocusKeepFocusOn(ref: HTMLElement, isFocused: boolean, modal: {willAlertModalBecomeVisible: boolean; isVisible: boolean}, onyxFocused: boolean) {
+function composerFocusKeepFocusOn(ref: HTMLElement, isFocused: boolean, modal: Modal, onyxFocused: boolean) {
if (isFocused && !onyxFocused) {
inputFocusChange(true);
ref.focus();
diff --git a/src/libs/actions/InputFocus/index.ts b/src/libs/actions/InputFocus/index.ts
index 1840b0625626..6d8706ebdd0e 100644
--- a/src/libs/actions/InputFocus/index.ts
+++ b/src/libs/actions/InputFocus/index.ts
@@ -1,5 +1,9 @@
-function inputFocusChange() {}
-function composerFocusKeepFocusOn() {}
-const callback = () => {};
+import type {Modal} from '@src/types/onyx';
+
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+function inputFocusChange(focus: boolean) {}
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+function composerFocusKeepFocusOn(ref: HTMLElement, isFocused: boolean, modal: Modal, onyxFocused: boolean) {}
+const callback = (method: () => void) => method();
export {composerFocusKeepFocusOn, inputFocusChange, callback};
diff --git a/src/libs/actions/InputFocus/index.website.ts b/src/libs/actions/InputFocus/index.website.ts
index 8e41e06d7401..541254ac0cda 100644
--- a/src/libs/actions/InputFocus/index.website.ts
+++ b/src/libs/actions/InputFocus/index.website.ts
@@ -2,13 +2,14 @@ import Onyx from 'react-native-onyx';
import * as Browser from '@libs/Browser';
import ReportActionComposeFocusManager from '@libs/ReportActionComposeFocusManager';
import ONYXKEYS from '@src/ONYXKEYS';
+import type {Modal} from '@src/types/onyx';
function inputFocusChange(focus: boolean) {
Onyx.set(ONYXKEYS.INPUT_FOCUSED, focus);
}
let refSave: HTMLElement | undefined;
-function composerFocusKeepFocusOn(ref: HTMLElement, isFocused: boolean, modal: {willAlertModalBecomeVisible: boolean; isVisible: boolean}, onyxFocused: boolean) {
+function composerFocusKeepFocusOn(ref: HTMLElement, isFocused: boolean, modal: Modal, onyxFocused: boolean) {
if (isFocused && !onyxFocused) {
inputFocusChange(true);
ref.focus();
diff --git a/src/libs/actions/MemoryOnlyKeys/MemoryOnlyKeys.js b/src/libs/actions/MemoryOnlyKeys/MemoryOnlyKeys.ts
similarity index 71%
rename from src/libs/actions/MemoryOnlyKeys/MemoryOnlyKeys.js
rename to src/libs/actions/MemoryOnlyKeys/MemoryOnlyKeys.ts
index 028bce225909..3e8c613187b4 100644
--- a/src/libs/actions/MemoryOnlyKeys/MemoryOnlyKeys.js
+++ b/src/libs/actions/MemoryOnlyKeys/MemoryOnlyKeys.ts
@@ -1,8 +1,9 @@
import Onyx from 'react-native-onyx';
+import type {OnyxKey} from 'react-native-onyx/lib/types';
import Log from '@libs/Log';
import ONYXKEYS from '@src/ONYXKEYS';
-const memoryOnlyKeys = [ONYXKEYS.COLLECTION.REPORT, ONYXKEYS.COLLECTION.POLICY, ONYXKEYS.PERSONAL_DETAILS_LIST];
+const memoryOnlyKeys: OnyxKey[] = [ONYXKEYS.COLLECTION.REPORT, ONYXKEYS.COLLECTION.POLICY, ONYXKEYS.PERSONAL_DETAILS_LIST];
const enable = () => {
Log.info('[MemoryOnlyKeys] enabled');
diff --git a/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.native.js b/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.native.js
deleted file mode 100644
index 9d08b9db6aa4..000000000000
--- a/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.native.js
+++ /dev/null
@@ -1,6 +0,0 @@
-/**
- * This is a no-op because the global methods will only work for web and desktop
- */
-const exposeGlobalMemoryOnlyKeysMethods = () => {};
-
-export default exposeGlobalMemoryOnlyKeysMethods;
diff --git a/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.native.ts b/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.native.ts
new file mode 100644
index 000000000000..b89e03bdefdc
--- /dev/null
+++ b/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.native.ts
@@ -0,0 +1,8 @@
+import type ExposeGlobalMemoryOnlyKeysMethods from './types';
+
+/**
+ * This is a no-op because the global methods will only work for web and desktop
+ */
+const exposeGlobalMemoryOnlyKeysMethods: ExposeGlobalMemoryOnlyKeysMethods = () => {};
+
+export default exposeGlobalMemoryOnlyKeysMethods;
diff --git a/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.js b/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.ts
similarity index 67%
rename from src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.js
rename to src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.ts
index 1d039c8980a9..4514edacb288 100644
--- a/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.js
+++ b/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/index.ts
@@ -1,6 +1,7 @@
import * as MemoryOnlyKeys from '@userActions/MemoryOnlyKeys/MemoryOnlyKeys';
+import type ExposeGlobalMemoryOnlyKeysMethods from './types';
-const exposeGlobalMemoryOnlyKeysMethods = () => {
+const exposeGlobalMemoryOnlyKeysMethods: ExposeGlobalMemoryOnlyKeysMethods = () => {
window.enableMemoryOnlyKeys = () => {
MemoryOnlyKeys.enable();
};
diff --git a/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/types.ts b/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/types.ts
new file mode 100644
index 000000000000..4cb50041b627
--- /dev/null
+++ b/src/libs/actions/MemoryOnlyKeys/exposeGlobalMemoryOnlyKeysMethods/types.ts
@@ -0,0 +1,3 @@
+type ExposeGlobalMemoryOnlyKeysMethods = () => void;
+
+export default ExposeGlobalMemoryOnlyKeysMethods;
diff --git a/src/libs/actions/OnyxUpdateManager.js b/src/libs/actions/OnyxUpdateManager.ts
similarity index 86%
rename from src/libs/actions/OnyxUpdateManager.js
rename to src/libs/actions/OnyxUpdateManager.ts
index 21cea452295b..ab0dea960b27 100644
--- a/src/libs/actions/OnyxUpdateManager.js
+++ b/src/libs/actions/OnyxUpdateManager.ts
@@ -1,5 +1,4 @@
import Onyx from 'react-native-onyx';
-import _ from 'underscore';
import Log from '@libs/Log';
import * as SequentialQueue from '@libs/Network/SequentialQueue';
import CONST from '@src/CONST';
@@ -22,27 +21,27 @@ import * as OnyxUpdates from './OnyxUpdates';
// The circular dependency happens because this file calls API.GetMissingOnyxUpdates() which uses the SaveResponseInOnyx.js file
// (as a middleware). Therefore, SaveResponseInOnyx.js can't import and use this file directly.
-let lastUpdateIDAppliedToClient = 0;
+let lastUpdateIDAppliedToClient: number | null = 0;
Onyx.connect({
key: ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT,
- callback: (val) => (lastUpdateIDAppliedToClient = val),
+ callback: (value) => (lastUpdateIDAppliedToClient = value),
});
export default () => {
console.debug('[OnyxUpdateManager] Listening for updates from the server');
Onyx.connect({
key: ONYXKEYS.ONYX_UPDATES_FROM_SERVER,
- callback: (val) => {
- if (!val) {
+ callback: (value) => {
+ if (!value) {
return;
}
// Since we used the same key that used to store another object, let's confirm that the current object is
// following the new format before we proceed. If it isn't, then let's clear the object in Onyx.
if (
- !_.isObject(val) ||
- !_.has(val, 'type') ||
- (!(val.type === CONST.ONYX_UPDATE_TYPES.HTTPS && _.has(val, 'request') && _.has(val, 'response')) && !(val.type === CONST.ONYX_UPDATE_TYPES.PUSHER && _.has(val, 'updates')))
+ !(typeof value === 'object' && !!value) ||
+ !('type' in value) ||
+ (!(value.type === CONST.ONYX_UPDATE_TYPES.HTTPS && value.request && value.response) && !(value.type === CONST.ONYX_UPDATE_TYPES.PUSHER && value.updates))
) {
console.debug('[OnyxUpdateManager] Invalid format found for updates, cleaning and unpausing the queue');
Onyx.set(ONYXKEYS.ONYX_UPDATES_FROM_SERVER, null);
@@ -50,9 +49,9 @@ export default () => {
return;
}
- const updateParams = val;
- const lastUpdateIDFromServer = val.lastUpdateID;
- const previousUpdateIDFromServer = val.previousUpdateID;
+ const updateParams = value;
+ const lastUpdateIDFromServer = value.lastUpdateID;
+ const previousUpdateIDFromServer = value.previousUpdateID;
// In cases where we received a previousUpdateID and it doesn't match our lastUpdateIDAppliedToClient
// we need to perform one of the 2 possible cases:
@@ -76,7 +75,7 @@ export default () => {
canUnpauseQueuePromise = App.finalReconnectAppAfterActivatingReliableUpdates();
} else {
// The flow below is setting the promise to a getMissingOnyxUpdates to address flow (2) explained above.
- console.debug(`[OnyxUpdateManager] Client is behind the server by ${previousUpdateIDFromServer - lastUpdateIDAppliedToClient} so fetching incremental updates`);
+ console.debug(`[OnyxUpdateManager] Client is behind the server by ${Number(previousUpdateIDFromServer) - lastUpdateIDAppliedToClient} so fetching incremental updates`);
Log.info('Gap detected in update IDs from server so fetching incremental updates', true, {
lastUpdateIDFromServer,
previousUpdateIDFromServer,
diff --git a/src/libs/actions/OnyxUpdates.ts b/src/libs/actions/OnyxUpdates.ts
index a0772db49585..d89f10ee9c7b 100644
--- a/src/libs/actions/OnyxUpdates.ts
+++ b/src/libs/actions/OnyxUpdates.ts
@@ -44,6 +44,12 @@ function applyHTTPSOnyxUpdates(request: Request, response: Response) {
}
return Promise.resolve();
})
+ .then(() => {
+ if (request.finallyData) {
+ return updateHandler(request.finallyData);
+ }
+ return Promise.resolve();
+ })
.then(() => {
console.debug('[OnyxUpdateManager] Done applying HTTPS update');
return Promise.resolve(response);
@@ -71,6 +77,7 @@ function applyPusherOnyxUpdates(updates: OnyxUpdateEvent[]) {
*/
function apply({lastUpdateID, type, request, response, updates}: Merge): Promise;
function apply({lastUpdateID, type, request, response, updates}: Merge): Promise;
+function apply({lastUpdateID, type, request, response, updates}: OnyxUpdatesFromServer): Promise;
function apply({lastUpdateID, type, request, response, updates}: OnyxUpdatesFromServer): Promise | undefined {
Log.info(`[OnyxUpdateManager] Applying update type: ${type} with lastUpdateID: ${lastUpdateID}`, false, {command: request?.command});
diff --git a/src/libs/actions/PersonalDetails.ts b/src/libs/actions/PersonalDetails.ts
index 0e1662da4d55..508cca34fb88 100644
--- a/src/libs/actions/PersonalDetails.ts
+++ b/src/libs/actions/PersonalDetails.ts
@@ -43,20 +43,19 @@ Onyx.connect({
});
/**
- * Returns the displayName for a user
+ * Creates a new displayName for a user based on passed personal details or login.
*/
-function getDisplayName(login: string, personalDetail: Pick | null): string {
+function createDisplayName(login: string, personalDetails: Pick | OnyxEntry): string {
// If we have a number like +15857527441@expensify.sms then let's remove @expensify.sms and format it
// so that the option looks cleaner in our UI.
const userLogin = LocalePhoneNumber.formatPhoneNumber(login);
- const userDetails = personalDetail ?? allPersonalDetails?.[login];
- if (!userDetails) {
+ if (!personalDetails) {
return userLogin;
}
- const firstName = userDetails.firstName ?? '';
- const lastName = userDetails.lastName ?? '';
+ const firstName = personalDetails.firstName ?? '';
+ const lastName = personalDetails.lastName ?? '';
const fullName = `${firstName} ${lastName}`.trim();
// It's possible for fullName to be empty string, so we must use "||" to fallback to userLogin.
@@ -150,7 +149,7 @@ function updateDisplayName(firstName: string, lastName: string) {
[currentUserAccountID]: {
firstName,
lastName,
- displayName: getDisplayName(currentUserEmail ?? '', {
+ displayName: createDisplayName(currentUserEmail ?? '', {
firstName,
lastName,
}),
@@ -566,7 +565,7 @@ export {
deleteAvatar,
extractFirstAndLastNameFromAvailableDetails,
getCountryISO,
- getDisplayName,
+ createDisplayName,
getPrivatePersonalDetails,
openPersonalDetailsPage,
openPublicProfilePage,
diff --git a/src/libs/actions/Policy.js b/src/libs/actions/Policy.js
index 212fd3ead898..a21b795fa89a 100644
--- a/src/libs/actions/Policy.js
+++ b/src/libs/actions/Policy.js
@@ -1,4 +1,5 @@
import {PUBLIC_DOMAINS} from 'expensify-common/lib/CONST';
+import ExpensiMark from 'expensify-common/lib/ExpensiMark';
import Str from 'expensify-common/lib/str';
import {escapeRegExp} from 'lodash';
import filter from 'lodash/filter';
@@ -616,10 +617,7 @@ function addMembersToWorkspace(invitedEmailsToAccountIDs, welcomeNote, policyID)
const params = {
employees: JSON.stringify(_.map(logins, (login) => ({email: login}))),
-
- // Do not escape HTML special chars for welcomeNote as this will be handled in the backend.
- // See https://github.com/Expensify/App/issues/20081 for more details.
- welcomeNote,
+ welcomeNote: new ExpensiMark().replace(welcomeNote),
policyID,
};
if (!_.isEmpty(membersChats.reportCreationData)) {
@@ -1305,7 +1303,7 @@ function createWorkspace(policyOwnerEmail = '', makeMeAdmin = false, policyName
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${announceChatReportID}`,
value: {
- [_.keys(announceChatData)[0]]: {
+ [announceCreatedReportActionID]: {
pendingAction: null,
},
},
@@ -1324,7 +1322,7 @@ function createWorkspace(policyOwnerEmail = '', makeMeAdmin = false, policyName
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${adminsChatReportID}`,
value: {
- [_.keys(adminsChatData)[0]]: {
+ [adminsCreatedReportActionID]: {
pendingAction: null,
},
},
@@ -1343,7 +1341,7 @@ function createWorkspace(policyOwnerEmail = '', makeMeAdmin = false, policyName
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseChatReportID}`,
value: {
- [_.keys(expenseChatData)[0]]: {
+ [expenseCreatedReportActionID]: {
pendingAction: null,
},
},
diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts
index cef236a3e1bb..55e91834a803 100644
--- a/src/libs/actions/Report.ts
+++ b/src/libs/actions/Report.ts
@@ -369,7 +369,7 @@ function addActions(reportID: string, text = '', file?: File) {
const successReportActions: OnyxCollection> = {};
Object.entries(optimisticReportActions).forEach(([actionKey]) => {
- successReportActions[actionKey] = {pendingAction: null};
+ successReportActions[actionKey] = {pendingAction: null, isOptimisticAction: null};
});
const successData: OnyxUpdate[] = [
@@ -940,6 +940,7 @@ function readNewestAction(reportID: string) {
};
API.write('ReadNewestAction', parameters, {optimisticData});
+ DeviceEventEmitter.emit(`readNewestAction_${reportID}`, lastReadTime);
}
/**
diff --git a/src/libs/actions/ReportActions.ts b/src/libs/actions/ReportActions.ts
index 31f06a5f0372..aad6ae39810a 100644
--- a/src/libs/actions/ReportActions.ts
+++ b/src/libs/actions/ReportActions.ts
@@ -13,7 +13,7 @@ function clearReportActionErrors(reportID: string, reportAction: ReportAction) {
return;
}
- if (reportAction.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD) {
+ if (reportAction.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD || reportAction.isOptimisticAction) {
// Delete the optimistic action
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${originalReportID}`, {
[reportAction.reportActionID]: null,
diff --git a/src/libs/actions/Session/index.ts b/src/libs/actions/Session/index.ts
index 67f531bff505..bde2954e191a 100644
--- a/src/libs/actions/Session/index.ts
+++ b/src/libs/actions/Session/index.ts
@@ -200,16 +200,7 @@ function resendValidateCode(login = credentials.login) {
},
},
];
- const successData: OnyxUpdate[] = [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.ACCOUNT,
- value: {
- loadingForm: null,
- },
- },
- ];
- const failureData: OnyxUpdate[] = [
+ const finallyData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
@@ -225,7 +216,7 @@ function resendValidateCode(login = credentials.login) {
const params: RequestNewValidateCodeParams = {email: login};
- API.write('RequestNewValidateCode', params, {optimisticData, successData, failureData});
+ API.write('RequestNewValidateCode', params, {optimisticData, finallyData});
}
type OnyxData = {
@@ -301,11 +292,11 @@ function beginSignIn(email: string) {
* Given an idToken from Sign in with Apple, checks the API to see if an account
* exists for that email address and signs the user in if so.
*/
-function beginAppleSignIn(idToken: string) {
+function beginAppleSignIn(idToken: string | undefined | null) {
const {optimisticData, successData, failureData} = signInAttemptState();
type BeginAppleSignInParams = {
- idToken: string;
+ idToken: typeof idToken;
preferredLocale: ValueOf | null;
};
@@ -318,11 +309,11 @@ function beginAppleSignIn(idToken: string) {
* Shows Google sign-in process, and if an auth token is successfully obtained,
* passes the token on to the Expensify API to sign in with
*/
-function beginGoogleSignIn(token: string) {
+function beginGoogleSignIn(token: string | null) {
const {optimisticData, successData, failureData} = signInAttemptState();
type BeginGoogleSignInParams = {
- token: string;
+ token: string | null;
preferredLocale: ValueOf | null;
};
diff --git a/src/libs/actions/Task.js b/src/libs/actions/Task.js
index a83a2a42fa68..e46c9fc380cd 100644
--- a/src/libs/actions/Task.js
+++ b/src/libs/actions/Task.js
@@ -191,7 +191,7 @@ function createTaskAndNavigate(parentReportID, title, description, assigneeEmail
successData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`,
- value: {[optimisticAddCommentReport.reportAction.reportActionID]: {pendingAction: null}},
+ value: {[optimisticAddCommentReport.reportAction.reportActionID]: {pendingAction: null, isOptimisticAction: null}},
});
// FOR PARENT REPORT (SHARE DESTINATION)
diff --git a/src/libs/actions/TeachersUnite.js b/src/libs/actions/TeachersUnite.js
deleted file mode 100644
index 98b1f82629a4..000000000000
--- a/src/libs/actions/TeachersUnite.js
+++ /dev/null
@@ -1,180 +0,0 @@
-import lodashGet from 'lodash/get';
-import Onyx from 'react-native-onyx';
-import _ from 'underscore';
-import * as API from '@libs/API';
-import Navigation from '@libs/Navigation/Navigation';
-import * as OptionsListUtils from '@libs/OptionsListUtils';
-import * as ReportUtils from '@libs/ReportUtils';
-import CONST from '@src/CONST';
-import ONYXKEYS from '@src/ONYXKEYS';
-
-let sessionEmail = '';
-let sessionAccountID = 0;
-Onyx.connect({
- key: ONYXKEYS.SESSION,
- callback: (val) => {
- sessionEmail = lodashGet(val, 'email', '');
- sessionAccountID = lodashGet(val, 'accountID', 0);
- },
-});
-
-let allPersonalDetails;
-Onyx.connect({
- key: ONYXKEYS.PERSONAL_DETAILS_LIST,
- callback: (val) => (allPersonalDetails = val),
-});
-
-/**
- * @param {String} partnerUserID
- * @param {String} firstName
- * @param {String} lastName
- */
-function referTeachersUniteVolunteer(partnerUserID, firstName, lastName) {
- const optimisticPublicRoom = ReportUtils.buildOptimisticChatReport([], CONST.TEACHERS_UNITE.PUBLIC_ROOM_NAME, CONST.REPORT.CHAT_TYPE.POLICY_ROOM, CONST.TEACHERS_UNITE.POLICY_ID);
- const optimisticData = [
- {
- onyxMethod: Onyx.METHOD.SET,
- key: `${ONYXKEYS.COLLECTION.REPORT}${optimisticPublicRoom.reportID}`,
- value: {
- ...optimisticPublicRoom,
- reportID: optimisticPublicRoom.reportID,
- policyName: CONST.TEACHERS_UNITE.POLICY_NAME,
- },
- },
- ];
- API.write(
- 'ReferTeachersUniteVolunteer',
- {
- publicRoomReportID: optimisticPublicRoom.reportID,
- firstName,
- lastName,
- partnerUserID,
- },
- {optimisticData},
- );
- Navigation.dismissModal(CONST.TEACHERS_UNITE.PUBLIC_ROOM_ID);
-}
-
-/**
- * Optimistically creates a policyExpenseChat for the school principal and passes data to AddSchoolPrincipal
- * @param {String} firstName
- * @param {String} partnerUserID
- * @param {String} lastName
- */
-function addSchoolPrincipal(firstName, partnerUserID, lastName) {
- const policyName = CONST.TEACHERS_UNITE.POLICY_NAME;
- const policyID = CONST.TEACHERS_UNITE.POLICY_ID;
- const loggedInEmail = OptionsListUtils.addSMSDomainIfPhoneNumber(sessionEmail);
- const reportCreationData = {};
-
- const expenseChatData = ReportUtils.buildOptimisticChatReport([sessionAccountID], '', CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, policyID, sessionAccountID, true, policyName);
- const expenseChatReportID = expenseChatData.reportID;
- const expenseReportCreatedAction = ReportUtils.buildOptimisticCreatedReportAction(sessionEmail);
- const expenseReportActionData = {
- [expenseReportCreatedAction.reportActionID]: expenseReportCreatedAction,
- };
-
- reportCreationData[loggedInEmail] = {
- reportID: expenseChatReportID,
- reportActionID: expenseReportCreatedAction.reportActionID,
- };
-
- API.write(
- 'AddSchoolPrincipal',
- {
- firstName,
- lastName,
- partnerUserID,
- reportCreationData: JSON.stringify(reportCreationData),
- },
- {
- optimisticData: [
- {
- onyxMethod: Onyx.METHOD.SET,
- key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
- value: {
- id: policyID,
- isPolicyExpenseChatEnabled: true,
- type: CONST.POLICY.TYPE.CORPORATE,
- name: policyName,
- role: CONST.POLICY.ROLE.USER,
- owner: sessionEmail,
- outputCurrency: lodashGet(allPersonalDetails, [sessionAccountID, 'localCurrencyCode'], CONST.CURRENCY.USD),
- pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
- },
- },
- {
- onyxMethod: Onyx.METHOD.SET,
- key: `${ONYXKEYS.COLLECTION.POLICY_MEMBERS}${policyID}`,
- value: {
- [sessionAccountID]: {
- role: CONST.POLICY.ROLE.USER,
- errors: {},
- },
- },
- },
- {
- onyxMethod: Onyx.METHOD.SET,
- key: `${ONYXKEYS.COLLECTION.REPORT}${expenseChatReportID}`,
- value: {
- pendingFields: {
- addWorkspaceRoom: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
- },
- ...expenseChatData,
- },
- },
- {
- onyxMethod: Onyx.METHOD.SET,
- key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseChatReportID}`,
- value: expenseReportActionData,
- },
- ],
- successData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
- value: {pendingAction: null},
- },
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: `${ONYXKEYS.COLLECTION.REPORT}${expenseChatReportID}`,
- value: {
- pendingFields: {
- addWorkspaceRoom: null,
- },
- pendingAction: null,
- },
- },
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseChatReportID}`,
- value: {
- [_.keys(expenseChatData)[0]]: {
- pendingAction: null,
- },
- },
- },
- ],
- failureData: [
- {
- onyxMethod: Onyx.METHOD.SET,
- key: `${ONYXKEYS.COLLECTION.POLICY_MEMBERS}${policyID}`,
- value: null,
- },
- {
- onyxMethod: Onyx.METHOD.SET,
- key: `${ONYXKEYS.COLLECTION.REPORT}${expenseChatReportID}`,
- value: null,
- },
- {
- onyxMethod: Onyx.METHOD.SET,
- key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseChatReportID}`,
- value: null,
- },
- ],
- },
- );
- Navigation.dismissModal(expenseChatReportID);
-}
-
-export default {referTeachersUniteVolunteer, addSchoolPrincipal};
diff --git a/src/libs/actions/TeachersUnite.ts b/src/libs/actions/TeachersUnite.ts
new file mode 100644
index 000000000000..14b1a6455349
--- /dev/null
+++ b/src/libs/actions/TeachersUnite.ts
@@ -0,0 +1,200 @@
+import Onyx from 'react-native-onyx';
+import type {OnyxEntry, OnyxUpdate} from 'react-native-onyx';
+import * as API from '@libs/API';
+import Navigation from '@libs/Navigation/Navigation';
+import * as OptionsListUtils from '@libs/OptionsListUtils';
+import * as ReportUtils from '@libs/ReportUtils';
+import type {OptimisticCreatedReportAction} from '@libs/ReportUtils';
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import type {PersonalDetailsList} from '@src/types/onyx';
+
+type CreationData = {
+ reportID: string;
+ reportActionID: string;
+};
+
+type ReportCreationData = Record;
+
+type ExpenseReportActionData = Record;
+
+let sessionEmail = '';
+let sessionAccountID = 0;
+Onyx.connect({
+ key: ONYXKEYS.SESSION,
+ callback: (value) => {
+ sessionEmail = value?.email ?? '';
+ sessionAccountID = value?.accountID ?? 0;
+ },
+});
+
+let allPersonalDetails: OnyxEntry;
+Onyx.connect({
+ key: ONYXKEYS.PERSONAL_DETAILS_LIST,
+ callback: (value) => (allPersonalDetails = value),
+});
+
+/**
+ * @param publicRoomReportID - This is the global reportID for the public room, we'll ignore the optimistic one
+ */
+function referTeachersUniteVolunteer(partnerUserID: string, firstName: string, lastName: string, policyID: string, publicRoomReportID: string) {
+ const optimisticPublicRoom = ReportUtils.buildOptimisticChatReport([], CONST.TEACHERS_UNITE.PUBLIC_ROOM_NAME, CONST.REPORT.CHAT_TYPE.POLICY_ROOM, policyID);
+ const optimisticData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.SET,
+ key: `${ONYXKEYS.COLLECTION.REPORT}${publicRoomReportID}`,
+ value: {
+ ...optimisticPublicRoom,
+ reportID: publicRoomReportID,
+ policyName: CONST.TEACHERS_UNITE.POLICY_NAME,
+ },
+ },
+ ];
+
+ type ReferTeachersUniteVolunteerParams = {
+ reportID: string;
+ firstName: string;
+ lastName: string;
+ partnerUserID: string;
+ };
+
+ const parameters: ReferTeachersUniteVolunteerParams = {
+ reportID: publicRoomReportID,
+ firstName,
+ lastName,
+ partnerUserID,
+ };
+
+ API.write('ReferTeachersUniteVolunteer', parameters, {optimisticData});
+ Navigation.dismissModal(publicRoomReportID);
+}
+
+/**
+ * Optimistically creates a policyExpenseChat for the school principal and passes data to AddSchoolPrincipal
+ */
+function addSchoolPrincipal(firstName: string, partnerUserID: string, lastName: string, policyID: string) {
+ const policyName = CONST.TEACHERS_UNITE.POLICY_NAME;
+ const loggedInEmail = OptionsListUtils.addSMSDomainIfPhoneNumber(sessionEmail);
+ const reportCreationData: ReportCreationData = {};
+
+ const expenseChatData = ReportUtils.buildOptimisticChatReport([sessionAccountID], '', CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, policyID, sessionAccountID, true, policyName);
+ const expenseChatReportID = expenseChatData.reportID;
+ const expenseReportCreatedAction = ReportUtils.buildOptimisticCreatedReportAction(sessionEmail);
+ const expenseReportActionData: ExpenseReportActionData = {
+ [expenseReportCreatedAction.reportActionID]: expenseReportCreatedAction,
+ };
+
+ reportCreationData[loggedInEmail] = {
+ reportID: expenseChatReportID,
+ reportActionID: expenseReportCreatedAction.reportActionID,
+ };
+
+ const optimisticData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.SET,
+ key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
+ value: {
+ id: policyID,
+ isPolicyExpenseChatEnabled: true,
+ areChatRoomsEnabled: true,
+ type: CONST.POLICY.TYPE.CORPORATE,
+ name: policyName,
+ role: CONST.POLICY.ROLE.USER,
+ owner: sessionEmail,
+ outputCurrency: allPersonalDetails?.[sessionAccountID]?.localCurrencyCode ?? CONST.CURRENCY.USD,
+ pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
+ },
+ },
+ {
+ onyxMethod: Onyx.METHOD.SET,
+ key: `${ONYXKEYS.COLLECTION.POLICY_MEMBERS}${policyID}`,
+ value: {
+ [sessionAccountID]: {
+ role: CONST.POLICY.ROLE.USER,
+ errors: {},
+ },
+ },
+ },
+ {
+ onyxMethod: Onyx.METHOD.SET,
+ key: `${ONYXKEYS.COLLECTION.REPORT}${expenseChatReportID}`,
+ value: {
+ pendingFields: {
+ addWorkspaceRoom: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
+ },
+ ...expenseChatData,
+ },
+ },
+ {
+ onyxMethod: Onyx.METHOD.SET,
+ key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseChatReportID}`,
+ value: expenseReportActionData,
+ },
+ ];
+
+ const successData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
+ value: {pendingAction: null},
+ },
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: `${ONYXKEYS.COLLECTION.REPORT}${expenseChatReportID}`,
+ value: {
+ pendingFields: {
+ addWorkspaceRoom: null,
+ },
+ pendingAction: null,
+ },
+ },
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseChatReportID}`,
+ value: {
+ [Object.keys(expenseChatData)[0]]: {
+ pendingAction: null,
+ },
+ },
+ },
+ ];
+
+ const failureData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.SET,
+ key: `${ONYXKEYS.COLLECTION.POLICY_MEMBERS}${policyID}`,
+ value: null,
+ },
+ {
+ onyxMethod: Onyx.METHOD.SET,
+ key: `${ONYXKEYS.COLLECTION.REPORT}${expenseChatReportID}`,
+ value: null,
+ },
+ {
+ onyxMethod: Onyx.METHOD.SET,
+ key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseChatReportID}`,
+ value: null,
+ },
+ ];
+
+ type AddSchoolPrincipalParams = {
+ firstName: string;
+ lastName: string;
+ partnerUserID: string;
+ policyID: string;
+ reportCreationData: string;
+ };
+
+ const parameters: AddSchoolPrincipalParams = {
+ firstName,
+ lastName,
+ partnerUserID,
+ policyID,
+ reportCreationData: JSON.stringify(reportCreationData),
+ };
+
+ API.write('AddSchoolPrincipal', parameters, {optimisticData, successData, failureData});
+ Navigation.dismissModal(expenseChatReportID);
+}
+
+export default {referTeachersUniteVolunteer, addSchoolPrincipal};
diff --git a/src/libs/actions/Transaction.ts b/src/libs/actions/Transaction.ts
index f8bfa5fe78fd..674d0c000656 100644
--- a/src/libs/actions/Transaction.ts
+++ b/src/libs/actions/Transaction.ts
@@ -64,6 +64,7 @@ function saveWaypoint(transactionID: string, index: string, waypoint: RecentWayp
[`waypoint${index}`]: waypoint,
},
},
+ amount: CONST.IOU.DEFAULT_AMOUNT,
// Empty out errors when we're saving a new waypoint as this indicates the user is updating their input
errorFields: {
route: null,
@@ -132,6 +133,7 @@ function removeWaypoint(transaction: Transaction, currentIndex: string, isDraft:
...transaction.comment,
waypoints: reIndexedWaypoints,
},
+ amount: CONST.IOU.DEFAULT_AMOUNT,
};
if (!isRemovedWaypointEmpty) {
@@ -244,7 +246,7 @@ function updateWaypoints(transactionID: string, waypoints: WaypointCollection, i
comment: {
waypoints,
},
-
+ amount: CONST.IOU.DEFAULT_AMOUNT,
// Empty out errors when we're saving new waypoints as this indicates the user is updating their input
errorFields: {
route: null,
diff --git a/src/libs/actions/TransactionEdit.js b/src/libs/actions/TransactionEdit.ts
similarity index 77%
rename from src/libs/actions/TransactionEdit.js
rename to src/libs/actions/TransactionEdit.ts
index 2cb79ac387bd..b1710aa72cbb 100644
--- a/src/libs/actions/TransactionEdit.js
+++ b/src/libs/actions/TransactionEdit.ts
@@ -1,28 +1,32 @@
import Onyx from 'react-native-onyx';
+import type {OnyxEntry} from 'react-native-onyx';
import ONYXKEYS from '@src/ONYXKEYS';
+import type {Transaction} from '@src/types/onyx';
/**
* Makes a backup copy of a transaction object that can be restored when the user cancels editing a transaction.
- *
- * @param {Object} transaction
*/
-function createBackupTransaction(transaction) {
+function createBackupTransaction(transaction: OnyxEntry) {
+ if (!transaction) {
+ return;
+ }
+
const newTransaction = {
...transaction,
};
+
// Use set so that it will always fully overwrite any backup transaction that could have existed before
Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transaction.transactionID}`, newTransaction);
}
/**
* Removes a transaction from Onyx that was only used temporary in the edit flow
- * @param {String} transactionID
*/
-function removeBackupTransaction(transactionID) {
+function removeBackupTransaction(transactionID: string) {
Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transactionID}`, null);
}
-function restoreOriginalTransactionFromBackup(transactionID) {
+function restoreOriginalTransactionFromBackup(transactionID: string) {
const connectionID = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transactionID}`,
callback: (backupTransaction) => {
diff --git a/src/libs/actions/User.js b/src/libs/actions/User.ts
similarity index 62%
rename from src/libs/actions/User.js
rename to src/libs/actions/User.ts
index 67828c766147..8e3bd5f2c017 100644
--- a/src/libs/actions/User.js
+++ b/src/libs/actions/User.ts
@@ -1,7 +1,8 @@
import {isBefore} from 'date-fns';
-import lodashGet from 'lodash/get';
+import type {OnyxCollection, OnyxUpdate} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
-import _ from 'underscore';
+import type {OnyxEntry} from 'react-native-onyx/lib/types';
+import type {ValueOf} from 'type-fest';
import * as API from '@libs/API';
import * as ErrorUtils from '@libs/ErrorUtils';
import Navigation from '@libs/Navigation/Navigation';
@@ -12,80 +13,90 @@ import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
+import type {FrequentlyUsedEmoji} from '@src/types/onyx';
+import type Login from '@src/types/onyx/Login';
+import type {OnyxServerUpdate} from '@src/types/onyx/OnyxUpdatesFromServer';
+import type OnyxPersonalDetails from '@src/types/onyx/PersonalDetails';
+import type {Status} from '@src/types/onyx/PersonalDetails';
+import type ReportAction from '@src/types/onyx/ReportAction';
+import {isEmptyObject} from '@src/types/utils/EmptyObject';
+import type {EmptyObject} from '@src/types/utils/EmptyObject';
import * as Link from './Link';
import * as OnyxUpdates from './OnyxUpdates';
import * as PersonalDetails from './PersonalDetails';
import * as Report from './Report';
import * as Session from './Session';
-let currentUserAccountID = '';
+type BlockedFromConciergeNVP = {expiresAt: number};
+
+let currentUserAccountID = -1;
let currentEmail = '';
Onyx.connect({
key: ONYXKEYS.SESSION,
- callback: (val) => {
- currentUserAccountID = lodashGet(val, 'accountID', -1);
- currentEmail = lodashGet(val, 'email', '');
+ callback: (value) => {
+ currentUserAccountID = value?.accountID ?? -1;
+ currentEmail = value?.email ?? '';
},
});
-let myPersonalDetails = {};
+let myPersonalDetails: OnyxEntry | EmptyObject = {};
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
- callback: (val) => {
- if (!val || !currentUserAccountID) {
+ callback: (value) => {
+ if (!value || currentUserAccountID === -1) {
return;
}
- myPersonalDetails = val[currentUserAccountID];
+ myPersonalDetails = value[currentUserAccountID];
},
});
/**
- * Attempt to close the user's account
- *
- * @param {String} message optional reason for closing account
+ * Attempt to close the user's accountt
*/
-function closeAccount(message) {
+function closeAccount(reason: string) {
// Note: successData does not need to set isLoading to false because if the CloseAccount
// command succeeds, a Pusher response will clear all Onyx data.
- API.write(
- 'CloseAccount',
- {message},
- {
- optimisticData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.FORMS.CLOSE_ACCOUNT_FORM,
- value: {isLoading: true},
- },
- ],
- failureData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.FORMS.CLOSE_ACCOUNT_FORM,
- value: {isLoading: false},
- },
- ],
+
+ const optimisticData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.FORMS.CLOSE_ACCOUNT_FORM,
+ value: {isLoading: true},
},
- );
+ ];
+ const failureData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.FORMS.CLOSE_ACCOUNT_FORM,
+ value: {isLoading: false},
+ },
+ ];
+
+ type CloseAccountParams = {message: string};
+
+ const parameters: CloseAccountParams = {message: reason};
+
+ API.write('CloseAccount', parameters, {
+ optimisticData,
+ failureData,
+ });
}
/**
* Resends a validation link to a given login
- *
- * @param {String} login
*/
-function resendValidateCode(login) {
+function resendValidateCode(login: string) {
Session.resendValidateCode(login);
}
/**
* Requests a new validate code be sent for the passed contact method
*
- * @param {String} contactMethod - the new contact method that the user is trying to verify
+ * @param contactMethod - the new contact method that the user is trying to verify
*/
-function requestContactMethodValidateCode(contactMethod) {
- const optimisticData = [
+function requestContactMethodValidateCode(contactMethod: string) {
+ const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -103,7 +114,7 @@ function requestContactMethodValidateCode(contactMethod) {
},
},
];
- const successData = [
+ const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -117,7 +128,8 @@ function requestContactMethodValidateCode(contactMethod) {
},
},
];
- const failureData = [
+
+ const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -135,55 +147,51 @@ function requestContactMethodValidateCode(contactMethod) {
},
];
- API.write(
- 'RequestContactMethodValidateCode',
- {
- email: contactMethod,
- },
- {optimisticData, successData, failureData},
- );
+ type RequestContactMethodValidateCodeParams = {email: string};
+
+ const parameters: RequestContactMethodValidateCodeParams = {email: contactMethod};
+
+ API.write('RequestContactMethodValidateCode', parameters, {optimisticData, successData, failureData});
}
/**
- * Sets whether or not the user is subscribed to Expensify news
- *
- * @param {Boolean} isSubscribed
+ * Sets whether the user is subscribed to Expensify news
*/
-function updateNewsletterSubscription(isSubscribed) {
- API.write(
- 'UpdateNewsletterSubscription',
+function updateNewsletterSubscription(isSubscribed: boolean) {
+ const optimisticData: OnyxUpdate[] = [
{
- isSubscribed,
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.USER,
+ value: {isSubscribedToNewsletter: isSubscribed},
},
+ ];
+ const failureData: OnyxUpdate[] = [
{
- optimisticData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.USER,
- value: {isSubscribedToNewsletter: isSubscribed},
- },
- ],
- failureData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.USER,
- value: {isSubscribedToNewsletter: !isSubscribed},
- },
- ],
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.USER,
+ value: {isSubscribedToNewsletter: !isSubscribed},
},
- );
+ ];
+
+ type UpdateNewsletterSubscriptionParams = {isSubscribed: boolean};
+
+ const parameters: UpdateNewsletterSubscriptionParams = {isSubscribed};
+
+ API.write('UpdateNewsletterSubscription', parameters, {
+ optimisticData,
+ failureData,
+ });
}
/**
* Delete a specific contact method
- *
- * @param {String} contactMethod - the contact method being deleted
- * @param {Array} loginList
+ * @param contactMethod - the contact method being deleted
+ * @param loginList
*/
-function deleteContactMethod(contactMethod, loginList) {
+function deleteContactMethod(contactMethod: string, loginList: Record) {
const oldLoginData = loginList[contactMethod];
- const optimisticData = [
+ const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -200,7 +208,7 @@ function deleteContactMethod(contactMethod, loginList) {
},
},
];
- const successData = [
+ const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -209,7 +217,7 @@ function deleteContactMethod(contactMethod, loginList) {
},
},
];
- const failureData = [
+ const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -227,23 +235,18 @@ function deleteContactMethod(contactMethod, loginList) {
},
];
- API.write(
- 'DeleteContactMethod',
- {
- partnerUserID: contactMethod,
- },
- {optimisticData, successData, failureData},
- );
+ type DeleteContactMethodParams = {partnerUserID: string};
+
+ const parameters: DeleteContactMethodParams = {partnerUserID: contactMethod};
+
+ API.write('DeleteContactMethod', parameters, {optimisticData, successData, failureData});
Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.route);
}
/**
* Clears any possible stored errors for a specific field on a contact method
- *
- * @param {String} contactMethod
- * @param {String} fieldName
*/
-function clearContactMethodErrors(contactMethod, fieldName) {
+function clearContactMethodErrors(contactMethod: string, fieldName: string) {
Onyx.merge(ONYXKEYS.LOGIN_LIST, {
[contactMethod]: {
errorFields: {
@@ -259,9 +262,9 @@ function clearContactMethodErrors(contactMethod, fieldName) {
/**
* Resets the state indicating whether a validation code has been sent to a specific contact method.
*
- * @param {String} contactMethod - The identifier of the contact method to reset.
+ * @param contactMethod - The identifier of the contact method to reset.
*/
-function resetContactMethodValidateCodeSentState(contactMethod) {
+function resetContactMethodValidateCodeSentState(contactMethod: string) {
Onyx.merge(ONYXKEYS.LOGIN_LIST, {
[contactMethod]: {
validateCodeSent: false,
@@ -271,11 +274,9 @@ function resetContactMethodValidateCodeSentState(contactMethod) {
/**
* Adds a secondary login to a user's account
- *
- * @param {String} contactMethod
*/
-function addNewContactMethodAndNavigate(contactMethod) {
- const optimisticData = [
+function addNewContactMethodAndNavigate(contactMethod: string) {
+ const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -293,7 +294,7 @@ function addNewContactMethodAndNavigate(contactMethod) {
},
},
];
- const successData = [
+ const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -306,7 +307,7 @@ function addNewContactMethodAndNavigate(contactMethod) {
},
},
];
- const failureData = [
+ const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -323,20 +324,21 @@ function addNewContactMethodAndNavigate(contactMethod) {
},
];
- API.write('AddNewContactMethod', {partnerUserID: contactMethod}, {optimisticData, successData, failureData});
+ type AddNewContactMethodParams = {partnerUserID: string};
+
+ const parameters: AddNewContactMethodParams = {partnerUserID: contactMethod};
+
+ API.write('AddNewContactMethod', parameters, {optimisticData, successData, failureData});
Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.route);
}
/**
* Validates a login given an accountID and validation code
- *
- * @param {Number} accountID
- * @param {String} validateCode
*/
-function validateLogin(accountID, validateCode) {
+function validateLogin(accountID: number, validateCode: string) {
Onyx.merge(ONYXKEYS.ACCOUNT, {...CONST.DEFAULT_ACCOUNT_DATA, isLoading: true});
- const optimisticData = [
+ const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
@@ -345,25 +347,23 @@ function validateLogin(accountID, validateCode) {
},
},
];
- API.write(
- 'ValidateLogin',
- {
- accountID,
- validateCode,
- },
- {optimisticData},
- );
+
+ type ValidateLoginParams = {
+ accountID: number;
+ validateCode: string;
+ };
+
+ const parameters: ValidateLoginParams = {accountID, validateCode};
+
+ API.write('ValidateLogin', parameters, {optimisticData});
Navigation.navigate(ROUTES.HOME);
}
/**
* Validates a secondary login / contact method
- *
- * @param {String} contactMethod - The contact method the user is trying to verify
- * @param {String} validateCode
*/
-function validateSecondaryLogin(contactMethod, validateCode) {
- const optimisticData = [
+function validateSecondaryLogin(contactMethod: string, validateCode: string) {
+ const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -388,7 +388,7 @@ function validateSecondaryLogin(contactMethod, validateCode) {
},
},
];
- const successData = [
+ const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -409,7 +409,8 @@ function validateSecondaryLogin(contactMethod, validateCode) {
value: {isLoading: false},
},
];
- const failureData = [
+
+ const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -432,47 +433,40 @@ function validateSecondaryLogin(contactMethod, validateCode) {
},
];
- API.write(
- 'ValidateSecondaryLogin',
- {
- partnerUserID: contactMethod,
- validateCode,
- },
- {optimisticData, successData, failureData},
- );
+ type ValidateSecondaryLoginParams = {partnerUserID: string; validateCode: string};
+
+ const parameters: ValidateSecondaryLoginParams = {partnerUserID: contactMethod, validateCode};
+
+ API.write('ValidateSecondaryLogin', parameters, {optimisticData, successData, failureData});
}
/**
* Checks the blockedFromConcierge object to see if it has an expiresAt key,
* and if so whether the expiresAt date of a user's ban is before right now
*
- * @param {Object} blockedFromConciergeNVP
- * @returns {Boolean}
*/
-function isBlockedFromConcierge(blockedFromConciergeNVP) {
- if (_.isEmpty(blockedFromConciergeNVP)) {
+function isBlockedFromConcierge(blockedFromConciergeNVP: OnyxEntry): boolean {
+ if (isEmptyObject(blockedFromConciergeNVP)) {
return false;
}
- if (!blockedFromConciergeNVP.expiresAt) {
+ if (!blockedFromConciergeNVP?.expiresAt) {
return false;
}
return isBefore(new Date(), new Date(blockedFromConciergeNVP.expiresAt));
}
-function triggerNotifications(onyxUpdates) {
- _.each(onyxUpdates, (update) => {
+function triggerNotifications(onyxUpdates: OnyxServerUpdate[]) {
+ onyxUpdates.forEach((update) => {
if (!update.shouldNotify) {
return;
}
const reportID = update.key.replace(ONYXKEYS.COLLECTION.REPORT_ACTIONS, '');
- const reportActions = _.values(update.value);
+ const reportActions = Object.values((update.value as OnyxCollection) ?? {});
- // eslint-disable-next-line rulesdir/no-negated-variables
- const notifiableActions = _.filter(reportActions, (action) => ReportActionsUtils.isNotifiableReportAction(action));
- _.each(notifiableActions, (action) => Report.showReportActionNotification(reportID, action));
+ reportActions.forEach((action) => action && ReportActionsUtils.isNotifiableReportAction(action) && Report.showReportActionNotification(reportID, action));
});
}
@@ -482,13 +476,13 @@ function triggerNotifications(onyxUpdates) {
*/
function subscribeToUserEvents() {
// If we don't have the user's accountID yet (because the app isn't fully setup yet) we can't subscribe so return early
- if (!currentUserAccountID) {
+ if (currentUserAccountID === -1) {
return;
}
// Handles the mega multipleEvents from Pusher which contains an array of single events.
// Each single event is passed to PusherUtils in order to trigger the callbacks for that event
- PusherUtils.subscribeToPrivateUserChannelEvent(Pusher.TYPE.MULTIPLE_EVENTS, currentUserAccountID, (pushJSON) => {
+ PusherUtils.subscribeToPrivateUserChannelEvent(Pusher.TYPE.MULTIPLE_EVENTS, currentUserAccountID.toString(), (pushJSON) => {
// The data for this push event comes in two different formats:
// 1. Original format - this is what was sent before the RELIABLE_UPDATES project and will go away once RELIABLE_UPDATES is fully complete
// - The data is an array of objects, where each object is an onyx update
@@ -496,8 +490,8 @@ function subscribeToUserEvents() {
// 1. Reliable updates format - this is what was sent with the RELIABLE_UPDATES project and will be the format from now on
// - The data is an object, containing updateIDs from the server and an array of onyx updates (this array is the same format as the original format above)
// Example: {lastUpdateID: 1, previousUpdateID: 0, updates: [{onyxMethod: 'whatever', key: 'foo', value: 'bar'}]}
- if (_.isArray(pushJSON)) {
- _.each(pushJSON, (multipleEvent) => {
+ if (Array.isArray(pushJSON)) {
+ pushJSON.forEach((multipleEvent) => {
PusherUtils.triggerMultiEventHandler(multipleEvent.eventType, multipleEvent.data);
});
return;
@@ -506,7 +500,7 @@ function subscribeToUserEvents() {
const updates = {
type: CONST.ONYX_UPDATE_TYPES.PUSHER,
lastUpdateID: Number(pushJSON.lastUpdateID || 0),
- updates: pushJSON.updates,
+ updates: pushJSON.updates ?? [],
previousUpdateID: Number(pushJSON.previousUpdateID || 0),
};
if (!OnyxUpdates.doesClientNeedToBeUpdated(Number(pushJSON.previousUpdateID || 0))) {
@@ -520,10 +514,10 @@ function subscribeToUserEvents() {
});
// Handles Onyx updates coming from Pusher through the mega multipleEvents.
- PusherUtils.subscribeToMultiEvent(Pusher.TYPE.MULTIPLE_EVENT_TYPE.ONYX_API_UPDATE, (pushJSON) =>
+ PusherUtils.subscribeToMultiEvent(Pusher.TYPE.MULTIPLE_EVENT_TYPE.ONYX_API_UPDATE, (pushJSON: OnyxServerUpdate[]) =>
SequentialQueue.getCurrentRequest().then(() => {
// If we don't have the currentUserAccountID (user is logged out) we don't want to update Onyx with data from Pusher
- if (!currentUserAccountID) {
+ if (currentUserAccountID === -1) {
return;
}
@@ -540,54 +534,51 @@ function subscribeToUserEvents() {
/**
* Sync preferredSkinTone with Onyx and Server
- * @param {Number} skinTone
*/
-function updatePreferredSkinTone(skinTone) {
- const optimisticData = [
+function updatePreferredSkinTone(skinTone: number) {
+ const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.SET,
key: ONYXKEYS.PREFERRED_EMOJI_SKIN_TONE,
value: skinTone,
},
];
- API.write(
- 'UpdatePreferredEmojiSkinTone',
- {
- value: skinTone,
- },
- {optimisticData},
- );
+
+ type UpdatePreferredEmojiSkinToneParams = {
+ value: number;
+ };
+
+ const parameters: UpdatePreferredEmojiSkinToneParams = {value: skinTone};
+
+ API.write('UpdatePreferredEmojiSkinTone', parameters, {optimisticData});
}
/**
* Sync frequentlyUsedEmojis with Onyx and Server
- * @param {Object[]} frequentlyUsedEmojis
*/
-function updateFrequentlyUsedEmojis(frequentlyUsedEmojis) {
- const optimisticData = [
+function updateFrequentlyUsedEmojis(frequentlyUsedEmojis: FrequentlyUsedEmoji[]) {
+ const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.SET,
key: ONYXKEYS.FREQUENTLY_USED_EMOJIS,
value: frequentlyUsedEmojis,
},
];
- API.write(
- 'UpdateFrequentlyUsedEmojis',
- {
- value: JSON.stringify(frequentlyUsedEmojis),
- },
- {optimisticData},
- );
+ type UpdateFrequentlyUsedEmojisParams = {value: string};
+
+ const parameters: UpdateFrequentlyUsedEmojisParams = {value: JSON.stringify(frequentlyUsedEmojis)};
+
+ API.write('UpdateFrequentlyUsedEmojis', parameters, {optimisticData});
}
/**
* Sync user chat priority mode with Onyx and Server
- * @param {String} mode
- * @param {boolean} [automatic] if we changed the mode automatically
+ * @param mode
+ * @param [automatic] if we changed the mode automatically
*/
-function updateChatPriorityMode(mode, automatic = false) {
+function updateChatPriorityMode(mode: ValueOf, automatic = false) {
const autoSwitchedToFocusMode = mode === CONST.PRIORITY_MODE.GSD && automatic;
- const optimisticData = [
+ const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.NVP_PRIORITY_MODE,
@@ -603,14 +594,17 @@ function updateChatPriorityMode(mode, automatic = false) {
});
}
- API.write(
- 'UpdateChatPriorityMode',
- {
- value: mode,
- automatic,
- },
- {optimisticData},
- );
+ type UpdateChatPriorityModeParams = {
+ value: ValueOf;
+ automatic: boolean;
+ };
+
+ const parameters: UpdateChatPriorityModeParams = {
+ value: mode,
+ automatic,
+ };
+
+ API.write('UpdateChatPriorityMode', parameters, {optimisticData});
if (!autoSwitchedToFocusMode) {
Navigation.goBack(ROUTES.SETTINGS_PREFERENCES);
@@ -621,10 +615,7 @@ function clearFocusModeNotification() {
Onyx.set(ONYXKEYS.FOCUS_MODE_NOTIFICATION, false);
}
-/**
- * @param {Boolean} shouldUseStagingServer
- */
-function setShouldUseStagingServer(shouldUseStagingServer) {
+function setShouldUseStagingServer(shouldUseStagingServer: boolean) {
Onyx.merge(ONYXKEYS.USER, {shouldUseStagingServer});
}
@@ -641,62 +632,64 @@ function clearScreenShareRequest() {
/**
* Open an OldDot tab linking to a screen share request.
- * @param {String} accessToken Access token required to join a screen share room, generated by the backend
- * @param {String} roomName Name of the screen share room to join
+ * @param accessToken Access token required to join a screen share room, generated by the backend
+ * @param roomName Name of the screen share room to join
*/
-function joinScreenShare(accessToken, roomName) {
+function joinScreenShare(accessToken: string, roomName: string) {
Link.openOldDotLink(`inbox?action=screenShare&accessToken=${accessToken}&name=${roomName}`);
clearScreenShareRequest();
}
/**
* Downloads the statement PDF for the provided period
- * @param {String} period YYYYMM format
+ * @param period YYYYMM format
*/
-function generateStatementPDF(period) {
- API.read(
- 'GetStatementPDF',
- {period},
- {
- optimisticData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.WALLET_STATEMENT,
- value: {
- isGenerating: true,
- },
- },
- ],
- successData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.WALLET_STATEMENT,
- value: {
- isGenerating: false,
- },
- },
- ],
- failureData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.WALLET_STATEMENT,
- value: {
- isGenerating: false,
- },
- },
- ],
+function generateStatementPDF(period: string) {
+ const optimisticData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.WALLET_STATEMENT,
+ value: {
+ isGenerating: true,
+ },
},
- );
+ ];
+ const successData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.WALLET_STATEMENT,
+ value: {
+ isGenerating: false,
+ },
+ },
+ ];
+ const failureData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.WALLET_STATEMENT,
+ value: {
+ isGenerating: false,
+ },
+ },
+ ];
+
+ type GetStatementPDFParams = {period: string};
+
+ const parameters: GetStatementPDFParams = {period};
+
+ API.read('GetStatementPDF', parameters, {
+ optimisticData,
+ successData,
+ failureData,
+ });
}
/**
* Sets a contact method / secondary login as the user's "Default" contact method.
- *
- * @param {String} newDefaultContactMethod
*/
-function setContactMethodAsDefault(newDefaultContactMethod) {
+function setContactMethodAsDefault(newDefaultContactMethod: string) {
const oldDefaultContactMethod = currentEmail;
- const optimisticData = [
+ const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.SESSION,
@@ -724,12 +717,12 @@ function setContactMethodAsDefault(newDefaultContactMethod) {
value: {
[currentUserAccountID]: {
login: newDefaultContactMethod,
- displayName: PersonalDetails.getDisplayName(newDefaultContactMethod, myPersonalDetails),
+ displayName: PersonalDetails.createDisplayName(newDefaultContactMethod, myPersonalDetails),
},
},
},
];
- const successData = [
+ const successData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGIN_LIST,
@@ -742,7 +735,7 @@ function setContactMethodAsDefault(newDefaultContactMethod) {
},
},
];
- const failureData = [
+ const failureData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.SESSION,
@@ -772,15 +765,25 @@ function setContactMethodAsDefault(newDefaultContactMethod) {
},
},
];
- API.write('SetContactMethodAsDefault', {partnerUserID: newDefaultContactMethod}, {optimisticData, successData, failureData});
+
+ type SetContactMethodAsDefaultParams = {
+ partnerUserID: string;
+ };
+
+ const parameters: SetContactMethodAsDefaultParams = {
+ partnerUserID: newDefaultContactMethod,
+ };
+
+ API.write('SetContactMethodAsDefault', parameters, {
+ optimisticData,
+ successData,
+ failureData,
+ });
Navigation.goBack(ROUTES.SETTINGS_CONTACT_METHODS.route);
}
-/**
- * @param {String} theme
- */
-function updateTheme(theme) {
- const optimisticData = [
+function updateTheme(theme: ValueOf) {
+ const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.SET,
key: ONYXKEYS.PREFERRED_THEME,
@@ -788,37 +791,45 @@ function updateTheme(theme) {
},
];
- API.write(
- 'UpdateTheme',
- {
- value: theme,
- },
- {optimisticData},
- );
+ type UpdateThemeParams = {
+ value: string;
+ };
+
+ const parameters: UpdateThemeParams = {
+ value: theme,
+ };
+
+ API.write('UpdateTheme', parameters, {optimisticData});
Navigation.navigate(ROUTES.SETTINGS_PREFERENCES);
}
/**
* Sets a custom status
- *
- * @param {Object} status
- * @param {String} status.text
- * @param {String} status.emojiCode
*/
-function updateCustomStatus(status) {
- API.write('UpdateStatus', status, {
- optimisticData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.PERSONAL_DETAILS_LIST,
- value: {
- [currentUserAccountID]: {
- status,
- },
+function updateCustomStatus(status: Status) {
+ const optimisticData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.PERSONAL_DETAILS_LIST,
+ value: {
+ [currentUserAccountID]: {
+ status,
},
},
- ],
+ },
+ ];
+
+ type UpdateStatusParams = {
+ text?: string;
+ emojiCode: string;
+ clearAfter?: string;
+ };
+
+ const parameters: UpdateStatusParams = {text: status.text, emojiCode: status.emojiCode, clearAfter: status.clearAfter};
+
+ API.write('UpdateStatus', parameters, {
+ optimisticData,
});
}
@@ -826,39 +837,38 @@ function updateCustomStatus(status) {
* Clears the custom status
*/
function clearCustomStatus() {
- API.write('ClearStatus', undefined, {
- optimisticData: [
- {
- onyxMethod: Onyx.METHOD.MERGE,
- key: ONYXKEYS.PERSONAL_DETAILS_LIST,
- value: {
- [currentUserAccountID]: {
- status: null, // Clearing the field
- },
+ const optimisticData: OnyxUpdate[] = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: ONYXKEYS.PERSONAL_DETAILS_LIST,
+ value: {
+ [currentUserAccountID]: {
+ status: null, // Clearing the field
},
},
- ],
+ },
+ ];
+ API.write('ClearStatus', undefined, {
+ optimisticData,
});
}
/**
* Sets a custom status
*
- * @param {Object} status
- * @param {String} status.text
- * @param {String} status.emojiCode
- * @param {String} status.clearAfter - ISO 8601 format string, which represents the time when the status should be cleared
+ * @param status.text
+ * @param status.emojiCode
+ * @param status.clearAfter - ISO 8601 format string, which represents the time when the status should be cleared
*/
-function updateDraftCustomStatus(status) {
+function updateDraftCustomStatus(status: Status) {
Onyx.merge(ONYXKEYS.CUSTOM_STATUS_DRAFT, status);
}
/**
* Clear the custom draft status
- *
*/
function clearDraftCustomStatus() {
- Onyx.merge(ONYXKEYS.CUSTOM_STATUS_DRAFT, {text: '', emojiCode: '', clearAfter: '', customDateTemporary: ''});
+ Onyx.merge(ONYXKEYS.CUSTOM_STATUS_DRAFT, {text: '', emojiCode: '', clearAfter: ''});
}
export {
diff --git a/src/libs/mapChildrenFlat.ts b/src/libs/mapChildrenFlat.ts
new file mode 100644
index 000000000000..238e57d47a83
--- /dev/null
+++ b/src/libs/mapChildrenFlat.ts
@@ -0,0 +1,27 @@
+import React from 'react';
+
+/**
+ * Maps over the children of a React component and extracts the result of the mapping if there is only one child.
+ *
+ * @param children The children to map over.
+ * @param fn The callback to run for each child.
+ * @returns The flattened result of mapping over the children.
+ *
+ * @example
+ * // Usage example:
+ * const result = mapChildrenFlat(children, (child, index) => {
+ * // Your mapping logic here
+ * return modifiedChild;
+ * });
+ */
+const mapChildrenFlat = (...args: Parameters>) => {
+ const mappedChildren = React.Children.map(...args);
+
+ if (Array.isArray(mappedChildren) && mappedChildren.length === 1) {
+ return mappedChildren[0];
+ }
+
+ return mappedChildren;
+};
+
+export default mapChildrenFlat;
diff --git a/src/libs/mergeRefs.ts b/src/libs/mergeRefs.ts
new file mode 100644
index 000000000000..d4f342d17ca4
--- /dev/null
+++ b/src/libs/mergeRefs.ts
@@ -0,0 +1,18 @@
+import type {LegacyRef, MutableRefObject, RefCallback} from 'react';
+
+/**
+ * Assigns element reference to multiple refs.
+ * @param refs The ref object or function arguments.
+ */
+export default function mergeRefs(...refs: Array | LegacyRef | undefined | null>): RefCallback {
+ return (value) => {
+ refs.forEach((ref) => {
+ if (typeof ref === 'function') {
+ ref(value);
+ } else if (ref != null) {
+ // eslint-disable-next-line no-param-reassign
+ (ref as MutableRefObject).current = value;
+ }
+ });
+ };
+}
diff --git a/src/pages/DetailsPage.js b/src/pages/DetailsPage.js
index 2fdab08e6675..f215b4167ab6 100755
--- a/src/pages/DetailsPage.js
+++ b/src/pages/DetailsPage.js
@@ -1,4 +1,3 @@
-import {parsePhoneNumber} from 'awesome-phonenumber';
import Str from 'expensify-common/lib/str';
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
@@ -23,6 +22,7 @@ import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import compose from '@libs/compose';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
+import {parsePhoneNumber} from '@libs/PhoneNumber';
import * as ReportUtils from '@libs/ReportUtils';
import * as UserUtils from '@libs/UserUtils';
import * as Report from '@userActions/Report';
diff --git a/src/pages/EditRequestMerchantPage.js b/src/pages/EditRequestMerchantPage.js
index c8766d9acc67..e5966bad2d2b 100644
--- a/src/pages/EditRequestMerchantPage.js
+++ b/src/pages/EditRequestMerchantPage.js
@@ -27,7 +27,7 @@ function EditRequestMerchantPage({defaultMerchant, onSubmit, isPolicyExpenseChat
const styles = useThemeStyles();
const {translate} = useLocalize();
const merchantInputRef = useRef(null);
- const isEmptyMerchant = defaultMerchant === '' || defaultMerchant === CONST.TRANSACTION.UNKNOWN_MERCHANT || defaultMerchant === CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT;
+ const isEmptyMerchant = defaultMerchant === '' || defaultMerchant === CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT;
const validate = useCallback(
(value) => {
diff --git a/src/pages/EditRequestPage.js b/src/pages/EditRequestPage.js
index bc05c110ab2f..fe43d96001a0 100644
--- a/src/pages/EditRequestPage.js
+++ b/src/pages/EditRequestPage.js
@@ -145,6 +145,24 @@ function EditRequestPage({report, route, policyCategories, policyTags, parentRep
[transaction, report],
);
+ const saveMerchant = useCallback(
+ ({merchant: newMerchant}) => {
+ const newTrimmedMerchant = newMerchant.trim();
+
+ // In case the merchant hasn't been changed, do not make the API request.
+ // In case the merchant has been set to empty string while current merchant is partial, do nothing too.
+ if (newTrimmedMerchant === transactionMerchant || (newTrimmedMerchant === '' && transactionMerchant === CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT)) {
+ Navigation.dismissModal();
+ return;
+ }
+
+ // An empty newTrimmedMerchant is only possible for the P2P IOU case
+ IOU.updateMoneyRequestMerchant(transaction.transactionID, report.reportID, newTrimmedMerchant || CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT);
+ Navigation.dismissModal();
+ },
+ [transactionMerchant, transaction, report],
+ );
+
const saveTag = useCallback(
({tag: newTag}) => {
let updatedTag = newTag;
@@ -203,23 +221,7 @@ function EditRequestPage({report, route, policyCategories, policyTags, parentRep
{
- const newTrimmedMerchant = transactionChanges.merchant.trim();
-
- // In case the merchant hasn't been changed, do not make the API request.
- // In case the merchant has been set to empty string while current merchant is partial, do nothing too.
- if (newTrimmedMerchant === transactionMerchant || (newTrimmedMerchant === '' && transactionMerchant === CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT)) {
- Navigation.dismissModal();
- return;
- }
-
- // This is possible only in case of IOU requests.
- if (newTrimmedMerchant === '') {
- editMoneyRequest({merchant: CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT});
- return;
- }
- editMoneyRequest({merchant: newTrimmedMerchant});
- }}
+ onSubmit={saveMerchant}
/>
);
}
diff --git a/src/pages/EditRequestReceiptPage.js b/src/pages/EditRequestReceiptPage.js
index 1525ec162963..40fe64da7eed 100644
--- a/src/pages/EditRequestReceiptPage.js
+++ b/src/pages/EditRequestReceiptPage.js
@@ -7,7 +7,7 @@ import ScreenWrapper from '@components/ScreenWrapper';
import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import Navigation from '@libs/Navigation/Navigation';
-import ReceiptSelector from './iou/ReceiptSelector';
+import IOURequestStepScan from './iou/request/step/IOURequestStepScan';
const propTypes = {
/** React Navigation route */
@@ -21,16 +21,9 @@ const propTypes = {
reportID: PropTypes.string,
}),
}).isRequired,
-
- /** The id of the transaction we're editing */
- transactionID: PropTypes.string,
-};
-
-const defaultProps = {
- transactionID: '',
};
-function EditRequestReceiptPage({route, transactionID}) {
+function EditRequestReceiptPage({route}) {
const styles = useThemeStyles();
const {translate} = useLocalize();
const [isDraggingOver, setIsDraggingOver] = useState(false);
@@ -49,11 +42,7 @@ function EditRequestReceiptPage({route, transactionID}) {
title={translate('common.receipt')}
onBackButtonPress={Navigation.goBack}
/>
-
+
)}
@@ -62,7 +51,6 @@ function EditRequestReceiptPage({route, transactionID}) {
}
EditRequestReceiptPage.propTypes = propTypes;
-EditRequestReceiptPage.defaultProps = defaultProps;
EditRequestReceiptPage.displayName = 'EditRequestReceiptPage';
export default EditRequestReceiptPage;
diff --git a/src/pages/EnablePayments/AdditionalDetailsStep.js b/src/pages/EnablePayments/AdditionalDetailsStep.js
index d6f21f3ecdca..faa525a318ab 100644
--- a/src/pages/EnablePayments/AdditionalDetailsStep.js
+++ b/src/pages/EnablePayments/AdditionalDetailsStep.js
@@ -1,4 +1,3 @@
-import {parsePhoneNumber} from 'awesome-phonenumber';
import {subYears} from 'date-fns';
import PropTypes from 'prop-types';
import React from 'react';
@@ -17,6 +16,7 @@ import withCurrentUserPersonalDetails, {withCurrentUserPersonalDetailsDefaultPro
import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import compose from '@libs/compose';
+import {parsePhoneNumber} from '@libs/PhoneNumber';
import * as ValidationUtils from '@libs/ValidationUtils';
import AddressForm from '@pages/ReimbursementAccount/AddressForm';
import * as PersonalDetails from '@userActions/PersonalDetails';
@@ -87,7 +87,7 @@ function AdditionalDetailsStep({walletAdditionalDetails, translate, currentUserP
const shouldAskForFullSSN = walletAdditionalDetails.errorCode === CONST.WALLET.ERROR.SSN;
/**
- * @param {Object} values The values object is passed from Form.js and contains info for each form element that has an inputID
+ * @param {Object} values The values object is passed from FormProvider and contains info for each form element that has an inputID
* @returns {Object}
*/
const validate = (values) => {
@@ -128,7 +128,7 @@ function AdditionalDetailsStep({walletAdditionalDetails, translate, currentUserP
};
/**
- * @param {Object} values The values object is passed from Form.js and contains info for each form element that has an inputID
+ * @param {Object} values The values object is passed from FormProvider and contains info for each form element that has an inputID
*/
const activateWallet = (values) => {
const personalDetails = {
diff --git a/src/pages/FlagCommentPage.js b/src/pages/FlagCommentPage.js
index 6c6421593837..47d2ad356dad 100644
--- a/src/pages/FlagCommentPage.js
+++ b/src/pages/FlagCommentPage.js
@@ -13,7 +13,6 @@ import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import compose from '@libs/compose';
import Navigation from '@libs/Navigation/Navigation';
-import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as Report from '@userActions/Report';
import * as Session from '@userActions/Session';
@@ -43,10 +42,15 @@ const propTypes = {
}).isRequired,
...withLocalizePropTypes,
+
+ /* Onyx Props */
+ /** All the report actions from the parent report */
+ parentReportActions: PropTypes.objectOf(PropTypes.shape(reportActionPropTypes)),
};
const defaultProps = {
reportActions: {},
+ parentReportActions: {},
report: {},
};
@@ -120,18 +124,19 @@ function FlagCommentPage(props) {
// Handle threads if needed
if (reportAction === undefined || reportAction.reportActionID === undefined) {
- reportAction = ReportActionsUtils.getParentReportAction(props.report);
+ reportAction = props.parentReportActions[props.report.parentReportActionID] || {};
}
return reportAction;
- }, [props.report, props.reportActions, props.route.params.reportActionID]);
+ }, [props.report, props.reportActions, props.route.params.reportActionID, props.parentReportActions]);
const flagComment = (severity) => {
let reportID = getReportID(props.route);
const reportAction = getActionToFlag();
+ const parentReportAction = props.parentReportActions[props.report.parentReportActionID] || {};
// Handle threads if needed
- if (ReportUtils.isChatThread(props.report) && reportAction.reportActionID === ReportActionsUtils.getParentReportAction(props.report).reportActionID) {
+ if (ReportUtils.isChatThread(props.report) && reportAction.reportActionID === parentReportAction.reportActionID) {
reportID = ReportUtils.getParentReport(props.report).reportID;
}
diff --git a/src/pages/LoadingPage.js b/src/pages/LoadingPage.js
new file mode 100644
index 000000000000..fc315495619a
--- /dev/null
+++ b/src/pages/LoadingPage.js
@@ -0,0 +1,36 @@
+import PropTypes from 'prop-types';
+import React from 'react';
+import FullScreenLoadingIndicator from '@components/FullscreenLoadingIndicator';
+import HeaderWithBackButton from '@components/HeaderWithBackButton';
+import ScreenWrapper from '@components/ScreenWrapper';
+import useThemeStyles from '@hooks/useThemeStyles';
+
+const propTypes = {
+ /** Method to trigger when pressing back button of the header */
+ onBackButtonPress: PropTypes.func,
+ title: PropTypes.string.isRequired,
+};
+
+const defaultProps = {
+ onBackButtonPress: undefined,
+};
+
+function LoadingPage(props) {
+ const styles = useThemeStyles();
+ return (
+
+
+
+
+ );
+}
+
+LoadingPage.displayName = 'LoadingPage';
+LoadingPage.propTypes = propTypes;
+LoadingPage.defaultProps = defaultProps;
+
+export default LoadingPage;
diff --git a/src/pages/LogInWithShortLivedAuthTokenPage.js b/src/pages/LogInWithShortLivedAuthTokenPage.js
index 2c5184f5c162..1fe9b67eef16 100644
--- a/src/pages/LogInWithShortLivedAuthTokenPage.js
+++ b/src/pages/LogInWithShortLivedAuthTokenPage.js
@@ -89,7 +89,6 @@ function LogInWithShortLivedAuthTokenPage(props) {
diff --git a/src/pages/NewChatPage.js b/src/pages/NewChatPage.js
index d7abbab6e93f..3a58727eddb7 100755
--- a/src/pages/NewChatPage.js
+++ b/src/pages/NewChatPage.js
@@ -1,6 +1,6 @@
import PropTypes from 'prop-types';
import React, {useCallback, useEffect, useMemo, useState} from 'react';
-import {View} from 'react-native';
+import {InteractionManager, View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import KeyboardAvoidingView from '@components/KeyboardAvoidingView';
@@ -13,10 +13,9 @@ import useAutoFocusInput from '@hooks/useAutoFocusInput';
import useNetwork from '@hooks/useNetwork';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
-import * as Browser from '@libs/Browser';
import compose from '@libs/compose';
+import * as DeviceCapabilities from '@libs/DeviceCapabilities';
import * as OptionsListUtils from '@libs/OptionsListUtils';
-import Permissions from '@libs/Permissions';
import * as ReportUtils from '@libs/ReportUtils';
import variables from '@styles/variables';
import * as Report from '@userActions/Report';
@@ -61,6 +60,7 @@ function NewChatPage({betas, isGroupChat, personalDetails, reports, translate, i
const [selectedOptions, setSelectedOptions] = useState([]);
const {isOffline} = useNetwork();
const {isSmallScreenWidth} = useWindowDimensions();
+ const [didScreenTransitionEnd, setDidScreenTransitionEnd] = useState(false);
const maxParticipantsReached = selectedOptions.length === CONST.REPORT.MAXIMUM_PARTICIPANTS;
const headerMessage = OptionsListUtils.getHeaderMessage(
@@ -116,7 +116,7 @@ function NewChatPage({betas, isGroupChat, personalDetails, reports, translate, i
* Removes a selected option from list if already selected. If not already selected add this option to the list.
* @param {Object} option
*/
- function toggleOption(option) {
+ const toggleOption = (option) => {
const isOptionInList = _.some(selectedOptions, (selectedOption) => selectedOption.login === option.login);
let newSelectedOptions;
@@ -154,7 +154,7 @@ function NewChatPage({betas, isGroupChat, personalDetails, reports, translate, i
setFilteredRecentReports(recentReports);
setFilteredPersonalDetails(newChatPersonalDetails);
setFilteredUserToInvite(userToInvite);
- }
+ };
/**
* Creates a new 1:1 chat with the option and the current user,
@@ -162,9 +162,9 @@ function NewChatPage({betas, isGroupChat, personalDetails, reports, translate, i
*
* @param {Object} option
*/
- function createChat(option) {
+ const createChat = (option) => {
Report.navigateToAndOpenReport([option.login]);
- }
+ };
/**
* Creates a new group chat with all the selected options and the current user,
@@ -178,7 +178,7 @@ function NewChatPage({betas, isGroupChat, personalDetails, reports, translate, i
Report.navigateToAndOpenReport(logins);
};
- useEffect(() => {
+ const updateOptions = useCallback(() => {
const {
recentReports,
personalDetails: newChatPersonalDetails,
@@ -208,6 +208,21 @@ function NewChatPage({betas, isGroupChat, personalDetails, reports, translate, i
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reports, personalDetails, searchTerm]);
+ useEffect(() => {
+ const interactionTask = InteractionManager.runAfterInteractions(() => {
+ setDidScreenTransitionEnd(true);
+ });
+
+ return interactionTask.cancel;
+ }, []);
+
+ useEffect(() => {
+ if (!didScreenTransitionEnd) {
+ return;
+ }
+ updateOptions();
+ }, [didScreenTransitionEnd, updateOptions]);
+
// When search term updates we will fetch any reports
const setSearchTermAndSearchInServer = useCallback((text = '') => {
Report.searchInServer(text);
@@ -231,9 +246,7 @@ function NewChatPage({betas, isGroupChat, personalDetails, reports, translate, i
behavior="padding"
// Offset is needed as KeyboardAvoidingView in nested inside of TabNavigator instead of wrapping whole screen.
// This is because when wrapping whole screen the screen was freezing when changing Tabs.
- keyboardVerticalOffset={
- variables.contentHeaderHeight + insets.top + (Permissions.canUsePolicyRooms(betas) ? variables.tabSelectorButtonHeight + variables.tabSelectorButtonPadding : 0)
- }
+ keyboardVerticalOffset={variables.contentHeaderHeight + insets.top + variables.tabSelectorButtonHeight + variables.tabSelectorButtonPadding}
>
0 ? safeAreaPaddingBottomStyle : {}]}>
toggleOption(option)}
+ onAddToSelection={toggleOption}
sections={sections}
selectedOptions={selectedOptions}
- onSelectRow={(option) => createChat(option)}
+ onSelectRow={createChat}
onChangeText={setSearchTermAndSearchInServer}
headerMessage={headerMessage}
boldStyle
- shouldPreventDefaultFocusOnSelectRow={!Browser.isMobile()}
- shouldShowOptions={isOptionsDataReady}
+ shouldPreventDefaultFocusOnSelectRow={!DeviceCapabilities.canUseTouchScreen()}
+ shouldShowOptions={isOptionsDataReady && didScreenTransitionEnd}
shouldShowConfirmButton
shouldShowReferralCTA
referralContentType={CONST.REFERRAL_PROGRAM.CONTENT_TYPES.START_CHAT}
diff --git a/src/pages/NewChatSelectorPage.js b/src/pages/NewChatSelectorPage.js
index e8d392dcb477..ba64ffec5a96 100755
--- a/src/pages/NewChatSelectorPage.js
+++ b/src/pages/NewChatSelectorPage.js
@@ -7,7 +7,6 @@ import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import withWindowDimensions, {windowDimensionsPropTypes} from '@components/withWindowDimensions';
import compose from '@libs/compose';
import OnyxTabNavigator, {TopTab} from '@libs/Navigation/OnyxTabNavigator';
-import Permissions from '@libs/Permissions';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import NewChatPage from './NewChatPage';
@@ -35,29 +34,25 @@ function NewChatSelectorPage(props) {
testID={NewChatSelectorPage.displayName}
>
- {Permissions.canUsePolicyRooms(props.betas) ? (
- (
-
- )}
- >
- (
+
-
-
- ) : (
-
- )}
+ )}
+ >
+
+
+
);
}
diff --git a/src/pages/PrivateNotes/PrivateNotesEditPage.js b/src/pages/PrivateNotes/PrivateNotesEditPage.js
index c62fbe3edcb5..0d4bc2c3e7e1 100644
--- a/src/pages/PrivateNotes/PrivateNotesEditPage.js
+++ b/src/pages/PrivateNotes/PrivateNotesEditPage.js
@@ -182,7 +182,7 @@ PrivateNotesEditPage.defaultProps = defaultProps;
export default compose(
withLocalize,
- withReportAndPrivateNotesOrNotFound,
+ withReportAndPrivateNotesOrNotFound('privateNotes.title'),
withOnyx({
personalDetailsList: {
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
diff --git a/src/pages/PrivateNotes/PrivateNotesListPage.js b/src/pages/PrivateNotes/PrivateNotesListPage.js
index a34eb0ce596d..8e2f8c9f43e0 100644
--- a/src/pages/PrivateNotes/PrivateNotesListPage.js
+++ b/src/pages/PrivateNotes/PrivateNotesListPage.js
@@ -144,7 +144,7 @@ PrivateNotesListPage.displayName = 'PrivateNotesListPage';
export default compose(
withLocalize,
- withReportAndPrivateNotesOrNotFound,
+ withReportAndPrivateNotesOrNotFound('privateNotes.title'),
withOnyx({
personalDetailsList: {
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
diff --git a/src/pages/PrivateNotes/PrivateNotesViewPage.js b/src/pages/PrivateNotes/PrivateNotesViewPage.js
index 1406dfd76748..f71259a2b685 100644
--- a/src/pages/PrivateNotes/PrivateNotesViewPage.js
+++ b/src/pages/PrivateNotes/PrivateNotesViewPage.js
@@ -103,7 +103,7 @@ PrivateNotesViewPage.defaultProps = defaultProps;
export default compose(
withLocalize,
- withReportAndPrivateNotesOrNotFound,
+ withReportAndPrivateNotesOrNotFound('privateNotes.title'),
withOnyx({
personalDetailsList: {
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
diff --git a/src/pages/ProfilePage.js b/src/pages/ProfilePage.js
index 0618f0ad2a9d..c0c782f176ca 100755
--- a/src/pages/ProfilePage.js
+++ b/src/pages/ProfilePage.js
@@ -1,4 +1,3 @@
-import {parsePhoneNumber} from 'awesome-phonenumber';
import Str from 'expensify-common/lib/str';
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
@@ -27,6 +26,7 @@ import useThemeStyles from '@hooks/useThemeStyles';
import compose from '@libs/compose';
import Navigation from '@libs/Navigation/Navigation';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
+import {parsePhoneNumber} from '@libs/PhoneNumber';
import * as ReportUtils from '@libs/ReportUtils';
import * as UserUtils from '@libs/UserUtils';
import * as ValidationUtils from '@libs/ValidationUtils';
@@ -134,7 +134,8 @@ function ProfilePage(props) {
const navigateBackTo = lodashGet(props.route, 'params.backTo', ROUTES.HOME);
- const notificationPreference = !_.isEmpty(props.report) ? props.translate(`notificationPreferencesPage.notificationPreferences.${props.report.notificationPreference}`) : '';
+ const shouldShowNotificationPreference = !_.isEmpty(props.report) && props.report.notificationPreference !== CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN;
+ const notificationPreference = shouldShowNotificationPreference ? props.translate(`notificationPreferencesPage.notificationPreferences.${props.report.notificationPreference}`) : '';
// eslint-disable-next-line rulesdir/prefer-early-return
useEffect(() => {
@@ -227,7 +228,7 @@ function ProfilePage(props) {
) : null}
{shouldShowLocalTime && }
- {!_.isEmpty(props.report) && notificationPreference !== CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN && (
+ {shouldShowNotificationPreference && (
{
const accountID = lodashGet(option, 'accountID', null);
const isOptionInPersonalDetails = _.some(personalDetails, (personalDetail) => personalDetail.accountID === accountID);
-
- const isPartOfSearchTerm = option.text.toLowerCase().includes(searchTerm.trim().toLowerCase());
+ const parsedPhoneNumber = parsePhoneNumber(LoginUtils.appendCountryCode(Str.removeSMSDomain(searchTerm)));
+ const searchValue = parsedPhoneNumber.possible ? parsedPhoneNumber.number.e164 : searchTerm.toLowerCase();
+ const isPartOfSearchTerm = option.text.toLowerCase().includes(searchValue) || option.login.toLowerCase().includes(searchValue);
return isPartOfSearchTerm || isOptionInPersonalDetails;
});
}
@@ -230,7 +234,7 @@ function RoomInvitePage(props) {
onSelectRow={toggleOption}
onConfirm={inviteUsers}
showScrollIndicator
- shouldPreventDefaultFocusOnSelectRow={!Browser.isMobile()}
+ shouldPreventDefaultFocusOnSelectRow={!DeviceCapabilities.canUseTouchScreen()}
showLoadingPlaceholder={!didScreenTransitionEnd || !OptionsListUtils.isPersonalDetailsReady(props.personalDetails)}
/>
diff --git a/src/pages/RoomMembersPage.js b/src/pages/RoomMembersPage.js
index 67228e574de6..a8c600a91845 100644
--- a/src/pages/RoomMembersPage.js
+++ b/src/pages/RoomMembersPage.js
@@ -14,8 +14,8 @@ import withCurrentUserPersonalDetails, {withCurrentUserPersonalDetailsDefaultPro
import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import withWindowDimensions, {windowDimensionsPropTypes} from '@components/withWindowDimensions';
import useThemeStyles from '@hooks/useThemeStyles';
-import * as Browser from '@libs/Browser';
import compose from '@libs/compose';
+import * as DeviceCapabilities from '@libs/DeviceCapabilities';
import Log from '@libs/Log';
import Navigation from '@libs/Navigation/Navigation';
import * as OptionsListUtils from '@libs/OptionsListUtils';
@@ -289,7 +289,7 @@ function RoomMembersPage(props) {
onSelectAll={() => toggleAllUsers(data)}
showLoadingPlaceholder={!OptionsListUtils.isPersonalDetailsReady(personalDetails) || !didLoadRoomMembers}
showScrollIndicator
- shouldPreventDefaultFocusOnSelectRow={!Browser.isMobile()}
+ shouldPreventDefaultFocusOnSelectRow={!DeviceCapabilities.canUseTouchScreen()}
/>
diff --git a/src/pages/SearchPage/SearchPageFooter.tsx b/src/pages/SearchPage/SearchPageFooter.tsx
new file mode 100644
index 000000000000..69429962869b
--- /dev/null
+++ b/src/pages/SearchPage/SearchPageFooter.tsx
@@ -0,0 +1,59 @@
+import React from 'react';
+import {View} from 'react-native';
+import Icon from '@components/Icon';
+import {Info} from '@components/Icon/Expensicons';
+import {PressableWithoutFeedback} from '@components/Pressable';
+import Text from '@components/Text';
+import useLocalize from '@hooks/useLocalize';
+import useTheme from '@hooks/useTheme';
+import useThemeStyles from '@hooks/useThemeStyles';
+import Navigation from '@libs/Navigation/Navigation';
+import CONST from '@src/CONST';
+import ROUTES from '@src/ROUTES';
+
+function SearchPageFooter() {
+ const themeStyles = useThemeStyles();
+ const theme = useTheme();
+ const {translate} = useLocalize();
+
+ return (
+
+ {
+ Navigation.navigate(ROUTES.REFERRAL_DETAILS_MODAL.getRoute(CONST.REFERRAL_PROGRAM.CONTENT_TYPES.REFER_FRIEND));
+ }}
+ style={[
+ themeStyles.p5,
+ themeStyles.w100,
+ themeStyles.br2,
+ themeStyles.highlightBG,
+ themeStyles.flexRow,
+ themeStyles.justifyContentBetween,
+ themeStyles.alignItemsCenter,
+ {gap: 10},
+ ]}
+ accessibilityLabel="referral"
+ role={CONST.ACCESSIBILITY_ROLE.BUTTON}
+ >
+
+ {translate(`referralProgram.${CONST.REFERRAL_PROGRAM.CONTENT_TYPES.REFER_FRIEND}.buttonText1`)}
+
+ {translate(`referralProgram.${CONST.REFERRAL_PROGRAM.CONTENT_TYPES.REFER_FRIEND}.buttonText2`)}
+
+
+
+
+
+ );
+}
+
+SearchPageFooter.displayName = 'SearchPageFooter';
+
+export default SearchPageFooter;
diff --git a/src/pages/SearchPage/index.js b/src/pages/SearchPage/index.js
new file mode 100644
index 000000000000..211f3622e06c
--- /dev/null
+++ b/src/pages/SearchPage/index.js
@@ -0,0 +1,183 @@
+import PropTypes from 'prop-types';
+import React, {useEffect, useMemo, useState} from 'react';
+import {View} from 'react-native';
+import {withOnyx} from 'react-native-onyx';
+import HeaderWithBackButton from '@components/HeaderWithBackButton';
+import {usePersonalDetails} from '@components/OnyxProvider';
+import ScreenWrapper from '@components/ScreenWrapper';
+import SelectionList from '@components/SelectionList';
+import useDebouncedState from '@hooks/useDebouncedState';
+import useLocalize from '@hooks/useLocalize';
+import useNetwork from '@hooks/useNetwork';
+import useThemeStyles from '@hooks/useThemeStyles';
+import Navigation from '@libs/Navigation/Navigation';
+import * as OptionsListUtils from '@libs/OptionsListUtils';
+import Performance from '@libs/Performance';
+import * as ReportUtils from '@libs/ReportUtils';
+import reportPropTypes from '@pages/reportPropTypes';
+import * as Report from '@userActions/Report';
+import Timing from '@userActions/Timing';
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import SearchPageFooter from './SearchPageFooter';
+
+const propTypes = {
+ /* Onyx Props */
+
+ /** Beta features list */
+ betas: PropTypes.arrayOf(PropTypes.string),
+
+ /** All reports shared with the user */
+ reports: PropTypes.objectOf(reportPropTypes),
+};
+
+const defaultProps = {
+ betas: [],
+ reports: {},
+};
+
+const setPerformanceTimersEnd = () => {
+ Timing.end(CONST.TIMING.SEARCH_RENDER);
+ Performance.markEnd(CONST.TIMING.SEARCH_RENDER);
+};
+
+const SearchPageFooterInstance = ;
+
+function SearchPage({betas, reports}) {
+ const [isScreenTransitionEnd, setIsScreenTransitionEnd] = useState(false);
+ const {translate} = useLocalize();
+ const {isOffline} = useNetwork();
+ const themeStyles = useThemeStyles();
+ const personalDetails = usePersonalDetails();
+
+ const offlineMessage = isOffline ? `${translate('common.youAppearToBeOffline')} ${translate('search.resultsAreLimited')}` : '';
+
+ const [searchValue, debouncedSearchValue, setSearchValue] = useDebouncedState('');
+
+ useEffect(() => {
+ Timing.start(CONST.TIMING.SEARCH_RENDER);
+ Performance.markStart(CONST.TIMING.SEARCH_RENDER);
+ }, []);
+
+ const onChangeText = (text = '') => {
+ Report.searchInServer(text);
+ setSearchValue(text);
+ };
+
+ const {
+ recentReports,
+ personalDetails: localPersonalDetails,
+ userToInvite,
+ headerMessage,
+ } = useMemo(() => {
+ if (!isScreenTransitionEnd) {
+ return {
+ recentReports: {},
+ personalDetails: {},
+ userToInvite: {},
+ headerMessage: '',
+ };
+ }
+ const options = OptionsListUtils.getSearchOptions(reports, personalDetails, debouncedSearchValue.trim(), betas);
+ const header = OptionsListUtils.getHeaderMessage(options.recentReports.length + options.personalDetails.length !== 0, Boolean(options.userToInvite), debouncedSearchValue);
+ return {...options, headerMessage: header};
+ }, [debouncedSearchValue, reports, personalDetails, betas, isScreenTransitionEnd]);
+
+ const sections = useMemo(() => {
+ const newSections = [];
+ let indexOffset = 0;
+
+ if (recentReports.length > 0) {
+ newSections.push({
+ data: recentReports,
+ shouldShow: true,
+ indexOffset,
+ });
+ indexOffset += recentReports.length;
+ }
+
+ if (localPersonalDetails.length > 0) {
+ newSections.push({
+ data: localPersonalDetails,
+ shouldShow: true,
+ indexOffset,
+ });
+ indexOffset += recentReports.length;
+ }
+
+ if (userToInvite) {
+ newSections.push({
+ data: [userToInvite],
+ shouldShow: true,
+ indexOffset,
+ });
+ }
+
+ return newSections;
+ }, [localPersonalDetails, recentReports, userToInvite]);
+
+ const selectReport = (option) => {
+ if (!option) {
+ return;
+ }
+
+ if (option.reportID) {
+ setSearchValue('');
+ Navigation.dismissModal(option.reportID);
+ } else {
+ Report.navigateToAndOpenReport([option.login]);
+ }
+ };
+
+ const handleScreenTransitionEnd = () => {
+ setIsScreenTransitionEnd(true);
+ };
+
+ const isOptionsDataReady = useMemo(() => ReportUtils.isReportDataReady() && OptionsListUtils.isPersonalDetailsReady(personalDetails), [personalDetails]);
+
+ return (
+
+ {({didScreenTransitionEnd, safeAreaPaddingBottomStyle}) => (
+ <>
+
+
+
+
+ >
+ )}
+
+ );
+}
+
+SearchPage.propTypes = propTypes;
+SearchPage.defaultProps = defaultProps;
+SearchPage.displayName = 'SearchPage';
+
+export default withOnyx({
+ reports: {
+ key: ONYXKEYS.COLLECTION.REPORT,
+ },
+ betas: {
+ key: ONYXKEYS.BETAS,
+ },
+ isSearchingForReports: {
+ key: ONYXKEYS.IS_SEARCHING_FOR_REPORTS,
+ initWithStoredValues: false,
+ },
+})(SearchPage);
diff --git a/src/pages/TeachersUnite/IntroSchoolPrincipalPage.js b/src/pages/TeachersUnite/IntroSchoolPrincipalPage.js
index 3b4edb3240e5..e0715da9e5ef 100644
--- a/src/pages/TeachersUnite/IntroSchoolPrincipalPage.js
+++ b/src/pages/TeachersUnite/IntroSchoolPrincipalPage.js
@@ -11,6 +11,7 @@ import HeaderWithBackButton from '@components/HeaderWithBackButton';
import ScreenWrapper from '@components/ScreenWrapper';
import Text from '@components/Text';
import TextInput from '@components/TextInput';
+import useEnvironment from '@hooks/useEnvironment';
import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import * as ErrorUtils from '@libs/ErrorUtils';
@@ -37,6 +38,7 @@ const defaultProps = {
function IntroSchoolPrincipalPage(props) {
const styles = useThemeStyles();
const {translate} = useLocalize();
+ const {isProduction} = useEnvironment();
/**
* @param {Object} values
@@ -45,7 +47,8 @@ function IntroSchoolPrincipalPage(props) {
* @param {String} values.lastName
*/
const onSubmit = (values) => {
- TeachersUnite.addSchoolPrincipal(values.firstName.trim(), values.partnerUserID.trim(), values.lastName.trim());
+ const policyID = isProduction ? CONST.TEACHERS_UNITE.PROD_POLICY_ID : CONST.TEACHERS_UNITE.TEST_POLICY_ID;
+ TeachersUnite.addSchoolPrincipal(values.firstName.trim(), values.partnerUserID.trim(), values.lastName.trim(), policyID);
};
/**
diff --git a/src/pages/TeachersUnite/KnowATeacherPage.js b/src/pages/TeachersUnite/KnowATeacherPage.js
index 61e03017b7ea..5b8c9455ba38 100644
--- a/src/pages/TeachersUnite/KnowATeacherPage.js
+++ b/src/pages/TeachersUnite/KnowATeacherPage.js
@@ -11,6 +11,7 @@ import HeaderWithBackButton from '@components/HeaderWithBackButton';
import ScreenWrapper from '@components/ScreenWrapper';
import Text from '@components/Text';
import TextInput from '@components/TextInput';
+import useEnvironment from '@hooks/useEnvironment';
import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import * as ErrorUtils from '@libs/ErrorUtils';
@@ -37,6 +38,7 @@ const defaultProps = {
function KnowATeacherPage(props) {
const styles = useThemeStyles();
const {translate} = useLocalize();
+ const {isProduction} = useEnvironment();
/**
* Submit form to pass firstName, partnerUserID and lastName
@@ -52,7 +54,9 @@ function KnowATeacherPage(props) {
const firstName = values.firstName.trim();
const lastName = values.lastName.trim();
- TeachersUnite.referTeachersUniteVolunteer(contactMethod, firstName, lastName);
+ const policyID = isProduction ? CONST.TEACHERS_UNITE.PROD_POLICY_ID : CONST.TEACHERS_UNITE.TEST_POLICY_ID;
+ const publicRoomReportID = isProduction ? CONST.TEACHERS_UNITE.PROD_PUBLIC_ROOM_ID : CONST.TEACHERS_UNITE.TEST_PUBLIC_ROOM_ID;
+ TeachersUnite.referTeachersUniteVolunteer(contactMethod, firstName, lastName, policyID, publicRoomReportID);
};
/**
diff --git a/src/pages/TeachersUnite/SaveTheWorldPage.js b/src/pages/TeachersUnite/SaveTheWorldPage.js
index 36e03f0b4716..107c0e39b6a0 100644
--- a/src/pages/TeachersUnite/SaveTheWorldPage.js
+++ b/src/pages/TeachersUnite/SaveTheWorldPage.js
@@ -1,8 +1,5 @@
-import _ from 'lodash';
-import PropTypes from 'prop-types';
import React from 'react';
import {View} from 'react-native';
-import {withOnyx} from 'react-native-onyx';
import IllustratedHeaderPageLayout from '@components/IllustratedHeaderPageLayout';
import LottieAnimations from '@components/LottieAnimations';
import MenuItem from '@components/MenuItem';
@@ -11,28 +8,13 @@ import useLocalize from '@hooks/useLocalize';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import Navigation from '@libs/Navigation/Navigation';
-import CONST from '@src/CONST';
-import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import SCREENS from '@src/SCREENS';
-const propTypes = {
- /** The list of this user's policies */
- policy: PropTypes.shape({
- /** The user's role in the policy */
- role: PropTypes.string,
- }),
-};
-
-const defaultProps = {
- policy: {},
-};
-
-function SaveTheWorldPage(props) {
+function SaveTheWorldPage() {
const theme = useTheme();
const styles = useThemeStyles();
const {translate} = useLocalize();
- const isTeacherAlreadyInvited = !_.isUndefined(props.policy) && props.policy.role === CONST.POLICY.ROLE.USER;
return (
Navigation.navigate(ROUTES.I_KNOW_A_TEACHER)}
/>
- {!isTeacherAlreadyInvited && (
- Navigation.navigate(ROUTES.I_AM_A_TEACHER)}
- />
- )}
+ Navigation.navigate(ROUTES.I_AM_A_TEACHER)}
+ />
);
}
-SaveTheWorldPage.propTypes = propTypes;
-SaveTheWorldPage.defaultProps = defaultProps;
SaveTheWorldPage.displayName = 'SaveTheWorldPage';
-
-export default withOnyx({
- policy: {
- key: () => `${ONYXKEYS.COLLECTION.POLICY}${CONST.TEACHERS_UNITE.POLICY_ID}`,
- },
-})(SaveTheWorldPage);
+export default SaveTheWorldPage;
diff --git a/src/pages/home/ReportScreen.js b/src/pages/home/ReportScreen.js
index 8e177e0c2e64..64e48ecd5509 100644
--- a/src/pages/home/ReportScreen.js
+++ b/src/pages/home/ReportScreen.js
@@ -11,6 +11,7 @@ import DragAndDropProvider from '@components/DragAndDrop/Provider';
import MoneyReportHeader from '@components/MoneyReportHeader';
import MoneyRequestHeader from '@components/MoneyRequestHeader';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
+import {usePersonalDetails} from '@components/OnyxProvider';
import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView';
import ScreenWrapper from '@components/ScreenWrapper';
import TaskHeaderActionButton from '@components/TaskHeaderActionButton';
@@ -18,7 +19,6 @@ import withCurrentReportID, {withCurrentReportIDDefaultProps, withCurrentReportI
import withViewportOffsetTop from '@components/withViewportOffsetTop';
import useAppFocusEvent from '@hooks/useAppFocusEvent';
import useLocalize from '@hooks/useLocalize';
-import useNetwork from '@hooks/useNetwork';
import usePrevious from '@hooks/usePrevious';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
@@ -35,6 +35,7 @@ import reportMetadataPropTypes from '@pages/reportMetadataPropTypes';
import reportPropTypes from '@pages/reportPropTypes';
import * as ComposerActions from '@userActions/Composer';
import * as Report from '@userActions/Report';
+import * as Task from '@userActions/Task';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
@@ -66,8 +67,11 @@ const propTypes = {
/** The report metadata loading states */
reportMetadata: reportMetadataPropTypes,
- /** Array of report actions for this report */
- reportActions: PropTypes.arrayOf(PropTypes.shape(reportActionPropTypes)),
+ /** All the report actions for this report */
+ reportActions: PropTypes.objectOf(PropTypes.shape(reportActionPropTypes)),
+
+ /** The report's parentReportAction */
+ parentReportAction: PropTypes.shape(reportActionPropTypes),
/** Whether the composer is full size */
isComposerFullSize: PropTypes.bool,
@@ -104,7 +108,8 @@ const propTypes = {
const defaultProps = {
isSidebarLoaded: false,
- reportActions: [],
+ reportActions: {},
+ parentReportAction: {},
report: {},
reportMetadata: {
isLoadingInitialReportActions: true,
@@ -144,6 +149,7 @@ function ReportScreen({
report,
reportMetadata,
reportActions,
+ parentReportAction,
accountManagerReportID,
personalDetails,
markReadyForHydration,
@@ -159,7 +165,6 @@ function ReportScreen({
const styles = useThemeStyles();
const {translate} = useLocalize();
const {isSmallScreenWidth} = useWindowDimensions();
- const {isOffline} = useNetwork();
const firstRenderRef = useRef(true);
const flatListRef = useRef();
@@ -180,23 +185,13 @@ function ReportScreen({
const {addWorkspaceRoomOrChatPendingAction, addWorkspaceRoomOrChatErrors} = ReportUtils.getReportOfflinePendingActionAndErrors(report);
const screenWrapperStyle = [styles.appContent, styles.flex1, {marginTop: viewportOffsetTop}];
- // eslint-disable-next-line react-hooks/exhaustive-deps -- need to re-filter the report actions when network status changes
- const filteredReportActions = useMemo(() => ReportActionsUtils.getSortedReportActionsForDisplay(reportActions, true), [isOffline, reportActions]);
-
// There are no reportActions at all to display and we are still in the process of loading the next set of actions.
- const isLoadingInitialReportActions = _.isEmpty(filteredReportActions) && reportMetadata.isLoadingInitialReportActions;
-
+ const isLoadingInitialReportActions = _.isEmpty(reportActions) && reportMetadata.isLoadingInitialReportActions;
const isOptimisticDelete = lodashGet(report, 'statusNum') === CONST.REPORT.STATUS.CLOSED;
-
const shouldHideReport = !ReportUtils.canAccessReport(report, policies, betas);
-
const isLoading = !reportID || !isSidebarLoaded || _.isEmpty(personalDetails);
-
- const parentReportAction = ReportActionsUtils.getParentReportAction(report);
const isSingleTransactionView = ReportUtils.isMoneyRequest(report);
-
const policy = policies[`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`] || {};
-
const isTopMostReportId = currentReportID === getReportID(route);
const didSubscribeToReportLeavingEvents = useRef(false);
@@ -239,7 +234,6 @@ function ReportScreen({
policy={policy}
personalDetails={personalDetails}
isSingleTransactionView={isSingleTransactionView}
- parentReportAction={parentReportAction}
/>
);
}
@@ -292,21 +286,52 @@ function ReportScreen({
Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(accountManagerReportID));
}, [accountManagerReportID]);
+ const allPersonalDetails = usePersonalDetails();
+
+ /**
+ * @param {String} text
+ */
+ const handleCreateTask = useCallback(
+ (text) => {
+ /**
+ * Matching task rule by group
+ * Group 1: Start task rule with []
+ * Group 2: Optional email group between \s+....\s* start rule with @+valid email
+ * Group 3: Title is remaining characters
+ */
+ const taskRegex = /^\[\]\s+(?:@([^\s@]+@[\w.-]+\.[a-zA-Z]{2,}))?\s*([\s\S]*)/;
+
+ const match = text.match(taskRegex);
+ if (!match) {
+ return false;
+ }
+ const title = match[2] ? match[2].trim().replace(/\n/g, ' ') : undefined;
+ if (!title) {
+ return false;
+ }
+ const email = match[1] ? match[1].trim() : undefined;
+ let assignee = {};
+ if (email) {
+ assignee = _.find(_.values(allPersonalDetails), (p) => p.login === email) || {};
+ }
+ Task.createTaskAndNavigate(getReportID(route), title, '', assignee.login, assignee.accountID, assignee.assigneeChatReport, report.policyID);
+ return true;
+ },
+ [allPersonalDetails, report.policyID, route],
+ );
+
/**
* @param {String} text
*/
const onSubmitComment = useCallback(
(text) => {
+ const isTaskCreated = handleCreateTask(text);
+ if (isTaskCreated) {
+ return;
+ }
Report.addComment(getReportID(route), text);
-
- // We need to scroll to the bottom of the list after the comment is added
- const refID = setTimeout(() => {
- flatListRef.current.scrollToOffset({animated: false, offset: 0});
- }, 10);
-
- return () => clearTimeout(refID);
},
- [route],
+ [route, handleCreateTask],
);
// Clear notifications for the current report when it's opened and re-focused
@@ -491,7 +516,7 @@ function ReportScreen({
>
{isReportReadyForDisplay && !isLoadingInitialReportActions && !isLoading && (
`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getReportID(route)}`,
canEvict: false,
+ selector: (reportActions) => ReportActionsUtils.getSortedReportActionsForDisplay(reportActions, true),
},
report: {
key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT}${getReportID(route)}`,
@@ -580,6 +606,17 @@ export default compose(
key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT_USER_IS_LEAVING_ROOM}${getReportID(route)}`,
initialValue: false,
},
+ parentReportAction: {
+ key: ({report}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report ? report.parentReportID : 0}`,
+ selector: (parentReportActions, props) => {
+ const parentReportActionID = lodashGet(props, 'report.parentReportActionID');
+ if (!parentReportActionID) {
+ return {};
+ }
+ return parentReportActions[parentReportActionID];
+ },
+ canEvict: false,
+ },
},
true,
),
diff --git a/src/pages/home/report/ContextMenu/ContextMenuActions.js b/src/pages/home/report/ContextMenu/ContextMenuActions.js
index b2e74a2b7cbf..f22eda58ce7f 100644
--- a/src/pages/home/report/ContextMenu/ContextMenuActions.js
+++ b/src/pages/home/report/ContextMenu/ContextMenuActions.js
@@ -161,12 +161,14 @@ export default [
const isActionCreator = ReportUtils.isActionCreator(reportAction);
childReportNotificationPreference = isActionCreator ? CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS : CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN;
}
+ const isDeletedAction = ReportActionsUtils.isDeletedAction(reportAction);
+ const shouldDisplayThreadReplies = ReportUtils.shouldDisplayThreadReplies(reportAction, reportID);
const subscribed = childReportNotificationPreference !== 'hidden';
const isCommentAction = reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT && !ReportUtils.isThreadFirstChat(reportAction, reportID);
const isReportPreviewAction = reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.REPORTPREVIEW;
const isIOUAction = reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.IOU && !ReportActionsUtils.isSplitBillAction(reportAction);
const isWhisperAction = ReportActionsUtils.isWhisperAction(reportAction);
- return !subscribed && !isWhisperAction && (isCommentAction || isReportPreviewAction || isIOUAction);
+ return !subscribed && !isWhisperAction && (isCommentAction || isReportPreviewAction || isIOUAction) && (!isDeletedAction || shouldDisplayThreadReplies);
},
onPress: (closePopover, {reportAction, reportID}) => {
let childReportNotificationPreference = lodashGet(reportAction, 'childReportNotificationPreference', '');
@@ -199,6 +201,8 @@ export default [
const isActionCreator = ReportUtils.isActionCreator(reportAction);
childReportNotificationPreference = isActionCreator ? CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS : CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN;
}
+ const isDeletedAction = ReportActionsUtils.isDeletedAction(reportAction);
+ const shouldDisplayThreadReplies = ReportUtils.shouldDisplayThreadReplies(reportAction, reportID);
const subscribed = childReportNotificationPreference !== 'hidden';
if (type !== CONST.CONTEXT_MENU_TYPES.REPORT_ACTION) {
return false;
@@ -206,7 +210,7 @@ export default [
const isCommentAction = reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT && !ReportUtils.isThreadFirstChat(reportAction, reportID);
const isReportPreviewAction = reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.REPORTPREVIEW;
const isIOUAction = reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.IOU && !ReportActionsUtils.isSplitBillAction(reportAction);
- return subscribed && (isCommentAction || isReportPreviewAction || isIOUAction);
+ return subscribed && (isCommentAction || isReportPreviewAction || isIOUAction) && (!isDeletedAction || shouldDisplayThreadReplies);
},
onPress: (closePopover, {reportAction, reportID}) => {
let childReportNotificationPreference = lodashGet(reportAction, 'childReportNotificationPreference', '');
diff --git a/src/pages/home/report/ListBoundaryLoader/ListBoundaryLoader.js b/src/pages/home/report/ListBoundaryLoader/ListBoundaryLoader.js
index 77bcc7bdd38e..e059c2f06019 100644
--- a/src/pages/home/report/ListBoundaryLoader/ListBoundaryLoader.js
+++ b/src/pages/home/report/ListBoundaryLoader/ListBoundaryLoader.js
@@ -39,17 +39,17 @@ function ListBoundaryLoader({type, isLoadingOlderReportActions, isLoadingInitial
// We use two different loading components for the header and footer
// to reduce the jumping effect when the user is scrolling to the newer report actions
if (type === CONST.LIST_COMPONENTS.FOOTER) {
- if (isLoadingOlderReportActions) {
- return ;
- }
+ /*
+ Ensure that the report chat is not loaded until the beginning.
+ This is to avoid displaying the skeleton view above the "created" action in a newly generated optimistic chat or one with not that many comments.
+ Additionally, if we are offline and the report is not loaded until the beginning, we assume there are more actions to load;
+ Therefore, show the skeleton view even though the actions are not actually loading.
+ */
+ const isReportLoadedUntilBeginning = lastReportActionName === CONST.REPORT.ACTIONS.TYPE.CREATED;
+ const mayLoadMoreActions = !isReportLoadedUntilBeginning && (isLoadingInitialReportActions || isOffline);
- // Make sure the report chat is not loaded till the beginning. This is so we do not show the
- // skeleton view above the "created" action in a newly generated optimistic chat or one with not
- // that many comments.
- // Also, if we are offline and the report is not yet loaded till the beginning, we assume there are more actions to load,
- // therefore show the skeleton view, even though the actions are not loading.
- if (lastReportActionName !== CONST.REPORT.ACTIONS.TYPE.CREATED && (isLoadingInitialReportActions || isOffline)) {
- return ;
+ if (isLoadingOlderReportActions || mayLoadMoreActions) {
+ return ;
}
}
if (type === CONST.LIST_COMPONENTS.HEADER && isLoadingNewerReportActions) {
diff --git a/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js b/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js
index 1e8439c0086b..6c1d71625dc9 100644
--- a/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js
+++ b/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js
@@ -5,7 +5,6 @@ import {findNodeHandle, InteractionManager, NativeModules, View} from 'react-nat
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import Composer from '@components/Composer';
-import {PopoverContext} from '@components/PopoverProvider';
import withKeyboardState from '@components/withKeyboardState';
import useLocalize from '@hooks/useLocalize';
import usePrevious from '@hooks/usePrevious';
@@ -108,7 +107,6 @@ function ComposerWithSuggestions({
// For testing
children,
}) {
- const {isOpen: isPopoverOpen} = React.useContext(PopoverContext);
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
@@ -411,15 +409,9 @@ function ComposerWithSuggestions({
* @param {Boolean} [shouldDelay=false] Impose delay before focusing the composer
* @memberof ReportActionCompose
*/
- const focus = useCallback(
- (shouldDelay = false) => {
- if (isPopoverOpen) {
- return;
- }
- focusComposerWithDelay(textInputRef.current)(shouldDelay);
- },
- [isPopoverOpen],
- );
+ const focus = useCallback((shouldDelay = false) => {
+ focusComposerWithDelay(textInputRef.current)(shouldDelay);
+ }, []);
const setUpComposeFocusManager = useCallback(() => {
// This callback is used in the contextMenuActions to manage giving focus back to the compose input.
diff --git a/src/pages/home/report/ReportActionItem.js b/src/pages/home/report/ReportActionItem.js
index 435c086d913f..b1130af5d2ff 100644
--- a/src/pages/home/report/ReportActionItem.js
+++ b/src/pages/home/report/ReportActionItem.js
@@ -117,6 +117,9 @@ const propTypes = {
/** The user's wallet account */
userWallet: userWalletPropTypes,
+
+ /** All the report actions belonging to the report's parent */
+ parentReportActions: PropTypes.objectOf(PropTypes.shape(reportActionPropTypes)),
};
const defaultProps = {
@@ -127,6 +130,7 @@ const defaultProps = {
iouReport: undefined,
shouldHideThreadDividerLine: false,
userWallet: {},
+ parentReportActions: {},
};
function ReportActionItem(props) {
@@ -483,9 +487,8 @@ function ReportActionItem(props) {
);
}
const numberOfThreadReplies = _.get(props, ['action', 'childVisibleActionCount'], 0);
- const hasReplies = numberOfThreadReplies > 0;
- const shouldDisplayThreadReplies = hasReplies && props.action.childCommenterCount && !ReportUtils.isThreadFirstChat(props.action, props.report.reportID);
+ const shouldDisplayThreadReplies = ReportUtils.shouldDisplayThreadReplies(props.action, props.report.reportID);
const oldestFourAccountIDs = _.map(lodashGet(props.action, 'childOldestFourAccountIDs', '').split(','), (accountID) => Number(accountID));
const draftMessageRightAlign = !_.isUndefined(props.draftMessage) ? styles.chatItemReactionsDraftRight : {};
@@ -569,7 +572,7 @@ function ReportActionItem(props) {
};
if (props.action.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED) {
- const parentReportAction = ReportActionsUtils.getParentReportAction(props.report);
+ const parentReportAction = props.parentReportActions[props.report.parentReportActionID];
if (ReportActionsUtils.isTransactionThread(parentReportAction)) {
return (
@@ -672,7 +675,7 @@ function ReportActionItem(props) {
>
{(hovered) => (
@@ -690,7 +693,9 @@ function ReportActionItem(props) {
ReportActions.clearReportActionErrors(props.report.reportID, props.action)}
- pendingAction={!_.isUndefined(props.draftMessage) ? null : props.action.pendingAction}
+ pendingAction={
+ !_.isUndefined(props.draftMessage) ? null : props.action.pendingAction || (props.action.isOptimisticAction ? CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD : '')
+ }
shouldHideOnDelete={!ReportActionsUtils.isThreadParentMessage(props.action, props.report.reportID)}
errors={props.action.errors}
errorRowStyles={[styles.ml10, styles.mr2]}
@@ -768,6 +773,10 @@ export default compose(
userWallet: {
key: ONYXKEYS.USER_WALLET,
},
+ parentReportActions: {
+ key: ({report}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report.parentReportID || 0}`,
+ canEvict: false,
+ },
}),
)(
memo(
@@ -785,6 +794,8 @@ export default compose(
_.isEqual(prevProps.report.errorFields, nextProps.report.errorFields) &&
lodashGet(prevProps.report, 'statusNum') === lodashGet(nextProps.report, 'statusNum') &&
lodashGet(prevProps.report, 'stateNum') === lodashGet(nextProps.report, 'stateNum') &&
+ lodashGet(prevProps.report, 'parentReportID') === lodashGet(nextProps.report, 'parentReportID') &&
+ lodashGet(prevProps.report, 'parentReportActionID') === lodashGet(nextProps.report, 'parentReportActionID') &&
prevProps.translate === nextProps.translate &&
// TaskReport's created actions render the TaskView, which updates depending on certain fields in the TaskReport
ReportUtils.isTaskReport(prevProps.report) === ReportUtils.isTaskReport(nextProps.report) &&
diff --git a/src/pages/home/report/ReportActionItemMessageEdit.js b/src/pages/home/report/ReportActionItemMessageEdit.tsx
similarity index 75%
rename from src/pages/home/report/ReportActionItemMessageEdit.js
rename to src/pages/home/report/ReportActionItemMessageEdit.tsx
index dbd3262f30d5..5934c4c333cb 100644
--- a/src/pages/home/report/ReportActionItemMessageEdit.js
+++ b/src/pages/home/report/ReportActionItemMessageEdit.tsx
@@ -1,17 +1,17 @@
import ExpensiMark from 'expensify-common/lib/ExpensiMark';
import Str from 'expensify-common/lib/str';
-import lodashGet from 'lodash/get';
-import PropTypes from 'prop-types';
-import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import lodashDebounce from 'lodash/debounce';
+import type {ForwardedRef} from 'react';
+import React, {forwardRef, useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {InteractionManager, Keyboard, View} from 'react-native';
-import _ from 'underscore';
+import type {NativeSyntheticEvent, TextInput, TextInputFocusEventData, TextInputKeyPressEventData} from 'react-native';
+import type {Emoji} from '@assets/emojis/types';
import Composer from '@components/Composer';
import EmojiPickerButton from '@components/EmojiPicker/EmojiPickerButton';
import ExceededCommentLength from '@components/ExceededCommentLength';
import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';
import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
-import refPropTypes from '@components/refPropTypes';
import Tooltip from '@components/Tooltip';
import useHandleExceedMaxCommentLength from '@hooks/useHandleExceedMaxCommentLength';
import useKeyboardState from '@hooks/useKeyboardState';
@@ -30,48 +30,37 @@ import ReportActionComposeFocusManager from '@libs/ReportActionComposeFocusManag
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import setShouldShowComposeInputKeyboardAware from '@libs/setShouldShowComposeInputKeyboardAware';
-import reportPropTypes from '@pages/reportPropTypes';
import * as EmojiPickerAction from '@userActions/EmojiPickerAction';
import * as InputFocus from '@userActions/InputFocus';
import * as Report from '@userActions/Report';
import * as User from '@userActions/User';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
+import type * as OnyxTypes from '@src/types/onyx';
import * as ReportActionContextMenu from './ContextMenu/ReportActionContextMenu';
-import reportActionPropTypes from './reportActionPropTypes';
-const propTypes = {
+type ReportActionItemMessageEditProps = {
/** All the data of the action */
- action: PropTypes.shape(reportActionPropTypes).isRequired,
+ action: OnyxTypes.ReportAction;
/** Draft message */
- draftMessage: PropTypes.string.isRequired,
+ draftMessage: string;
/** ReportID that holds the comment we're editing */
- reportID: PropTypes.string.isRequired,
+ reportID: string;
/** Position index of the report action in the overall report FlatList view */
- index: PropTypes.number.isRequired,
-
- /** A ref to forward to the text input */
- forwardedRef: refPropTypes,
+ index: number;
/** The report currently being looked at */
// eslint-disable-next-line react/no-unused-prop-types
- report: reportPropTypes,
+ report?: OnyxTypes.Report;
/** Whether or not the emoji picker is disabled */
- shouldDisableEmojiPicker: PropTypes.bool,
+ shouldDisableEmojiPicker?: boolean;
/** Stores user's preferred skin tone */
- preferredSkinTone: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
-};
-
-const defaultProps = {
- forwardedRef: () => {},
- report: {},
- shouldDisableEmojiPicker: false,
- preferredSkinTone: CONST.EMOJI_DEFAULT_SKIN_TONE,
+ preferredSkinTone?: number;
};
// native ids
@@ -80,7 +69,10 @@ const messageEditInput = 'messageEditInput';
const isMobileSafari = Browser.isMobileSafari();
-function ReportActionItemMessageEdit(props) {
+function ReportActionItemMessageEdit(
+ {action, draftMessage, reportID, index, shouldDisableEmojiPicker = false, preferredSkinTone = CONST.EMOJI_DEFAULT_SKIN_TONE}: ReportActionItemMessageEditProps,
+ forwardedRef: ForwardedRef,
+) {
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
@@ -90,13 +82,13 @@ function ReportActionItemMessageEdit(props) {
const {isSmallScreenWidth} = useWindowDimensions();
const getInitialDraft = () => {
- if (props.draftMessage === props.action.message[0].html) {
+ if (draftMessage === action?.message?.[0].html) {
// We only convert the report action message to markdown if the draft message is unchanged.
const parser = new ExpensiMark();
- return parser.htmlToMarkdown(props.draftMessage).trim();
+ return parser.htmlToMarkdown(draftMessage).trim();
}
// We need to decode saved draft message because it's escaped before saving.
- return Str.htmlDecode(props.draftMessage);
+ return Str.htmlDecode(draftMessage);
};
const getInitialSelection = () => {
@@ -107,7 +99,7 @@ function ReportActionItemMessageEdit(props) {
const length = getInitialDraft().length;
return {start: length, end: length};
};
- const emojisPresentBefore = useRef([]);
+ const emojisPresentBefore = useRef([]);
const [draft, setDraft] = useState(() => {
const initialDraft = getInitialDraft();
if (initialDraft) {
@@ -115,23 +107,29 @@ function ReportActionItemMessageEdit(props) {
}
return initialDraft;
});
- const [selection, setSelection] = useState(getInitialSelection);
- const [isFocused, setIsFocused] = useState(false);
+ const [selection, setSelection] = useState<{
+ start: number;
+ end: number;
+ }>(getInitialSelection);
+ const [isFocused, setIsFocused] = useState(false);
const {hasExceededMaxCommentLength, validateCommentMaxLength} = useHandleExceedMaxCommentLength();
- const [modal, setModal] = useState(false);
- const [onyxFocused, setOnyxFocused] = useState(false);
+ const [modal, setModal] = useState({
+ willAlertModalBecomeVisible: false,
+ isVisible: false,
+ });
+ const [onyxFocused, setOnyxFocused] = useState(false);
- const textInputRef = useRef(null);
- const isFocusedRef = useRef(false);
- const insertedEmojis = useRef([]);
+ const textInputRef = useRef<(HTMLTextAreaElement & TextInput) | null>(null);
+ const isFocusedRef = useRef(false);
+ const insertedEmojis = useRef([]);
const draftRef = useRef(draft);
useEffect(() => {
- if (ReportActionsUtils.isDeletedAction(props.action) || props.draftMessage === props.action.message[0].html) {
+ if (ReportActionsUtils.isDeletedAction(action) || (action.message && draftMessage === action.message[0].html)) {
return;
}
- setDraft(Str.htmlDecode(props.draftMessage));
- }, [props.draftMessage, props.action]);
+ setDraft(Str.htmlDecode(draftMessage));
+ }, [draftMessage, action]);
useEffect(() => {
// required for keeping last state of isFocused variable
@@ -139,14 +137,14 @@ function ReportActionItemMessageEdit(props) {
}, [isFocused]);
useEffect(() => {
- InputFocus.composerFocusKeepFocusOn(textInputRef.current, isFocused, modal, onyxFocused);
+ InputFocus.composerFocusKeepFocusOn(textInputRef.current as HTMLElement, isFocused, modal, onyxFocused);
}, [isFocused, modal, onyxFocused]);
useEffect(() => {
const unsubscribeOnyxModal = onyxSubscribe({
key: ONYXKEYS.MODAL,
callback: (modalArg) => {
- if (_.isNull(modalArg)) {
+ if (modalArg === null) {
return;
}
setModal(modalArg);
@@ -156,7 +154,7 @@ function ReportActionItemMessageEdit(props) {
const unsubscribeOnyxFocused = onyxSubscribe({
key: ONYXKEYS.INPUT_FOCUSED,
callback: (modalArg) => {
- if (_.isNull(modalArg)) {
+ if (modalArg === null) {
return;
}
setOnyxFocused(modalArg);
@@ -170,8 +168,8 @@ function ReportActionItemMessageEdit(props) {
// We consider the report action active if it's focused, its emoji picker is open or its context menu is open
const isActive = useCallback(
- () => isFocusedRef.current || EmojiPickerAction.isActive(props.action.reportActionID) || ReportActionContextMenu.isActiveReportAction(props.action.reportActionID),
- [props.action.reportActionID],
+ () => isFocusedRef.current || EmojiPickerAction.isActive(action.reportActionID) || ReportActionContextMenu.isActiveReportAction(action.reportActionID),
+ [action.reportActionID],
);
useEffect(() => {
@@ -188,7 +186,9 @@ function ReportActionItemMessageEdit(props) {
});
// Scroll content of textInputRef to bottom
- textInputRef.current.scrollTop = textInputRef.current.scrollHeight;
+ if (textInputRef.current) {
+ textInputRef.current.scrollTop = textInputRef.current.scrollHeight;
+ }
}
return () => {
@@ -200,10 +200,10 @@ function ReportActionItemMessageEdit(props) {
return;
}
- if (EmojiPickerAction.isActive(props.action.reportActionID)) {
+ if (EmojiPickerAction.isActive(action.reportActionID)) {
EmojiPickerAction.clearActive();
}
- if (ReportActionContextMenu.isActiveReportAction(props.action.reportActionID)) {
+ if (ReportActionContextMenu.isActiveReportAction(action.reportActionID)) {
ReportActionContextMenu.clearActiveReportAction();
}
@@ -212,7 +212,7 @@ function ReportActionItemMessageEdit(props) {
setShouldShowComposeInputKeyboardAware(true);
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- this cleanup needs to be called only on unmount
- }, [props.action.reportActionID]);
+ }, [action.reportActionID]);
/**
* Save the draft of the comment. This debounced so that we're not ceaselessly saving your edit. Saving the draft
@@ -221,10 +221,10 @@ function ReportActionItemMessageEdit(props) {
*/
const debouncedSaveDraft = useMemo(
() =>
- _.debounce((newDraft) => {
- Report.saveReportActionDraft(props.reportID, props.action, newDraft);
+ lodashDebounce((newDraft: string) => {
+ Report.saveReportActionDraft(reportID, action, newDraft);
}, 1000),
- [props.reportID, props.action],
+ [reportID, action],
);
/**
@@ -233,7 +233,7 @@ function ReportActionItemMessageEdit(props) {
*/
const debouncedUpdateFrequentlyUsedEmojis = useMemo(
() =>
- _.debounce(() => {
+ lodashDebounce(() => {
User.updateFrequentlyUsedEmojis(EmojiUtils.getFrequentlyUsedEmojis(insertedEmojis.current));
insertedEmojis.current = [];
}, 1000),
@@ -246,12 +246,12 @@ function ReportActionItemMessageEdit(props) {
* @param {String} newDraftInput
*/
const updateDraft = useCallback(
- (newDraftInput) => {
- const {text: newDraft, emojis, cursorPosition} = EmojiUtils.replaceAndExtractEmojis(newDraftInput, props.preferredSkinTone, preferredLocale);
+ (newDraftInput: string) => {
+ const {text: newDraft, emojis, cursorPosition} = EmojiUtils.replaceAndExtractEmojis(newDraftInput, preferredSkinTone, preferredLocale);
- if (!_.isEmpty(emojis)) {
+ if (emojis?.length > 0) {
const newEmojis = EmojiUtils.getAddedEmojis(emojis, emojisPresentBefore.current);
- if (!_.isEmpty(newEmojis)) {
+ if (newEmojis?.length > 0) {
insertedEmojis.current = [...insertedEmojis.current, ...newEmojis];
debouncedUpdateFrequentlyUsedEmojis();
}
@@ -261,7 +261,7 @@ function ReportActionItemMessageEdit(props) {
setDraft(newDraft);
if (newDraftInput !== newDraft) {
- const position = Math.max(selection.end + (newDraft.length - draftRef.current.length), cursorPosition || 0);
+ const position = Math.max(selection.end + (newDraft.length - draftRef.current.length), cursorPosition ?? 0);
setSelection({
start: position,
end: position,
@@ -271,22 +271,22 @@ function ReportActionItemMessageEdit(props) {
draftRef.current = newDraft;
// We want to escape the draft message to differentiate the HTML from the report action and the HTML the user drafted.
- debouncedSaveDraft(_.escape(newDraft));
+ debouncedSaveDraft(newDraft);
},
- [debouncedSaveDraft, debouncedUpdateFrequentlyUsedEmojis, props.preferredSkinTone, preferredLocale, selection.end],
+ [debouncedSaveDraft, debouncedUpdateFrequentlyUsedEmojis, preferredSkinTone, preferredLocale, selection.end],
);
useEffect(() => {
updateDraft(draft);
// eslint-disable-next-line react-hooks/exhaustive-deps -- run this only when language is changed
- }, [props.action.reportActionID, preferredLocale]);
+ }, [action.reportActionID, preferredLocale]);
/**
* Delete the draft of the comment being edited. This will take the comment out of "edit mode" with the old content.
*/
const deleteDraft = useCallback(() => {
debouncedSaveDraft.cancel();
- Report.deleteReportActionDraft(props.reportID, props.action);
+ Report.deleteReportActionDraft(reportID, action);
if (isActive()) {
ReportActionComposeFocusManager.clear();
@@ -294,13 +294,13 @@ function ReportActionItemMessageEdit(props) {
}
// Scroll to the last comment after editing to make sure the whole comment is clearly visible in the report.
- if (props.index === 0) {
+ if (index === 0) {
const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
- reportScrollManager.scrollToIndex(props.index, false);
+ reportScrollManager.scrollToIndex(index, false);
keyboardDidHideListener.remove();
});
}
- }, [props.action, debouncedSaveDraft, props.index, props.reportID, reportScrollManager, isActive]);
+ }, [action, debouncedSaveDraft, index, reportID, reportScrollManager, isActive]);
/**
* Save the draft of the comment to be the new comment message. This will take the comment out of "edit mode" with
@@ -320,18 +320,25 @@ function ReportActionItemMessageEdit(props) {
// When user tries to save the empty message, it will delete it. Prompt the user to confirm deleting.
if (!trimmedNewDraft) {
- textInputRef.current.blur();
- ReportActionContextMenu.showDeleteModal(props.reportID, props.action, true, deleteDraft, () => InteractionManager.runAfterInteractions(() => textInputRef.current.focus()));
+ textInputRef.current?.blur();
+ ReportActionContextMenu.showDeleteModal(
+ reportID,
+ action,
+ true,
+ deleteDraft,
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ () => InteractionManager.runAfterInteractions(() => textInputRef.current?.focus()),
+ );
return;
}
- Report.editReportComment(props.reportID, props.action, trimmedNewDraft);
+ Report.editReportComment(reportID, action, trimmedNewDraft);
deleteDraft();
- }, [props.action, debouncedSaveDraft, deleteDraft, draft, props.reportID]);
+ }, [action, debouncedSaveDraft, deleteDraft, draft, reportID]);
/**
- * @param {String} emoji
+ * @param emoji
*/
- const addEmojiToTextBox = (emoji) => {
+ const addEmojiToTextBox = (emoji: string) => {
setSelection((prevSelection) => ({
start: prevSelection.start + emoji.length + CONST.SPACE_LENGTH,
end: prevSelection.start + emoji.length + CONST.SPACE_LENGTH,
@@ -345,14 +352,15 @@ function ReportActionItemMessageEdit(props) {
* @param {Event} e
*/
const triggerSaveOrCancel = useCallback(
- (e) => {
+ (e: NativeSyntheticEvent | KeyboardEvent) => {
if (!e || ComposerUtils.canSkipTriggerHotkeys(isSmallScreenWidth, isKeyboardShown)) {
return;
}
- if (e.key === CONST.KEYBOARD_SHORTCUTS.ENTER.shortcutKey && !e.shiftKey) {
+ const keyEvent = e as KeyboardEvent;
+ if (keyEvent.key === CONST.KEYBOARD_SHORTCUTS.ENTER.shortcutKey && !keyEvent.shiftKey) {
e.preventDefault();
publishDraft();
- } else if (e.key === CONST.KEYBOARD_SHORTCUTS.ESCAPE.shortcutKey) {
+ } else if (keyEvent.key === CONST.KEYBOARD_SHORTCUTS.ESCAPE.shortcutKey) {
e.preventDefault();
deleteDraft();
}
@@ -404,11 +412,14 @@ function ReportActionItemMessageEdit(props) {
{
- ReportActionComposeFocusManager.editComposerRef.current = el;
+ ref={(el: TextInput & HTMLTextAreaElement) => {
textInputRef.current = el;
- // eslint-disable-next-line no-param-reassign
- props.forwardedRef.current = el;
+ if (typeof forwardedRef === 'function') {
+ forwardedRef(el);
+ } else if (forwardedRef) {
+ // eslint-disable-next-line no-param-reassign
+ forwardedRef.current = el;
+ }
}}
id={messageEditInput}
onChangeText={updateDraft} // Debounced saveDraftComment
@@ -418,21 +429,22 @@ function ReportActionItemMessageEdit(props) {
style={[styles.textInputCompose, styles.flex1, styles.bgTransparent]}
onFocus={() => {
setIsFocused(true);
- reportScrollManager.scrollToIndex(props.index, true);
+ reportScrollManager.scrollToIndex(index, true);
setShouldShowComposeInputKeyboardAware(false);
// Clear active report action when another action gets focused
- if (!EmojiPickerAction.isActive(props.action.reportActionID)) {
+ if (!EmojiPickerAction.isActive(action.reportActionID)) {
EmojiPickerAction.clearActive();
}
- if (!ReportActionContextMenu.isActiveReportAction(props.action.reportActionID)) {
+ if (!ReportActionContextMenu.isActiveReportAction(action.reportActionID)) {
ReportActionContextMenu.clearActiveReportAction();
}
}}
- onBlur={(event) => {
+ onBlur={(event: NativeSyntheticEvent) => {
setIsFocused(false);
- const relatedTargetId = lodashGet(event, 'nativeEvent.relatedTarget.id');
- if (_.contains([messageEditInput, emojiButtonID], relatedTargetId)) {
+ // @ts-expect-error TODO: TextInputFocusEventData doesn't contain relatedTarget.
+ const relatedTargetId = event.nativeEvent?.relatedTarget?.id;
+ if (relatedTargetId && [messageEditInput, emojiButtonID].includes(relatedTargetId)) {
return;
}
setShouldShowComposeInputKeyboardAware(true);
@@ -443,11 +455,11 @@ function ReportActionItemMessageEdit(props) {
focus(true)}
onEmojiSelected={addEmojiToTextBox}
id={emojiButtonID}
- emojiPickerID={props.action.reportActionID}
+ emojiPickerID={action.reportActionID}
/>
@@ -478,18 +490,6 @@ function ReportActionItemMessageEdit(props) {
);
}
-ReportActionItemMessageEdit.propTypes = propTypes;
-ReportActionItemMessageEdit.defaultProps = defaultProps;
ReportActionItemMessageEdit.displayName = 'ReportActionItemMessageEdit';
-const ReportActionItemMessageEditWithRef = React.forwardRef((props, ref) => (
-
-));
-
-ReportActionItemMessageEditWithRef.displayName = 'ReportActionItemMessageEditWithRef';
-
-export default ReportActionItemMessageEditWithRef;
+export default forwardRef(ReportActionItemMessageEdit);
diff --git a/src/pages/home/report/ReportActionsList.js b/src/pages/home/report/ReportActionsList.js
index 2009dc9a102d..dba8ef2e11d0 100644
--- a/src/pages/home/report/ReportActionsList.js
+++ b/src/pages/home/report/ReportActionsList.js
@@ -2,7 +2,7 @@ import {useRoute} from '@react-navigation/native';
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
-import {DeviceEventEmitter} from 'react-native';
+import {DeviceEventEmitter, InteractionManager} from 'react-native';
import Animated, {useAnimatedStyle, useSharedValue, withTiming} from 'react-native-reanimated';
import _ from 'underscore';
import InvertedFlatList from '@components/InvertedFlatList';
@@ -138,19 +138,19 @@ function ReportActionsList({
isComposerFullSize,
}) {
const styles = useThemeStyles();
- const reportScrollManager = useReportScrollManager();
const {translate} = useLocalize();
const {isOffline} = useNetwork();
const route = useRoute();
const opacity = useSharedValue(0);
const userActiveSince = useRef(null);
- const unreadActionSubscription = useRef(null);
+
const markerInit = () => {
if (!cacheUnreadMarkers.has(report.reportID)) {
return null;
}
return cacheUnreadMarkers.get(report.reportID);
};
+ const reportScrollManager = useReportScrollManager();
const [currentUnreadMarker, setCurrentUnreadMarker] = useState(markerInit);
const scrollingVerticalOffset = useRef(0);
const readActionSkipped = useRef(false);
@@ -159,7 +159,10 @@ function ReportActionsList({
const lastVisibleActionCreatedRef = useRef(report.lastVisibleActionCreated);
const lastReadTimeRef = useRef(report.lastReadTime);
- const sortedVisibleReportActions = _.filter(sortedReportActions, (s) => isOffline || s.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || s.errors);
+ const sortedVisibleReportActions = useMemo(
+ () => _.filter(sortedReportActions, (s) => isOffline || s.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || s.errors),
+ [sortedReportActions, isOffline],
+ );
const lastActionIndex = lodashGet(sortedVisibleReportActions, [0, 'reportActionID']);
const reportActionSize = useRef(sortedVisibleReportActions.length);
@@ -236,22 +239,35 @@ function ReportActionsList({
}, [report.lastReadTime, report.reportID]);
useEffect(() => {
- // If the reportID changes, we reset the userActiveSince to null, we need to do it because
- // this component doesn't unmount when the reportID changes
- if (unreadActionSubscription.current) {
- unreadActionSubscription.current.remove();
- unreadActionSubscription.current = null;
- }
-
- // Listen to specific reportID for unread event and set the marker to new message
- unreadActionSubscription.current = DeviceEventEmitter.addListener(`unreadAction_${report.reportID}`, (newLastReadTime) => {
+ const resetUnreadMarker = (newLastReadTime) => {
cacheUnreadMarkers.delete(report.reportID);
lastReadTimeRef.current = newLastReadTime;
setCurrentUnreadMarker(null);
+ };
+
+ const unreadActionSubscription = DeviceEventEmitter.addListener(`unreadAction_${report.reportID}`, (newLastReadTime) => {
+ resetUnreadMarker(newLastReadTime);
setMessageManuallyMarkedUnread(new Date().getTime());
});
+
+ const readNewestActionSubscription = DeviceEventEmitter.addListener(`readNewestAction_${report.reportID}`, (newLastReadTime) => {
+ resetUnreadMarker(newLastReadTime);
+ setMessageManuallyMarkedUnread(0);
+ });
+
+ return () => {
+ unreadActionSubscription.remove();
+ readNewestActionSubscription.remove();
+ };
}, [report.reportID]);
+ useEffect(() => {
+ InteractionManager.runAfterInteractions(() => {
+ reportScrollManager.scrollToBottom();
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
useEffect(() => {
// Why are we doing this, when in the cleanup of the useEffect we are already calling the unsubscribe function?
// Answer: On web, when navigating to another report screen, the previous report screen doesn't get unmounted,
@@ -273,7 +289,7 @@ function ReportActionsList({
if (!isFromCurrentUser) {
return;
}
- reportScrollManager.scrollToBottom();
+ InteractionManager.runAfterInteractions(() => reportScrollManager.scrollToBottom());
});
const cleanup = () => {
@@ -348,9 +364,9 @@ function ReportActionsList({
(reportAction, index) => {
let shouldDisplay = false;
if (!currentUnreadMarker) {
- const nextMessage = sortedReportActions[index + 1];
+ const nextMessage = sortedVisibleReportActions[index + 1];
const isCurrentMessageUnread = isMessageUnread(reportAction, lastReadTimeRef.current);
- shouldDisplay = isCurrentMessageUnread && (!nextMessage || !isMessageUnread(nextMessage, lastReadTimeRef.current));
+ shouldDisplay = isCurrentMessageUnread && (!nextMessage || !isMessageUnread(nextMessage, lastReadTimeRef.current)) && !ReportActionsUtils.shouldHideNewMarker(reportAction);
if (shouldDisplay && !messageManuallyMarkedUnread) {
const isWithinVisibleThreshold = scrollingVerticalOffset.current < MSG_VISIBLE_THRESHOLD ? reportAction.created < userActiveSince.current : true;
// Prevent displaying a new marker line when report action is of type "REPORTPREVIEW" and last actor is the current user
@@ -367,7 +383,7 @@ function ReportActionsList({
return shouldDisplay;
},
- [currentUnreadMarker, sortedReportActions, report.reportID, messageManuallyMarkedUnread],
+ [currentUnreadMarker, sortedVisibleReportActions, report.reportID, messageManuallyMarkedUnread],
);
useEffect(() => {
@@ -375,7 +391,7 @@ function ReportActionsList({
// This is to avoid a warning of:
// Cannot update a component (ReportActionsList) while rendering a different component (CellRenderer).
let markerFound = false;
- _.each(sortedReportActions, (reportAction, index) => {
+ _.each(sortedVisibleReportActions, (reportAction, index) => {
if (!shouldDisplayNewMarker(reportAction, index)) {
return;
}
@@ -388,7 +404,7 @@ function ReportActionsList({
if (!markerFound) {
setCurrentUnreadMarker(null);
}
- }, [sortedReportActions, report.lastReadTime, report.reportID, messageManuallyMarkedUnread, shouldDisplayNewMarker, currentUnreadMarker]);
+ }, [sortedVisibleReportActions, report.lastReadTime, report.reportID, messageManuallyMarkedUnread, shouldDisplayNewMarker, currentUnreadMarker]);
const renderItem = useCallback(
({item: reportAction, index}) => (
diff --git a/src/pages/home/report/ReportDropUI.js b/src/pages/home/report/ReportDropUI.js
index 3f113e685b1d..c1c3b8e506ab 100644
--- a/src/pages/home/report/ReportDropUI.js
+++ b/src/pages/home/report/ReportDropUI.js
@@ -6,7 +6,6 @@ import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';
import Text from '@components/Text';
import useLocalize from '@hooks/useLocalize';
-import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
const propTypes = {
@@ -15,7 +14,6 @@ const propTypes = {
};
function ReportDropUI({onDrop}) {
- const theme = useTheme();
const styles = useThemeStyles();
const {translate} = useLocalize();
return (
@@ -23,7 +21,6 @@ function ReportDropUI({onDrop}) {
{
- // Do not fetch private notes if isLoadingPrivateNotes is already defined, or if network is offline.
- if (isPrivateNotesFetchTriggered || network.isOffline) {
- return;
- }
-
- Report.getReportPrivateNote(report.reportID);
- // eslint-disable-next-line react-hooks/exhaustive-deps -- do not add report.isLoadingPrivateNotes to dependencies
- }, [report.reportID, network.isOffline, isPrivateNotesFetchTriggered]);
-
- const isPrivateNotesEmpty = accountID ? _.isEmpty(lodashGet(report, ['privateNotes', accountID, 'note'], '')) : _.isEmpty(report.privateNotes);
- const shouldShowFullScreenLoadingIndicator = !isPrivateNotesFetchTriggered || (isPrivateNotesEmpty && report.isLoadingPrivateNotes);
-
+ return (WrappedComponent) => {
// eslint-disable-next-line rulesdir/no-negated-variables
- const shouldShowNotFoundPage = useMemo(() => {
- // Show not found view if the report is archived, or if the note is not of current user.
- if (ReportUtils.isArchivedRoom(report) || (accountID && Number(session.accountID) !== Number(accountID))) {
- return true;
+ function WithReportAndPrivateNotesOrNotFound({forwardedRef, ...props}) {
+ const {translate} = useLocalize();
+ const {route, report, network, session} = props;
+ const accountID = route.params.accountID;
+ const isPrivateNotesFetchTriggered = !_.isUndefined(report.isLoadingPrivateNotes);
+ const prevIsOffline = usePrevious(network.isOffline);
+ const isReconnecting = prevIsOffline && !network.isOffline;
+ const isOtherUserNote = accountID && Number(session.accountID) !== Number(accountID);
+ const isPrivateNotesEmpty = accountID ? _.has(lodashGet(report, ['privateNotes', accountID, 'note'], '')) : _.isEmpty(report.privateNotes);
+
+ useEffect(() => {
+ // Do not fetch private notes if isLoadingPrivateNotes is already defined, or if network is offline.
+ if ((isPrivateNotesFetchTriggered && !isReconnecting) || network.isOffline) {
+ return;
+ }
+
+ Report.getReportPrivateNote(report.reportID);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- do not add report.isLoadingPrivateNotes to dependencies
+ }, [report.reportID, network.isOffline, isPrivateNotesFetchTriggered, isReconnecting]);
+
+ const shouldShowFullScreenLoadingIndicator = !isPrivateNotesFetchTriggered || (isPrivateNotesEmpty && (report.isLoadingPrivateNotes || !isOtherUserNote));
+
+ // eslint-disable-next-line rulesdir/no-negated-variables
+ const shouldShowNotFoundPage = useMemo(() => {
+ // Show not found view if the report is archived, or if the note is not of current user.
+ if (ReportUtils.isArchivedRoom(report) || (accountID && Number(session.accountID) !== Number(accountID))) {
+ return true;
+ }
+
+ // Don't show not found view if the notes are still loading, or if the notes are non-empty.
+ if (shouldShowFullScreenLoadingIndicator || !isPrivateNotesEmpty || isReconnecting) {
+ return false;
+ }
+
+ // As notes being empty and not loading is a valid case, show not found view only in offline mode.
+ return network.isOffline;
+ }, [report, network.isOffline, accountID, session.accountID, isPrivateNotesEmpty, shouldShowFullScreenLoadingIndicator, isReconnecting]);
+
+ if (shouldShowFullScreenLoadingIndicator) {
+ return ;
}
- // Don't show not found view if the notes are still loading, or if the notes are non-empty.
- if (shouldShowFullScreenLoadingIndicator || !isPrivateNotesEmpty) {
- return false;
+ if (shouldShowNotFoundPage) {
+ return ;
}
- // As notes being empty and not loading is a valid case, show not found view only in offline mode.
- return network.isOffline;
- }, [report, network.isOffline, accountID, session.accountID, isPrivateNotesEmpty, shouldShowFullScreenLoadingIndicator]);
-
- if (shouldShowFullScreenLoadingIndicator) {
- return ;
+ return (
+
+ );
}
- if (shouldShowNotFoundPage) {
- return ;
- }
+ WithReportAndPrivateNotesOrNotFound.propTypes = propTypes;
+ WithReportAndPrivateNotesOrNotFound.defaultProps = defaultProps;
+ WithReportAndPrivateNotesOrNotFound.displayName = `withReportAndPrivateNotesOrNotFound(${getComponentDisplayName(WrappedComponent)})`;
- return (
- (
+
- );
- }
-
- WithReportAndPrivateNotesOrNotFound.propTypes = propTypes;
- WithReportAndPrivateNotesOrNotFound.defaultProps = defaultProps;
- WithReportAndPrivateNotesOrNotFound.displayName = `withReportAndPrivateNotesOrNotFound(${getComponentDisplayName(WrappedComponent)})`;
-
- // eslint-disable-next-line rulesdir/no-negated-variables
- const WithReportAndPrivateNotesOrNotFoundWithRef = React.forwardRef((props, ref) => (
-
- ));
-
- WithReportAndPrivateNotesOrNotFoundWithRef.displayName = 'WithReportAndPrivateNotesOrNotFoundWithRef';
-
- return compose(
- withReportOrNotFound(),
- withOnyx({
- session: {
- key: ONYXKEYS.SESSION,
- },
- }),
- withNetwork(),
- )(WithReportAndPrivateNotesOrNotFoundWithRef);
+ ));
+
+ WithReportAndPrivateNotesOrNotFoundWithRef.displayName = 'WithReportAndPrivateNotesOrNotFoundWithRef';
+
+ return compose(
+ withReportOrNotFound(),
+ withOnyx({
+ session: {
+ key: ONYXKEYS.SESSION,
+ },
+ }),
+ withNetwork(),
+ )(WithReportAndPrivateNotesOrNotFoundWithRef);
+ };
}
diff --git a/src/pages/iou/MoneyRequestSelectorPage.js b/src/pages/iou/MoneyRequestSelectorPage.js
index 7b87b50bb7f3..0a0efc38313a 100644
--- a/src/pages/iou/MoneyRequestSelectorPage.js
+++ b/src/pages/iou/MoneyRequestSelectorPage.js
@@ -24,7 +24,7 @@ import * as IOU from '@userActions/IOU';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import NewDistanceRequestPage from './NewDistanceRequestPage';
-import ReceiptSelector from './ReceiptSelector';
+import IOURequestStepScan from './request/step/IOURequestStepScan';
import NewRequestAmountPage from './steps/NewRequestAmountPage';
const propTypes = {
@@ -132,11 +132,7 @@ function MoneyRequestSelectorPage(props) {
component={NewRequestAmountPage}
initialParams={{reportID, iouType}}
/>
-
+ {() => }
{shouldDisplayDistanceRequest && (
{
- const trackRef = useRef(null);
- const shouldShowCamera = useTabNavigatorFocus({
- tabIndex: cameraTabIndex,
- });
-
- const handleOnUserMedia = (stream) => {
- if (props.onUserMedia) {
- props.onUserMedia(stream);
- }
-
- const [track] = stream.getVideoTracks();
- const capabilities = track.getCapabilities();
- if (capabilities.torch) {
- trackRef.current = track;
- }
- if (onTorchAvailability) {
- onTorchAvailability(!!capabilities.torch);
- }
- };
-
- useEffect(() => {
- if (!trackRef.current) {
- return;
- }
-
- trackRef.current.applyConstraints({
- advanced: [{torch: torchOn}],
- });
- }, [torchOn]);
-
- if (!shouldShowCamera) {
- return null;
- }
- return (
-
-
-
- );
-});
-
-NavigationAwareCamera.propTypes = propTypes;
-NavigationAwareCamera.displayName = 'NavigationAwareCamera';
-NavigationAwareCamera.defaultProps = defaultProps;
-
-export default NavigationAwareCamera;
diff --git a/src/pages/iou/ReceiptSelector/NavigationAwareCamera/index.native.js b/src/pages/iou/ReceiptSelector/NavigationAwareCamera/index.native.js
deleted file mode 100644
index 65c17d3cb7ab..000000000000
--- a/src/pages/iou/ReceiptSelector/NavigationAwareCamera/index.native.js
+++ /dev/null
@@ -1,28 +0,0 @@
-import PropTypes from 'prop-types';
-import React from 'react';
-import {Camera} from 'react-native-vision-camera';
-import useTabNavigatorFocus from '@hooks/useTabNavigatorFocus';
-
-const propTypes = {
- /* The index of the tab that contains this camera */
- cameraTabIndex: PropTypes.number.isRequired,
-};
-
-// Wraps a camera that will only be active when the tab is focused or as soon as it starts to become focused.
-const NavigationAwareCamera = React.forwardRef(({cameraTabIndex, ...props}, ref) => {
- const isCameraActive = useTabNavigatorFocus({tabIndex: cameraTabIndex});
-
- return (
-
- );
-});
-
-NavigationAwareCamera.propTypes = propTypes;
-NavigationAwareCamera.displayName = 'NavigationAwareCamera';
-
-export default NavigationAwareCamera;
diff --git a/src/pages/iou/ReceiptSelector/index.js b/src/pages/iou/ReceiptSelector/index.js
deleted file mode 100644
index ae871260b03e..000000000000
--- a/src/pages/iou/ReceiptSelector/index.js
+++ /dev/null
@@ -1,340 +0,0 @@
-import lodashGet from 'lodash/get';
-import PropTypes from 'prop-types';
-import React, {useCallback, useContext, useReducer, useRef, useState} from 'react';
-import {ActivityIndicator, PanResponder, PixelRatio, Text, View} from 'react-native';
-import {withOnyx} from 'react-native-onyx';
-import Hand from '@assets/images/hand.svg';
-import ReceiptUpload from '@assets/images/receipt-upload.svg';
-import Shutter from '@assets/images/shutter.svg';
-import AttachmentPicker from '@components/AttachmentPicker';
-import Button from '@components/Button';
-import ConfirmModal from '@components/ConfirmModal';
-import CopyTextToClipboard from '@components/CopyTextToClipboard';
-import {DragAndDropContext} from '@components/DragAndDrop/Provider';
-import Icon from '@components/Icon';
-import * as Expensicons from '@components/Icon/Expensicons';
-import ImageSVG from '@components/ImageSVG';
-import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
-import useLocalize from '@hooks/useLocalize';
-import useTheme from '@hooks/useTheme';
-import useThemeStyles from '@hooks/useThemeStyles';
-import useWindowDimensions from '@hooks/useWindowDimensions';
-import * as Browser from '@libs/Browser';
-import * as FileUtils from '@libs/fileDownload/FileUtils';
-import Navigation from '@libs/Navigation/Navigation';
-import {iouDefaultProps, iouPropTypes} from '@pages/iou/propTypes';
-import ReceiptDropUI from '@pages/iou/ReceiptDropUI';
-import reportPropTypes from '@pages/reportPropTypes';
-import * as IOU from '@userActions/IOU';
-import CONST from '@src/CONST';
-import ONYXKEYS from '@src/ONYXKEYS';
-import NavigationAwareCamera from './NavigationAwareCamera';
-
-const propTypes = {
- /** The report on which the request is initiated on */
- report: reportPropTypes,
-
- /** React Navigation route */
- route: PropTypes.shape({
- /** Params from the route */
- params: PropTypes.shape({
- /** The type of IOU report, i.e. bill, request, send */
- iouType: PropTypes.string,
-
- /** The report ID of the IOU */
- reportID: PropTypes.string,
- }),
-
- /** The current route path */
- path: PropTypes.string,
- }).isRequired,
-
- /** Holds data related to Money Request view state, rather than the underlying Money Request data. */
- iou: iouPropTypes,
-
- /** The id of the transaction we're editing */
- transactionID: PropTypes.string,
-};
-
-const defaultProps = {
- report: {},
- iou: iouDefaultProps,
- transactionID: '',
-};
-
-function ReceiptSelector({route, transactionID, iou, report}) {
- const theme = useTheme();
- const styles = useThemeStyles();
- const iouType = lodashGet(route, 'params.iouType', '');
- const pageIndex = lodashGet(route, 'params.pageIndex', 1);
-
- // Grouping related states
- const [isAttachmentInvalid, setIsAttachmentInvalid] = useState(false);
- const [attachmentInvalidReasonTitle, setAttachmentInvalidReasonTitle] = useState('');
- const [attachmentInvalidReason, setAttachmentValidReason] = useState('');
-
- const [receiptImageTopPosition, setReceiptImageTopPosition] = useState(0);
- const {isSmallScreenWidth} = useWindowDimensions();
- const {translate} = useLocalize();
- const {isDraggingOver} = useContext(DragAndDropContext);
-
- const [cameraPermissionState, setCameraPermissionState] = useState('prompt');
- const [isFlashLightOn, toggleFlashlight] = useReducer((state) => !state, false);
- const [isTorchAvailable, setIsTorchAvailable] = useState(false);
- const cameraRef = useRef(null);
-
- const hideReciptModal = () => {
- setIsAttachmentInvalid(false);
- };
-
- /**
- * Sets the upload receipt error modal content when an invalid receipt is uploaded
- * @param {*} isInvalid
- * @param {*} title
- * @param {*} reason
- */
- const setUploadReceiptError = (isInvalid, title, reason) => {
- setIsAttachmentInvalid(isInvalid);
- setAttachmentInvalidReasonTitle(title);
- setAttachmentValidReason(reason);
- };
-
- function validateReceipt(file) {
- const {fileExtension} = FileUtils.splitExtensionFromFileName(lodashGet(file, 'name', ''));
- if (!CONST.API_ATTACHMENT_VALIDATIONS.ALLOWED_RECEIPT_EXTENSIONS.includes(fileExtension.toLowerCase())) {
- setUploadReceiptError(true, 'attachmentPicker.wrongFileType', 'attachmentPicker.notAllowedExtension');
- return false;
- }
-
- if (lodashGet(file, 'size', 0) > CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE) {
- setUploadReceiptError(true, 'attachmentPicker.attachmentTooLarge', 'attachmentPicker.sizeExceeded');
- return false;
- }
-
- if (lodashGet(file, 'size', 0) < CONST.API_ATTACHMENT_VALIDATIONS.MIN_SIZE) {
- setUploadReceiptError(true, 'attachmentPicker.attachmentTooSmall', 'attachmentPicker.sizeNotMet');
- return false;
- }
-
- return true;
- }
-
- /**
- * Sets the Receipt objects and navigates the user to the next page
- * @param {Object} file
- * @param {Object} iouObject
- * @param {Object} reportObject
- */
- const setReceiptAndNavigate = (file, iouObject, reportObject) => {
- if (!validateReceipt(file)) {
- return;
- }
-
- const filePath = URL.createObjectURL(file);
- IOU.setMoneyRequestReceipt(filePath, file.name);
-
- if (transactionID) {
- IOU.replaceReceipt(transactionID, file, filePath);
- Navigation.dismissModal();
- return;
- }
-
- IOU.navigateToNextPage(iouObject, iouType, reportObject, route.path);
- };
-
- const capturePhoto = useCallback(() => {
- if (!cameraRef.current.getScreenshot) {
- return;
- }
- const imageBase64 = cameraRef.current.getScreenshot();
- const filename = `receipt_${Date.now()}.png`;
- const imageFile = FileUtils.base64ToFile(imageBase64, filename);
- const filePath = URL.createObjectURL(imageFile);
- IOU.setMoneyRequestReceipt(filePath, imageFile.name);
-
- if (transactionID) {
- IOU.replaceReceipt(transactionID, imageFile, filePath);
- Navigation.dismissModal();
- return;
- }
-
- IOU.navigateToNextPage(iou, iouType, report, route.path);
- }, [cameraRef, iou, report, iouType, transactionID, route.path]);
-
- const panResponder = useRef(
- PanResponder.create({
- onPanResponderTerminationRequest: () => false,
- }),
- ).current;
-
- const mobileCameraView = () => (
- <>
-
- {(cameraPermissionState === 'prompt' || !cameraPermissionState) && (
-
- )}
-
- {cameraPermissionState === 'denied' && (
-
-
- {translate('receipt.takePhoto')}
- {translate('receipt.cameraAccess')}
-
- )}
- setCameraPermissionState('granted')}
- onUserMediaError={() => setCameraPermissionState('denied')}
- style={{...styles.videoContainer, display: cameraPermissionState !== 'granted' ? 'none' : 'block'}}
- ref={cameraRef}
- screenshotFormat="image/png"
- videoConstraints={{facingMode: {exact: 'environment'}}}
- torchOn={isFlashLightOn}
- onTorchAvailability={setIsTorchAvailable}
- forceScreenshotSourceSize
- cameraTabIndex={pageIndex}
- />
-
-
-
-
- {({openPicker}) => (
- {
- openPicker({
- onPicked: (file) => {
- setReceiptAndNavigate(file, iou, report);
- },
- });
- }}
- >
-
-
- )}
-
-
-
-
-
-
-
-
- >
- );
-
- const desktopUploadView = () => (
- <>
- setReceiptImageTopPosition(PixelRatio.roundToNearestPixel(nativeEvent.layout.top))}>
-
-
-
-
- {translate('receipt.upload')}
-
- {isSmallScreenWidth ? translate('receipt.chooseReceipt') : translate('receipt.dragReceiptBeforeEmail')}
-
- {isSmallScreenWidth ? null : translate('receipt.dragReceiptAfterEmail')}
-
-
-
-
- {({openPicker}) => (
- {
- openPicker({
- onPicked: (file) => {
- setReceiptAndNavigate(file, iou, report);
- },
- });
- }}
- />
- )}
-
- >
- );
-
- return (
-
- {!isDraggingOver && (Browser.isMobile() ? mobileCameraView() : desktopUploadView())}
- {
- const file = lodashGet(e, ['dataTransfer', 'files', 0]);
- setReceiptAndNavigate(file, iou, report);
- }}
- receiptImageTopPosition={receiptImageTopPosition}
- />
-
-
- );
-}
-
-ReceiptSelector.defaultProps = defaultProps;
-ReceiptSelector.propTypes = propTypes;
-ReceiptSelector.displayName = 'ReceiptSelector';
-
-export default withOnyx({
- iou: {key: ONYXKEYS.IOU},
- report: {
- key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT}${lodashGet(route, 'params.reportID', '')}`,
- },
-})(ReceiptSelector);
diff --git a/src/pages/iou/ReceiptSelector/index.native.js b/src/pages/iou/ReceiptSelector/index.native.js
deleted file mode 100644
index 3cae5389d86f..000000000000
--- a/src/pages/iou/ReceiptSelector/index.native.js
+++ /dev/null
@@ -1,303 +0,0 @@
-import lodashGet from 'lodash/get';
-import PropTypes from 'prop-types';
-import React, {useCallback, useEffect, useRef, useState} from 'react';
-import {ActivityIndicator, Alert, AppState, Text, View} from 'react-native';
-import {withOnyx} from 'react-native-onyx';
-import {RESULTS} from 'react-native-permissions';
-import {useCameraDevices} from 'react-native-vision-camera';
-import Hand from '@assets/images/hand.svg';
-import Shutter from '@assets/images/shutter.svg';
-import AttachmentPicker from '@components/AttachmentPicker';
-import Button from '@components/Button';
-import Icon from '@components/Icon';
-import * as Expensicons from '@components/Icon/Expensicons';
-import ImageSVG from '@components/ImageSVG';
-import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
-import useLocalize from '@hooks/useLocalize';
-import useTheme from '@hooks/useTheme';
-import useThemeStyles from '@hooks/useThemeStyles';
-import * as FileUtils from '@libs/fileDownload/FileUtils';
-import Log from '@libs/Log';
-import Navigation from '@libs/Navigation/Navigation';
-import {iouDefaultProps, iouPropTypes} from '@pages/iou/propTypes';
-import reportPropTypes from '@pages/reportPropTypes';
-import * as IOU from '@userActions/IOU';
-import CONST from '@src/CONST';
-import ONYXKEYS from '@src/ONYXKEYS';
-import * as CameraPermission from './CameraPermission';
-import NavigationAwareCamera from './NavigationAwareCamera';
-
-const propTypes = {
- /** React Navigation route */
- route: PropTypes.shape({
- /** Params from the route */
- params: PropTypes.shape({
- /** The type of IOU report, i.e. bill, request, send */
- iouType: PropTypes.string,
-
- /** The report ID of the IOU */
- reportID: PropTypes.string,
- }),
-
- /** The current route path */
- path: PropTypes.string,
- }).isRequired,
-
- /** The report on which the request is initiated on */
- report: reportPropTypes,
-
- /** Holds data related to Money Request view state, rather than the underlying Money Request data. */
- iou: iouPropTypes,
-
- /** The id of the transaction we're editing */
- transactionID: PropTypes.string,
-};
-
-const defaultProps = {
- report: {},
- iou: iouDefaultProps,
- transactionID: '',
-};
-
-function ReceiptSelector({route, report, iou, transactionID}) {
- const theme = useTheme();
- const styles = useThemeStyles();
- const devices = useCameraDevices('wide-angle-camera');
- const device = devices.back;
-
- const camera = useRef(null);
- const [flash, setFlash] = useState(false);
- const [cameraPermissionStatus, setCameraPermissionStatus] = useState(undefined);
-
- const iouType = lodashGet(route, 'params.iouType', '');
- const pageIndex = lodashGet(route, 'params.pageIndex', 1);
-
- const {translate} = useLocalize();
-
- useEffect(() => {
- const refreshCameraPermissionStatus = () => {
- CameraPermission.getCameraPermissionStatus()
- .then(setCameraPermissionStatus)
- .catch(() => setCameraPermissionStatus(RESULTS.UNAVAILABLE));
- };
-
- // Check initial camera permission status
- refreshCameraPermissionStatus();
-
- // Refresh permission status when app gain focus
- const subscription = AppState.addEventListener('change', (appState) => {
- if (appState !== 'active') {
- return;
- }
-
- refreshCameraPermissionStatus();
- });
-
- return () => {
- subscription.remove();
- };
- }, []);
-
- const validateReceipt = (file) => {
- const {fileExtension} = FileUtils.splitExtensionFromFileName(lodashGet(file, 'name', ''));
- if (!CONST.API_ATTACHMENT_VALIDATIONS.ALLOWED_RECEIPT_EXTENSIONS.includes(fileExtension.toLowerCase())) {
- Alert.alert(translate('attachmentPicker.wrongFileType'), translate('attachmentPicker.notAllowedExtension'));
- return false;
- }
-
- if (lodashGet(file, 'size', 0) > CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE) {
- Alert.alert(translate('attachmentPicker.attachmentTooLarge'), translate('attachmentPicker.sizeExceeded'));
- return false;
- }
-
- if (lodashGet(file, 'size', 0) < CONST.API_ATTACHMENT_VALIDATIONS.MIN_SIZE) {
- Alert.alert(translate('attachmentPicker.attachmentTooSmall'), translate('attachmentPicker.sizeNotMet'));
- return false;
- }
- return true;
- };
-
- const askForPermissions = () => {
- // There's no way we can check for the BLOCKED status without requesting the permission first
- // https://github.com/zoontek/react-native-permissions/blob/a836e114ce3a180b2b23916292c79841a267d828/README.md?plain=1#L670
- CameraPermission.requestCameraPermission()
- .then((status) => {
- setCameraPermissionStatus(status);
-
- if (status === RESULTS.BLOCKED) {
- FileUtils.showCameraPermissionsAlert();
- }
- })
- .catch(() => {
- setCameraPermissionStatus(RESULTS.UNAVAILABLE);
- });
- };
-
- const takePhoto = useCallback(() => {
- const showCameraAlert = () => {
- Alert.alert(translate('receipt.cameraErrorTitle'), translate('receipt.cameraErrorMessage'));
- };
-
- if (!camera.current) {
- showCameraAlert();
- return;
- }
-
- camera.current
- .takePhoto({
- qualityPrioritization: 'speed',
- flash: flash ? 'on' : 'off',
- })
- .then((photo) => {
- const filePath = `file://${photo.path}`;
- IOU.setMoneyRequestReceipt(filePath, photo.path);
-
- const onSuccess = (receipt) => {
- IOU.replaceReceipt(transactionID, receipt, filePath);
- };
-
- if (transactionID) {
- FileUtils.readFileAsync(filePath, photo.path, onSuccess);
- Navigation.dismissModal();
- return;
- }
-
- IOU.navigateToNextPage(iou, iouType, report, route.path);
- })
- .catch((error) => {
- showCameraAlert();
- Log.warn('Error taking photo', error);
- });
- }, [flash, iouType, iou, report, translate, transactionID, route.path]);
-
- // Wait for camera permission status to render
- if (cameraPermissionStatus == null) {
- return null;
- }
-
- return (
-
- {cameraPermissionStatus !== RESULTS.GRANTED && (
-
-
- {translate('receipt.takePhoto')}
- {translate('receipt.cameraAccess')}
-
-
- )}
- {cameraPermissionStatus === RESULTS.GRANTED && device == null && (
-
-
-
- )}
- {cameraPermissionStatus === RESULTS.GRANTED && device != null && (
-
-
-
-
-
- )}
-
-
- {({openPicker}) => (
- {
- openPicker({
- onPicked: (file) => {
- if (!validateReceipt(file)) {
- return;
- }
- const filePath = file.uri;
- IOU.setMoneyRequestReceipt(filePath, file.name);
-
- if (transactionID) {
- IOU.replaceReceipt(transactionID, file, filePath);
- Navigation.dismissModal();
- return;
- }
-
- IOU.navigateToNextPage(iou, iouType, report, route.path);
- },
- });
- }}
- >
-
-
- )}
-
-
-
-
- setFlash((prevFlash) => !prevFlash)}
- >
-
-
-
-
- );
-}
-
-ReceiptSelector.defaultProps = defaultProps;
-ReceiptSelector.propTypes = propTypes;
-ReceiptSelector.displayName = 'ReceiptSelector';
-
-export default withOnyx({
- iou: {
- key: ONYXKEYS.IOU,
- },
- report: {
- key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT}${lodashGet(route, 'params.reportID', '')}`,
- },
-})(ReceiptSelector);
diff --git a/src/pages/iou/request/MoneyTemporaryForRefactorRequestParticipantsSelector.js b/src/pages/iou/request/MoneyTemporaryForRefactorRequestParticipantsSelector.js
index 4db9c4ce3fb7..61b042052b05 100644
--- a/src/pages/iou/request/MoneyTemporaryForRefactorRequestParticipantsSelector.js
+++ b/src/pages/iou/request/MoneyTemporaryForRefactorRequestParticipantsSelector.js
@@ -12,8 +12,8 @@ import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import useNetwork from '@hooks/useNetwork';
import useThemeStyles from '@hooks/useThemeStyles';
import * as Report from '@libs/actions/Report';
-import * as Browser from '@libs/Browser';
import compose from '@libs/compose';
+import * as DeviceCapabilities from '@libs/DeviceCapabilities';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import * as ReportUtils from '@libs/ReportUtils';
import personalDetailsPropType from '@pages/personalDetailsPropType';
@@ -321,7 +321,7 @@ function MoneyTemporaryForRefactorRequestParticipantsSelector({
shouldShowOptions={isOptionsDataReady}
shouldShowReferralCTA
referralContentType={iouType === 'send' ? CONST.REFERRAL_PROGRAM.CONTENT_TYPES.SEND_MONEY : CONST.REFERRAL_PROGRAM.CONTENT_TYPES.MONEY_REQUEST}
- shouldPreventDefaultFocusOnSelectRow={!Browser.isMobile()}
+ shouldPreventDefaultFocusOnSelectRow={!DeviceCapabilities.canUseTouchScreen()}
shouldDelayFocus
footerContent={isAllowedToSplit && footerContent}
isLoadingNewOptions={isSearchingForReports}
diff --git a/src/pages/iou/request/step/IOURequestStepConfirmation.js b/src/pages/iou/request/step/IOURequestStepConfirmation.js
index d41442edd670..bbe703e50d18 100644
--- a/src/pages/iou/request/step/IOURequestStepConfirmation.js
+++ b/src/pages/iou/request/step/IOURequestStepConfirmation.js
@@ -131,7 +131,7 @@ function IOURequestStepConfirmation({
}, [transaction, iouType, requestType, transactionID, reportID]);
const navigateToAddReceipt = useCallback(() => {
- Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_SCAN.getRoute(iouType, transactionID, reportID, Navigation.getActiveRouteWithoutParams()));
+ Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_SCAN.getRoute(CONST.IOU.ACTION.CREATE, iouType, transactionID, reportID, Navigation.getActiveRouteWithoutParams()));
}, [iouType, transactionID, reportID]);
// When the component mounts, if there is a receipt, see if the image can be read from the disk. If not, redirect the user to the starting step of the flow.
diff --git a/src/pages/iou/request/step/IOURequestStepDistance.js b/src/pages/iou/request/step/IOURequestStepDistance.js
index 66cbd7f135a9..ddf692fedd46 100644
--- a/src/pages/iou/request/step/IOURequestStepDistance.js
+++ b/src/pages/iou/request/step/IOURequestStepDistance.js
@@ -131,6 +131,10 @@ function IOURequestStepDistance({
return ErrorUtils.getLatestErrorField(transaction, 'route');
}
+ if (_.keys(waypoints).length > 2 && _.size(validatedWaypoints) !== _.keys(waypoints).length) {
+ return {0: translate('iou.error.duplicateWaypointsErrorMessage')};
+ }
+
if (_.size(validatedWaypoints) < 2) {
return {0: translate('iou.error.atLeastTwoDifferentWaypoints')};
}
@@ -158,12 +162,12 @@ function IOURequestStepDistance({
const submitWaypoints = useCallback(() => {
// If there is any error or loading state, don't let user go to next page.
- if (_.size(validatedWaypoints) < 2 || hasRouteError || isLoadingRoute || isLoading) {
+ if (_.size(validatedWaypoints) < 2 || (_.keys(waypoints).length > 2 && _.size(validatedWaypoints) !== _.keys(waypoints).length) || hasRouteError || isLoadingRoute || isLoading) {
setHasError(true);
return;
}
navigateToNextStep();
- }, [setHasError, hasRouteError, isLoadingRoute, isLoading, validatedWaypoints, navigateToNextStep]);
+ }, [setHasError, waypoints, hasRouteError, isLoadingRoute, isLoading, validatedWaypoints, navigateToNextStep]);
return (
{/* Show error message if there is route error or there are less than 2 routes and user has tried submitting, */}
- {((hasError && _.size(validatedWaypoints) < 2) || hasRouteError) && (
+ {((hasError && _.size(validatedWaypoints) < 2) || (_.keys(waypoints).length > 2 && _.size(validatedWaypoints) !== _.keys(waypoints).length) || hasRouteError) && (
{
- if (!validateReceipt(file)) {
+ const navigateToConfirmationStep = useCallback(() => {
+ if (backTo) {
+ Navigation.goBack(backTo);
return;
}
- const fileSource = URL.createObjectURL(file);
- IOU.setMoneyRequestReceipt_temporaryForRefactor(transactionID, fileSource, file.name);
-
- if (backTo) {
- Navigation.goBack(backTo);
+ // If the transaction was created from the global create, the person needs to select participants, so take them there.
+ if (isFromGlobalCreate) {
+ Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_PARTICIPANTS.getRoute(iouType, transactionID, reportID));
return;
}
- // When an existing transaction is being edited (eg. not the create transaction flow)
- if (transactionID !== CONST.IOU.OPTIMISTIC_TRANSACTION_ID) {
- IOU.replaceReceipt(transactionID, file, fileSource);
+ // If the transaction was created from the + menu from the composer inside of a chat, the participants can automatically
+ // be added to the transaction (taken from the chat report participants) and then the person is taken to the confirmation step.
+ IOU.setMoneyRequestParticipantsFromReport(transactionID, report);
+ Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(iouType, transactionID, reportID));
+ }, [iouType, report, reportID, transactionID, isFromGlobalCreate, backTo]);
+
+ const updateScanAndNavigate = useCallback(
+ (file, source) => {
+ IOU.replaceReceipt(transactionID, file, source);
+ if (backTo) {
+ Navigation.goBack(backTo);
+ return;
+ }
Navigation.dismissModal();
+ },
+ [backTo, transactionID],
+ );
+
+ /**
+ * Sets the Receipt objects and navigates the user to the next page
+ * @param {Object} file
+ */
+ const setReceiptAndNavigate = (file) => {
+ if (!validateReceipt(file)) {
return;
}
- // If a reportID exists in the report object, it's because the user started this flow from using the + button in the composer
- // inside a report. In this case, the participants can be automatically assigned from the report and the user can skip the participants step and go straight
- // to the confirm step.
- if (report.reportID) {
- IOU.setMoneyRequestParticipantsFromReport(transactionID, report);
- Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(iouType, transactionID, reportID));
+ // Store the receipt on the transaction object in Onyx
+ const source = URL.createObjectURL(file);
+ IOU.setMoneyRequestReceipt(transactionID, source, file.name, action !== CONST.IOU.ACTION.EDIT);
+
+ if (action === CONST.IOU.ACTION.EDIT) {
+ updateScanAndNavigate(file, source);
return;
}
- Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_PARTICIPANTS.getRoute(iouType, transactionID, reportID));
+ navigateToConfirmationStep();
};
const capturePhoto = useCallback(() => {
@@ -150,33 +171,17 @@ function IOURequestStepScan({
}
const imageBase64 = cameraRef.current.getScreenshot();
const filename = `receipt_${Date.now()}.png`;
- const imageFile = FileUtils.base64ToFile(imageBase64, filename);
- const fileSource = URL.createObjectURL(imageFile);
- IOU.setMoneyRequestReceipt_temporaryForRefactor(transactionID, fileSource, imageFile.name);
-
- if (backTo) {
- Navigation.goBack(backTo);
- return;
- }
-
- // When an existing transaction is being edited (eg. not the create transaction flow)
- if (transactionID !== CONST.IOU.OPTIMISTIC_TRANSACTION_ID) {
- IOU.replaceReceipt(transactionID, imageFile, fileSource);
- Navigation.dismissModal();
- return;
- }
+ const file = FileUtils.base64ToFile(imageBase64, filename);
+ const source = URL.createObjectURL(file);
+ IOU.setMoneyRequestReceipt(transactionID, source, file.name, action !== CONST.IOU.ACTION.EDIT);
- // If a reportID exists in the report object, it's because the user started this flow from using the + button in the composer
- // inside a report. In this case, the participants can be automatically assigned from the report and the user can skip the participants step and go straight
- // to the confirm step.
- if (report.reportID) {
- IOU.setMoneyRequestParticipantsFromReport(transactionID, report);
- Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(iouType, transactionID, reportID));
+ if (action === CONST.IOU.ACTION.EDIT) {
+ updateScanAndNavigate(file, source);
return;
}
- Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_PARTICIPANTS.getRoute(iouType, transactionID, reportID));
- }, [cameraRef, report, iouType, transactionID, reportID, backTo]);
+ navigateToConfirmationStep();
+ }, [cameraRef, action, transactionID, updateScanAndNavigate, navigateToConfirmationStep]);
const panResponder = useRef(
PanResponder.create({
diff --git a/src/pages/iou/request/step/IOURequestStepScan/index.native.js b/src/pages/iou/request/step/IOURequestStepScan/index.native.js
index 66896fc178bf..38bcd16faf39 100644
--- a/src/pages/iou/request/step/IOURequestStepScan/index.native.js
+++ b/src/pages/iou/request/step/IOURequestStepScan/index.native.js
@@ -11,6 +11,7 @@ import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';
import ImageSVG from '@components/ImageSVG';
import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
+import transactionPropTypes from '@components/transactionPropTypes';
import useLocalize from '@hooks/useLocalize';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
@@ -36,17 +37,22 @@ const propTypes = {
/* Onyx Props */
/** The report that the transaction belongs to */
report: reportPropTypes,
+
+ /** The transaction (or draft transaction) being changed */
+ transaction: transactionPropTypes,
};
const defaultProps = {
report: {},
+ transaction: {},
};
function IOURequestStepScan({
report,
route: {
- params: {iouType, reportID, transactionID, backTo},
+ params: {action, iouType, reportID, transactionID, backTo},
},
+ transaction: {isFromGlobalCreate},
}) {
const theme = useTheme();
const styles = useThemeStyles();
@@ -118,7 +124,57 @@ function IOURequestStepScan({
});
};
- const takePhoto = useCallback(() => {
+ const navigateBack = () => {
+ Navigation.goBack();
+ };
+
+ const navigateToConfirmationStep = useCallback(() => {
+ if (backTo) {
+ Navigation.goBack(backTo);
+ return;
+ }
+
+ // If the transaction was created from the global create, the person needs to select participants, so take them there.
+ if (isFromGlobalCreate) {
+ Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_PARTICIPANTS.getRoute(iouType, transactionID, reportID));
+ return;
+ }
+
+ // If the transaction was created from the + menu from the composer inside of a chat, the participants can automatically
+ // be added to the transaction (taken from the chat report participants) and then the person is taken to the confirmation step.
+ IOU.setMoneyRequestParticipantsFromReport(transactionID, report);
+ Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(iouType, transactionID, reportID));
+ }, [iouType, report, reportID, transactionID, isFromGlobalCreate, backTo]);
+
+ const updateScanAndNavigate = useCallback(
+ (file, source) => {
+ Navigation.dismissModal();
+ IOU.replaceReceipt(transactionID, file, source);
+ },
+ [transactionID],
+ );
+
+ /**
+ * Sets the Receipt objects and navigates the user to the next page
+ * @param {Object} file
+ */
+ const setReceiptAndNavigate = (file) => {
+ if (!validateReceipt(file)) {
+ return;
+ }
+
+ // Store the receipt on the transaction object in Onyx
+ IOU.setMoneyRequestReceipt(transactionID, file.uri, file.name, action !== CONST.IOU.ACTION.EDIT);
+
+ if (action === CONST.IOU.ACTION.EDIT) {
+ updateScanAndNavigate(file, file.uri);
+ return;
+ }
+
+ navigateToConfirmationStep();
+ };
+
+ const capturePhoto = useCallback(() => {
const showCameraAlert = () => {
Alert.alert(translate('receipt.cameraErrorTitle'), translate('receipt.cameraErrorMessage'));
};
@@ -134,51 +190,30 @@ function IOURequestStepScan({
flash: flash ? 'on' : 'off',
})
.then((photo) => {
- const filePath = `file://${photo.path}`;
- IOU.setMoneyRequestReceipt_temporaryForRefactor(transactionID, filePath, photo.path);
-
- if (backTo) {
- Navigation.goBack(backTo);
- return;
- }
-
- const onSuccess = (receipt) => {
- IOU.replaceReceipt(transactionID, receipt, filePath);
- };
-
- // When an existing transaction is being edited (eg. not the create transaction flow)
- if (transactionID !== CONST.IOU.OPTIMISTIC_TRANSACTION_ID) {
- FileUtils.readFileAsync(filePath, photo.path, onSuccess);
- Navigation.dismissModal();
- return;
- }
-
- // If a reportID exists in the report object, it's because the user started this flow from using the + button in the composer
- // inside a report. In this case, the participants can be automatically assigned from the report and the user can skip the participants step and go straight
- // to the confirm step.
- if (report.reportID) {
- IOU.setMoneyRequestParticipantsFromReport(transactionID, report);
- Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(iouType, transactionID, reportID));
+ // Store the receipt on the transaction object in Onyx
+ const source = `file://${photo.path}`;
+ IOU.setMoneyRequestReceipt(transactionID, source, photo.path, action !== CONST.IOU.ACTION.EDIT);
+
+ if (action === CONST.IOU.ACTION.EDIT) {
+ FileUtils.readFileAsync(source, photo.path, (file) => {
+ updateScanAndNavigate(file, source);
+ });
return;
}
- Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_PARTICIPANTS.getRoute(iouType, transactionID, reportID));
+ navigateToConfirmationStep();
})
.catch((error) => {
showCameraAlert();
Log.warn('Error taking photo', error);
});
- }, [flash, iouType, report, translate, transactionID, reportID, backTo]);
+ }, [flash, action, translate, transactionID, updateScanAndNavigate, navigateToConfirmationStep]);
// Wait for camera permission status to render
if (cameraPermissionStatus == null) {
return null;
}
- const navigateBack = () => {
- Navigation.goBack(backTo || ROUTES.HOME);
- };
-
return (
{
openPicker({
- onPicked: (file) => {
- if (!validateReceipt(file)) {
- return;
- }
- const filePath = file.uri;
- IOU.setMoneyRequestReceipt_temporaryForRefactor(transactionID, filePath, file.name);
-
- if (backTo) {
- Navigation.goBack(backTo);
- return;
- }
-
- // When a transaction is being edited (eg. not in the creation flow)
- if (transactionID !== CONST.IOU.OPTIMISTIC_TRANSACTION_ID) {
- IOU.replaceReceipt(transactionID, file, filePath);
- Navigation.dismissModal();
- return;
- }
-
- // If a reportID exists in the report object, it's because the user started this flow from using the + button in the composer
- // inside a report. In this case, the participants can be automatically assigned from the report and the user can skip the participants step and go straight
- // to the confirm step.
- if (report.reportID) {
- IOU.setMoneyRequestParticipantsFromReport(transactionID, report);
- Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(iouType, transactionID, reportID));
- return;
- }
-
- Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_PARTICIPANTS.getRoute(iouType, transactionID, reportID));
- },
+ onPicked: setReceiptAndNavigate,
});
}}
>
@@ -286,7 +292,7 @@ function IOURequestStepScan({
role={CONST.ACCESSIBILITY_ROLE.BUTTON}
accessibilityLabel={translate('receipt.shutter')}
style={[styles.alignItemsCenter]}
- onPress={takePhoto}
+ onPress={capturePhoto}
>
{
- Navigation.goBack(isEditing ? ROUTES.MONEY_REQUEST_CONFIRMATION.getRoute(iouType, reportID) : ROUTES.HOME);
+ Navigation.goBack(backTo || ROUTES.HOME);
};
const navigateToCurrencySelectionPage = () => {
diff --git a/src/pages/iou/request/step/IOURequestStepTaxRatePage.js b/src/pages/iou/request/step/IOURequestStepTaxRatePage.js
index bae08cd8cb62..cf91ac1e1812 100644
--- a/src/pages/iou/request/step/IOURequestStepTaxRatePage.js
+++ b/src/pages/iou/request/step/IOURequestStepTaxRatePage.js
@@ -1,4 +1,3 @@
-import PropTypes from 'prop-types';
import React from 'react';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
@@ -16,21 +15,13 @@ import * as TransactionUtils from '@libs/TransactionUtils';
import * as IOU from '@userActions/IOU';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
+import IOURequestStepRoutePropTypes from './IOURequestStepRoutePropTypes';
import withFullTransactionOrNotFound from './withFullTransactionOrNotFound';
import withWritableReportOrNotFound from './withWritableReportOrNotFound';
const propTypes = {
- /** Route from navigation */
- route: PropTypes.shape({
- /** Params from the route */
- params: PropTypes.shape({
- /** The type of IOU report, i.e. bill, request, send */
- iouType: PropTypes.string,
-
- /** The report ID of the IOU */
- reportID: PropTypes.string,
- }),
- }).isRequired,
+ /** Navigation route context info provided by react navigation */
+ route: IOURequestStepRoutePropTypes.isRequired,
/* Onyx Props */
/** Collection of tax rates attached to a policy */
@@ -52,16 +43,16 @@ const getTaxAmount = (taxRates, selectedTaxRate, amount) => {
function IOURequestStepTaxRatePage({
route: {
- params: {iouType, reportID},
+ params: {backTo},
},
policyTaxRates,
transaction,
}) {
const {translate} = useLocalize();
- function navigateBack() {
- Navigation.goBack(ROUTES.MONEY_REQUEST_CONFIRMATION.getRoute(iouType, reportID));
- }
+ const navigateBack = () => {
+ Navigation.goBack(backTo || ROUTES.HOME);
+ };
const defaultTaxKey = policyTaxRates.defaultExternalID;
const defaultTaxName = (defaultTaxKey && `${policyTaxRates.taxes[defaultTaxKey].name} (${policyTaxRates.taxes[defaultTaxKey].value}) • ${translate('common.default')}`) || '';
@@ -73,7 +64,7 @@ function IOURequestStepTaxRatePage({
IOU.setMoneyRequestTaxRate(transaction.transactionID, taxes);
IOU.setMoneyRequestTaxAmount(transaction.transactionID, amountInSmallestCurrencyUnits);
- Navigation.goBack(ROUTES.MONEY_REQUEST_CONFIRMATION.getRoute(iouType, reportID));
+ Navigation.goBack(backTo || ROUTES.HOME);
};
return (
diff --git a/src/pages/iou/request/step/withFullTransactionOrNotFound.js b/src/pages/iou/request/step/withFullTransactionOrNotFound.js
index 1d5fdb3f6abd..001159f944e9 100644
--- a/src/pages/iou/request/step/withFullTransactionOrNotFound.js
+++ b/src/pages/iou/request/step/withFullTransactionOrNotFound.js
@@ -6,6 +6,7 @@ import {withOnyx} from 'react-native-onyx';
import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView';
import transactionPropTypes from '@components/transactionPropTypes';
import getComponentDisplayName from '@libs/getComponentDisplayName';
+import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import IOURequestStepRoutePropTypes from './IOURequestStepRoutePropTypes';
@@ -67,7 +68,10 @@ export default function (WrappedComponent) {
return withOnyx({
transaction: {
- key: ({route}) => `${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${lodashGet(route, 'params.transactionID', 0)}`,
+ key: ({route}) => {
+ const transactionID = lodashGet(route, 'params.transactionID', 0);
+ return `${transactionID === CONST.IOU.OPTIMISTIC_TRANSACTION_ID ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`;
+ },
},
})(WithFullTransactionOrNotFoundWithRef);
}
diff --git a/src/pages/iou/steps/MoneyRequstParticipantsPage/MoneyRequestParticipantsSelector.js b/src/pages/iou/steps/MoneyRequstParticipantsPage/MoneyRequestParticipantsSelector.js
index f51e6d7e9fdd..38f7ac7cd6ef 100755
--- a/src/pages/iou/steps/MoneyRequstParticipantsPage/MoneyRequestParticipantsSelector.js
+++ b/src/pages/iou/steps/MoneyRequstParticipantsPage/MoneyRequestParticipantsSelector.js
@@ -13,8 +13,8 @@ import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import useNetwork from '@hooks/useNetwork';
import useThemeStyles from '@hooks/useThemeStyles';
import * as Report from '@libs/actions/Report';
-import * as Browser from '@libs/Browser';
import compose from '@libs/compose';
+import * as DeviceCapabilities from '@libs/DeviceCapabilities';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import * as ReportUtils from '@libs/ReportUtils';
import reportPropTypes from '@pages/reportPropTypes';
@@ -334,7 +334,7 @@ function MoneyRequestParticipantsSelector({
shouldShowOptions={isOptionsDataReady}
shouldShowReferralCTA
referralContentType={iouType === 'send' ? CONST.REFERRAL_PROGRAM.CONTENT_TYPES.SEND_MONEY : CONST.REFERRAL_PROGRAM.CONTENT_TYPES.MONEY_REQUEST}
- shouldPreventDefaultFocusOnSelectRow={!Browser.isMobile()}
+ shouldPreventDefaultFocusOnSelectRow={!DeviceCapabilities.canUseTouchScreen()}
shouldDelayFocus
footerContent={isAllowedToSplit && footerContent}
isLoadingNewOptions={isSearchingForReports}
diff --git a/src/pages/settings/Security/SecuritySettingsPage.js b/src/pages/settings/Security/SecuritySettingsPage.tsx
similarity index 69%
rename from src/pages/settings/Security/SecuritySettingsPage.js
rename to src/pages/settings/Security/SecuritySettingsPage.tsx
index 392a264977c6..ad563282d0cd 100644
--- a/src/pages/settings/Security/SecuritySettingsPage.js
+++ b/src/pages/settings/Security/SecuritySettingsPage.tsx
@@ -1,42 +1,22 @@
-import PropTypes from 'prop-types';
import React, {useMemo} from 'react';
import {ScrollView, View} from 'react-native';
-import {withOnyx} from 'react-native-onyx';
-import _ from 'underscore';
import * as Expensicons from '@components/Icon/Expensicons';
import IllustratedHeaderPageLayout from '@components/IllustratedHeaderPageLayout';
import LottieAnimations from '@components/LottieAnimations';
import MenuItemList from '@components/MenuItemList';
-import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
+import useLocalize from '@hooks/useLocalize';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import useWaitForNavigation from '@hooks/useWaitForNavigation';
-import compose from '@libs/compose';
import Navigation from '@libs/Navigation/Navigation';
-import ONYXKEYS from '@src/ONYXKEYS';
+import type {TranslationPaths} from '@src/languages/types';
import ROUTES from '@src/ROUTES';
import SCREENS from '@src/SCREENS';
-const propTypes = {
- ...withLocalizePropTypes,
-
- /* Onyx Props */
-
- /** Holds information about the users account that is logging in */
- account: PropTypes.shape({
- /** Whether this account has 2FA enabled or not */
- requiresTwoFactorAuth: PropTypes.bool,
- }),
-};
-
-const defaultProps = {
- account: {},
-};
-
-function SecuritySettingsPage(props) {
+function SecuritySettingsPage() {
const theme = useTheme();
const styles = useThemeStyles();
- const {translate} = props;
+ const {translate} = useLocalize();
const waitForNavigate = useWaitForNavigation();
const menuItems = useMemo(() => {
@@ -53,13 +33,13 @@ function SecuritySettingsPage(props) {
},
];
- return _.map(baseMenuItems, (item) => ({
+ return baseMenuItems.map((item) => ({
key: item.translationKey,
- title: translate(item.translationKey),
+ title: translate(item.translationKey as TranslationPaths),
icon: item.icon,
- iconRight: item.iconRight,
onPress: item.action,
shouldShowRightIcon: true,
+ link: '',
}));
}, [translate, waitForNavigate]);
@@ -83,13 +63,6 @@ function SecuritySettingsPage(props) {
);
}
-SecuritySettingsPage.propTypes = propTypes;
-SecuritySettingsPage.defaultProps = defaultProps;
SecuritySettingsPage.displayName = 'SettingSecurityPage';
-export default compose(
- withLocalize,
- withOnyx({
- account: {key: ONYXKEYS.ACCOUNT},
- }),
-)(SecuritySettingsPage);
+export default SecuritySettingsPage;
diff --git a/src/pages/settings/Wallet/Card/BaseGetPhysicalCard.js b/src/pages/settings/Wallet/Card/BaseGetPhysicalCard.js
index 1d1ce906189b..f1c3fbe90533 100644
--- a/src/pages/settings/Wallet/Card/BaseGetPhysicalCard.js
+++ b/src/pages/settings/Wallet/Card/BaseGetPhysicalCard.js
@@ -3,7 +3,7 @@ import React, {useCallback, useEffect, useRef} from 'react';
import {Text} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
-import Form from '@components/Form';
+import FormProvider from '@components/Form/FormProvider';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
import ScreenWrapper from '@components/ScreenWrapper';
import useThemeStyles from '@hooks/useThemeStyles';
@@ -114,16 +114,15 @@ const defaultProps = {
loginList: {},
isConfirmation: false,
renderContent: (onSubmit, submitButtonText, styles, children = () => {}, onValidate = () => ({})) => (
-
+
),
onValidate: () => ({}),
};
diff --git a/src/pages/settings/Wallet/Card/GetPhysicalCardName.js b/src/pages/settings/Wallet/Card/GetPhysicalCardName.js
index 0040dac8b75f..abe94e7a0c2f 100644
--- a/src/pages/settings/Wallet/Card/GetPhysicalCardName.js
+++ b/src/pages/settings/Wallet/Card/GetPhysicalCardName.js
@@ -2,6 +2,7 @@ import PropTypes from 'prop-types';
import React from 'react';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
+import InputWrapper from '@components/Form/InputWrapper';
import TextInput from '@components/TextInput';
import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
@@ -72,7 +73,8 @@ function GetPhysicalCardName({
title={translate('getPhysicalCard.header')}
onValidate={onValidate}
>
-
-
diff --git a/src/pages/settings/Wallet/Card/GetPhysicalCardPhone.js b/src/pages/settings/Wallet/Card/GetPhysicalCardPhone.js
index 3d4c7f4ac6fb..27897c08d125 100644
--- a/src/pages/settings/Wallet/Card/GetPhysicalCardPhone.js
+++ b/src/pages/settings/Wallet/Card/GetPhysicalCardPhone.js
@@ -1,13 +1,13 @@
-import {parsePhoneNumber} from 'awesome-phonenumber';
import Str from 'expensify-common/lib/str';
import PropTypes from 'prop-types';
import React from 'react';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
+import InputWrapper from '@components/Form/InputWrapper';
import TextInput from '@components/TextInput';
import useLocalize from '@hooks/useLocalize';
-import useThemeStyles from '@hooks/useThemeStyles';
import FormUtils from '@libs/FormUtils';
+import {parsePhoneNumber} from '@libs/PhoneNumber';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
@@ -42,7 +42,6 @@ function GetPhysicalCardPhone({
params: {domain},
},
}) {
- const styles = useThemeStyles();
const {translate} = useLocalize();
const onValidate = (values) => {
@@ -66,14 +65,14 @@ function GetPhysicalCardPhone({
title={translate('getPhysicalCard.header')}
onValidate={onValidate}
>
-
diff --git a/src/pages/settings/Wallet/ExpensifyCardPage.js b/src/pages/settings/Wallet/ExpensifyCardPage.js
index 376c69beb955..3c44f806fdb8 100644
--- a/src/pages/settings/Wallet/ExpensifyCardPage.js
+++ b/src/pages/settings/Wallet/ExpensifyCardPage.js
@@ -265,7 +265,7 @@ function ExpensifyCardPage({
/>
>
)}
- {!_.isEmpty(physicalCard) && (
+ {physicalCard.state === CONST.EXPENSIFY_CARD.STATE.OPEN && (
<>
-
+
navigateToChooseTransferAccount(selectedAccount.accountType)}
+ displayInDefaultIconColor
/>
)}
diff --git a/src/pages/signin/LoginForm/BaseLoginForm.js b/src/pages/signin/LoginForm/BaseLoginForm.js
index de2f2900c58d..8fcea461eacd 100644
--- a/src/pages/signin/LoginForm/BaseLoginForm.js
+++ b/src/pages/signin/LoginForm/BaseLoginForm.js
@@ -1,5 +1,4 @@
import {useIsFocused} from '@react-navigation/native';
-import {parsePhoneNumber} from 'awesome-phonenumber';
import Str from 'expensify-common/lib/str';
import PropTypes from 'prop-types';
import React, {forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
@@ -25,6 +24,7 @@ import * as ErrorUtils from '@libs/ErrorUtils';
import isInputAutoFilled from '@libs/isInputAutoFilled';
import Log from '@libs/Log';
import * as LoginUtils from '@libs/LoginUtils';
+import {parsePhoneNumber} from '@libs/PhoneNumber';
import * as PolicyUtils from '@libs/PolicyUtils';
import * as ValidationUtils from '@libs/ValidationUtils';
import Visibility from '@libs/Visibility';
@@ -245,6 +245,15 @@ function LoginForm(props) {
isInputFocused() {
return input.current && input.current.isFocused();
},
+ clearDataAndFocus(clearLogin = true) {
+ if (!input.current) {
+ return;
+ }
+ if (clearLogin) {
+ Session.clearSignInData();
+ }
+ input.current.focus();
+ },
}));
const formErrorText = useMemo(() => (formError ? translate(formError) : ''), [formError, translate]);
diff --git a/src/pages/signin/LoginForm/index.js b/src/pages/signin/LoginForm/index.js
index 91aba70a866f..e861100c25fe 100644
--- a/src/pages/signin/LoginForm/index.js
+++ b/src/pages/signin/LoginForm/index.js
@@ -1,18 +1,24 @@
import PropTypes from 'prop-types';
import React from 'react';
+import refPropTypes from '@components/refPropTypes';
import BaseLoginForm from './BaseLoginForm';
const propTypes = {
/** Function used to scroll to the top of the page */
scrollPageToTop: PropTypes.func,
+
+ /** A reference so we can expose clearDataAndFocus */
+ innerRef: refPropTypes,
};
const defaultProps = {
scrollPageToTop: undefined,
+ innerRef: () => {},
};
-function LoginForm(props) {
+function LoginForm({innerRef, ...props}) {
return (
@@ -23,4 +29,14 @@ LoginForm.displayName = 'LoginForm';
LoginForm.propTypes = propTypes;
LoginForm.defaultProps = defaultProps;
-export default LoginForm;
+const LoginFormWithRef = React.forwardRef((props, ref) => (
+
+));
+
+LoginFormWithRef.displayName = 'LoginFormWithRef';
+
+export default LoginFormWithRef;
diff --git a/src/pages/signin/LoginForm/index.native.js b/src/pages/signin/LoginForm/index.native.js
index 87258e69165f..3187faac8127 100644
--- a/src/pages/signin/LoginForm/index.native.js
+++ b/src/pages/signin/LoginForm/index.native.js
@@ -1,17 +1,23 @@
import PropTypes from 'prop-types';
import React, {useEffect, useRef} from 'react';
+import _ from 'underscore';
+import refPropTypes from '@components/refPropTypes';
import AppStateMonitor from '@libs/AppStateMonitor';
import BaseLoginForm from './BaseLoginForm';
const propTypes = {
/** Function used to scroll to the top of the page */
scrollPageToTop: PropTypes.func,
+
+ /** A reference so we can expose clearDataAndFocus */
+ innerRef: refPropTypes,
};
const defaultProps = {
scrollPageToTop: undefined,
+ innerRef: () => {},
};
-function LoginForm(props) {
+function LoginForm({innerRef, ...props}) {
const loginFormRef = useRef();
const {scrollPageToTop} = props;
@@ -36,7 +42,15 @@ function LoginForm(props) {
(loginFormRef.current = ref)}
+ ref={(ref) => {
+ loginFormRef.current = ref;
+ if (typeof innerRef === 'function') {
+ innerRef(ref);
+ } else if (innerRef && _.has(innerRef, 'current')) {
+ // eslint-disable-next-line no-param-reassign
+ innerRef.current = ref;
+ }
+ }}
/>
);
}
@@ -45,4 +59,14 @@ LoginForm.displayName = 'LoginForm';
LoginForm.propTypes = propTypes;
LoginForm.defaultProps = defaultProps;
-export default LoginForm;
+const LoginFormWithRef = React.forwardRef((props, ref) => (
+
+));
+
+LoginFormWithRef.displayName = 'LoginFormWithRef';
+
+export default LoginFormWithRef;
diff --git a/src/pages/signin/SignInPage.js b/src/pages/signin/SignInPage.js
index 8cb0ef9907af..9d5b51d667ff 100644
--- a/src/pages/signin/SignInPage.js
+++ b/src/pages/signin/SignInPage.js
@@ -140,6 +140,7 @@ function SignInPageInner({credentials, account, isInModal, activeClients, prefer
const shouldShowSmallScreen = isSmallScreenWidth || isInModal;
const safeAreaInsets = useSafeAreaInsets();
const signInPageLayoutRef = useRef();
+ const loginFormRef = useRef();
/** This state is needed to keep track of if user is using recovery code instead of 2fa code,
* and we need it here since welcome text(`welcomeText`) also depends on it */
const [isUsingRecoveryCode, setIsUsingRecoveryCode] = useState(false);
@@ -242,6 +243,11 @@ function SignInPageInner({credentials, account, isInModal, activeClients, prefer
Log.warn('SignInPage in unexpected state!');
}
+ const navigateFocus = () => {
+ signInPageLayoutRef.current.scrollPageToTop();
+ loginFormRef.current.clearDataAndFocus();
+ };
+
return (
// Bottom SafeAreaView is removed so that login screen svg displays correctly on mobile.
// The SVG should flow under the Home Indicator on iOS.
@@ -253,10 +259,12 @@ function SignInPageInner({credentials, account, isInModal, activeClients, prefer
shouldShowWelcomeText={shouldShowWelcomeText}
ref={signInPageLayoutRef}
shouldShowSmallScreen={shouldShowSmallScreen}
+ navigateFocus={navigateFocus}
>
{/* LoginForm must use the isVisible prop. This keeps it mounted, but visually hidden
so that password managers can access the values. Conditionally rendering this component will break this feature. */}
{
- scrollPageToTop();
-
- // We need to clear sign in data in case the user is already in the ValidateCodeForm or PasswordForm pages
- Session.clearSignInData();
-};
-
-const columns = ({scrollPageToTop}) => [
+const columns = ({navigateFocus}) => [
{
translationPath: 'footer.features',
rows: [
@@ -135,11 +127,11 @@ const columns = ({scrollPageToTop}) => [
translationPath: 'footer.getStarted',
rows: [
{
- onPress: () => navigateHome(scrollPageToTop),
+ onPress: () => navigateFocus(),
translationPath: 'footer.createAccount',
},
{
- onPress: () => navigateHome(scrollPageToTop),
+ onPress: () => navigateFocus(),
translationPath: 'footer.logIn',
},
],
@@ -172,7 +164,7 @@ function Footer(props) {
) : null}
- {_.map(columns({scrollPageToTop: props.scrollPageToTop}), (column, i) => (
+ {_.map(columns({navigateFocus: props.navigateFocus}), (column, i) => (
-
+
@@ -179,7 +179,7 @@ function SignInPageLayout(props) {
diff --git a/src/pages/workspace/WorkspaceInvitePage.js b/src/pages/workspace/WorkspaceInvitePage.js
index 589c4971506b..c7a1da7b64ff 100644
--- a/src/pages/workspace/WorkspaceInvitePage.js
+++ b/src/pages/workspace/WorkspaceInvitePage.js
@@ -1,3 +1,4 @@
+import Str from 'expensify-common/lib/str';
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import React, {useEffect, useMemo, useState} from 'react';
@@ -12,10 +13,12 @@ import SelectionList from '@components/SelectionList';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useThemeStyles from '@hooks/useThemeStyles';
-import * as Browser from '@libs/Browser';
import compose from '@libs/compose';
+import * as DeviceCapabilities from '@libs/DeviceCapabilities';
+import * as LoginUtils from '@libs/LoginUtils';
import Navigation from '@libs/Navigation/Navigation';
import * as OptionsListUtils from '@libs/OptionsListUtils';
+import {parsePhoneNumber} from '@libs/PhoneNumber';
import * as PolicyUtils from '@libs/PolicyUtils';
import * as Policy from '@userActions/Policy';
import CONST from '@src/CONST';
@@ -141,8 +144,10 @@ function WorkspaceInvitePage(props) {
filterSelectedOptions = _.filter(selectedOptions, (option) => {
const accountID = lodashGet(option, 'accountID', null);
const isOptionInPersonalDetails = _.some(personalDetails, (personalDetail) => personalDetail.accountID === accountID);
+ const parsedPhoneNumber = parsePhoneNumber(LoginUtils.appendCountryCode(Str.removeSMSDomain(searchTerm)));
+ const searchValue = parsedPhoneNumber.possible ? parsedPhoneNumber.number.e164 : searchTerm.toLowerCase();
- const isPartOfSearchTerm = option.text.toLowerCase().includes(searchTerm.trim().toLowerCase());
+ const isPartOfSearchTerm = option.text.toLowerCase().includes(searchValue) || option.login.toLowerCase().includes(searchValue);
return isPartOfSearchTerm || isOptionInPersonalDetails;
});
}
@@ -281,7 +286,7 @@ function WorkspaceInvitePage(props) {
onConfirm={inviteUser}
showScrollIndicator
showLoadingPlaceholder={!didScreenTransitionEnd || !OptionsListUtils.isPersonalDetailsReady(props.personalDetails)}
- shouldPreventDefaultFocusOnSelectRow={!Browser.isMobile()}
+ shouldPreventDefaultFocusOnSelectRow={!DeviceCapabilities.canUseTouchScreen()}
/>
diff --git a/src/pages/workspace/WorkspaceNewRoomPage.js b/src/pages/workspace/WorkspaceNewRoomPage.js
index 8585fdf7ab97..21c93b87806a 100644
--- a/src/pages/workspace/WorkspaceNewRoomPage.js
+++ b/src/pages/workspace/WorkspaceNewRoomPage.js
@@ -4,7 +4,6 @@ import {View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import BlockingView from '@components/BlockingViews/BlockingView';
-import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView';
import Button from '@components/Button';
import FormProvider from '@components/Form/FormProvider';
import InputWrapper from '@components/Form/InputWrapper';
@@ -25,7 +24,6 @@ import useWindowDimensions from '@hooks/useWindowDimensions';
import compose from '@libs/compose';
import * as ErrorUtils from '@libs/ErrorUtils';
import Navigation from '@libs/Navigation/Navigation';
-import Permissions from '@libs/Permissions';
import * as PolicyUtils from '@libs/PolicyUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as ValidationUtils from '@libs/ValidationUtils';
@@ -48,9 +46,6 @@ const propTypes = {
policyID: PropTypes.string,
}),
- /** List of betas available to current user */
- betas: PropTypes.arrayOf(PropTypes.string),
-
/** The list of policies the user has access to. */
policies: PropTypes.objectOf(
PropTypes.shape({
@@ -84,7 +79,6 @@ const propTypes = {
}),
};
const defaultProps = {
- betas: [],
reports: {},
policies: {},
formState: {
@@ -246,96 +240,94 @@ function WorkspaceNewRoomPage(props) {
);
return (
-
-
- {({insets}) =>
- workspaceOptions.length === 0 ? (
- renderEmptyWorkspaceView()
- ) : (
-
+ {({insets}) =>
+ workspaceOptions.length === 0 ? (
+ renderEmptyWorkspaceView()
+ ) : (
+
+
-
-
-
-
-
-
-
-
-
-
- {isPolicyAdmin && (
-
-
-
- )}
-
+
+
+
+
+
+
+
+
+
+ {isPolicyAdmin && (
+
-
- {isSmallScreenWidth && }
-
- )
- }
-
-
+ )}
+
+
+
+
+ {isSmallScreenWidth && }
+
+ )
+ }
+
);
}
diff --git a/src/styles/index.ts b/src/styles/index.ts
index a6ac2e269eb0..097391f72dd2 100644
--- a/src/styles/index.ts
+++ b/src/styles/index.ts
@@ -3327,6 +3327,13 @@ const styles = (theme: ThemeColors) =>
verticalAlign: 'middle',
},
+ stickyHeaderEmoji: (isSmallScreenWidth: boolean, windowWidth: number) =>
+ ({
+ position: 'absolute',
+ width: isSmallScreenWidth ? windowWidth - 32 : CONST.EMOJI_PICKER_SIZE.WIDTH - 32,
+ ...spacing.mh4,
+ } satisfies ViewStyle),
+
reactionCounterText: {
fontSize: 13,
marginLeft: 4,
diff --git a/src/styles/utils/index.ts b/src/styles/utils/index.ts
index e2d237c6bbae..8b040dd8d72c 100644
--- a/src/styles/utils/index.ts
+++ b/src/styles/utils/index.ts
@@ -1,5 +1,6 @@
-import type {Animated, DimensionValue, ImageStyle, PressableStateCallbackType, StyleProp, TextStyle, ViewStyle} from 'react-native';
import {StyleSheet} from 'react-native';
+import type {Animated, DimensionValue, ImageStyle, PressableStateCallbackType, StyleProp, TextStyle, ViewStyle} from 'react-native';
+import type {OnyxEntry} from 'react-native-onyx';
import type {EdgeInsets} from 'react-native-safe-area-context';
import type {ValueOf} from 'type-fest';
import * as Browser from '@libs/Browser';
@@ -275,9 +276,9 @@ function getDefaultWorkspaceAvatarColor(workspaceName: string): ViewStyle {
/**
* Helper method to return eReceipt color code
*/
-function getEReceiptColorCode(transaction: Transaction): EReceiptColorName {
+function getEReceiptColorCode(transaction: OnyxEntry): EReceiptColorName {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
- const transactionID = transaction.parentTransactionID || transaction.transactionID || '';
+ const transactionID = transaction?.parentTransactionID || transaction?.transactionID || '';
const colorHash = UserUtils.hashText(transactionID.trim(), eReceiptColors.length);
@@ -1351,6 +1352,7 @@ const createStyleUtils = (theme: ThemeColors, styles: ThemeStyles) => ({
...(isReportActionItemGrouped ? positioning.tn8 : positioning.tn4),
...positioning.r4,
...styles.cursorDefault,
+ ...styles.userSelectNone,
position: 'absolute',
zIndex: 8,
}),
diff --git a/src/types/global.d.ts b/src/types/global.d.ts
index a3326ed4d008..0a122f083c8d 100644
--- a/src/types/global.d.ts
+++ b/src/types/global.d.ts
@@ -26,3 +26,10 @@ declare module '*.lottie' {
const value: LottieViewProps['source'];
export default value;
}
+
+// Global methods for Onyx key management for debugging purposes
+// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
+interface Window {
+ enableMemoryOnlyKeys: () => void;
+ disableMemoryOnlyKeys: () => void;
+}
diff --git a/src/types/modules/appleAuth.d.ts b/src/types/modules/appleAuth.d.ts
new file mode 100644
index 000000000000..1394768d613e
--- /dev/null
+++ b/src/types/modules/appleAuth.d.ts
@@ -0,0 +1,29 @@
+type ClientConfig = {
+ clientId?: string;
+ redirectURI?: string;
+ scope?: string;
+ state?: string;
+ nonce?: string;
+ usePopup?: boolean;
+};
+
+type Auth = {
+ init: (config: ClientConfig) => void;
+ signIn: (signInConfig?: ClientConfig) => Promise;
+ renderButton: () => void;
+};
+
+type AppleID = {
+ auth: Auth;
+};
+
+declare global {
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
+ interface Window {
+ AppleID: AppleID;
+ appleAuthScriptLoaded: boolean;
+ }
+}
+
+// We used the export {} line to mark this file as an external module
+export {};
diff --git a/src/types/modules/dom.d.ts b/src/types/modules/dom.d.ts
new file mode 100644
index 000000000000..60bd9c9ae983
--- /dev/null
+++ b/src/types/modules/dom.d.ts
@@ -0,0 +1,24 @@
+type AppleIDSignInOnSuccessEvent = {
+ detail: {
+ authorization: {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ id_token: string;
+ };
+ };
+};
+
+type AppleIDSignInOnFailureEvent = {
+ detail: {
+ error: string;
+ };
+};
+
+declare global {
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
+ interface DocumentEventMap extends GlobalEventHandlersEventMap {
+ AppleIDSignInOnSuccess: AppleIDSignInOnSuccessEvent;
+ AppleIDSignInOnFailure: AppleIDSignInOnFailureEvent;
+ }
+}
+
+export type {AppleIDSignInOnFailureEvent, AppleIDSignInOnSuccessEvent};
diff --git a/src/types/modules/google.d.ts b/src/types/modules/google.d.ts
new file mode 100644
index 000000000000..3c29e62bf9b3
--- /dev/null
+++ b/src/types/modules/google.d.ts
@@ -0,0 +1,35 @@
+type Response = {
+ credential: string;
+};
+
+type Initialize = {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ client_id: string;
+ callback: (response: Response) => void;
+};
+
+type Options = {
+ theme?: 'outline';
+ size?: 'large';
+ type?: 'standard' | 'icon';
+ shape?: 'circle' | 'pill';
+ width?: string;
+};
+
+type Google = {
+ accounts: {
+ id: {
+ initialize: ({client_id, callback}: Initialize) => void;
+ renderButton: (client_id, options: Options) => void;
+ };
+ };
+};
+
+declare global {
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
+ interface Window {
+ google: Google;
+ }
+}
+
+export default Response;
diff --git a/src/types/modules/navigator.d.ts b/src/types/modules/navigator.d.ts
new file mode 100644
index 000000000000..aca32a543b67
--- /dev/null
+++ b/src/types/modules/navigator.d.ts
@@ -0,0 +1,9 @@
+declare global {
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
+ interface Navigator {
+ userLanguage: string;
+ }
+}
+
+// We used the export {} line to mark this file as an external module
+export {};
diff --git a/src/types/onyx/Login.ts b/src/types/onyx/Login.ts
index 7a4093d4ab11..317c2b95c9b6 100644
--- a/src/types/onyx/Login.ts
+++ b/src/types/onyx/Login.ts
@@ -10,6 +10,9 @@ type Login = {
/** Date login was validated, used to show info indicator status */
validatedDate?: string;
+ /** Whether the user validation code was sent */
+ validateCodeSent?: boolean;
+
/** Field-specific server side errors keyed by microtime */
errorFields?: OnyxCommon.ErrorFields;
diff --git a/src/types/onyx/Policy.ts b/src/types/onyx/Policy.ts
index ff3a5e1dd23c..da4522487a7a 100644
--- a/src/types/onyx/Policy.ts
+++ b/src/types/onyx/Policy.ts
@@ -36,7 +36,7 @@ type Policy = {
owner: string;
/** The accountID of the policy owner */
- ownerAccountID: number;
+ ownerAccountID?: number;
/** The output currency for the policy */
outputCurrency: string;
@@ -51,7 +51,7 @@ type Policy = {
pendingAction?: OnyxCommon.PendingAction;
/** A list of errors keyed by microtime */
- errors: OnyxCommon.Errors;
+ errors?: OnyxCommon.Errors;
/** Whether this policy was loaded from a policy summary, or loaded completely with all of its values */
isFromFullPolicy?: boolean;
@@ -69,13 +69,13 @@ type Policy = {
isPolicyExpenseChatEnabled: boolean;
/** Whether the auto reporting is enabled */
- autoReporting: boolean;
+ autoReporting?: boolean;
/** The scheduled submit frequency set up on the this policy */
- autoReportingFrequency: ValueOf;
+ autoReportingFrequency?: ValueOf;
/** Whether the scheduled submit is enabled */
- isHarvestingEnabled: boolean;
+ isHarvestingEnabled?: boolean;
/** The accountID of manager who the employee submits their expenses to on paid policies */
submitsTo?: number;
diff --git a/src/types/onyx/ReportAction.ts b/src/types/onyx/ReportAction.ts
index b727bc40ce93..d81335b284ac 100644
--- a/src/types/onyx/ReportAction.ts
+++ b/src/types/onyx/ReportAction.ts
@@ -194,6 +194,9 @@ type ReportActionBase = {
/** We manually add this field while sorting to detect the end of the list */
isNewestReportAction?: boolean;
+
+ /** Flag for checking if data is from optimistic data */
+ isOptimisticAction?: boolean;
};
type ReportAction = ReportActionBase & OriginalMessage;
@@ -201,4 +204,4 @@ type ReportAction = ReportActionBase & OriginalMessage;
type ReportActions = Record;
export default ReportAction;
-export type {ReportActions, ReportActionBase, Message, LinkMetadata};
+export type {ReportActions, ReportActionBase, Message, LinkMetadata, OriginalMessage};
diff --git a/src/types/onyx/ReportActionReactions.ts b/src/types/onyx/ReportActionReactions.ts
index 0173fcf244f5..be117aafc4c5 100644
--- a/src/types/onyx/ReportActionReactions.ts
+++ b/src/types/onyx/ReportActionReactions.ts
@@ -24,7 +24,7 @@ type ReportActionReaction = {
users: UsersReactions;
/** Is this action pending? */
- pendingAction: OnyxCommon.PendingAction;
+ pendingAction?: OnyxCommon.PendingAction;
};
type ReportActionReactions = Record;
diff --git a/src/types/onyx/Request.ts b/src/types/onyx/Request.ts
index fa87e1d194c2..03d44b1ce94c 100644
--- a/src/types/onyx/Request.ts
+++ b/src/types/onyx/Request.ts
@@ -4,6 +4,7 @@ import type Response from './Response';
type OnyxData = {
successData?: OnyxUpdate[];
failureData?: OnyxUpdate[];
+ finallyData?: OnyxUpdate[];
optimisticData?: OnyxUpdate[];
};
@@ -17,6 +18,7 @@ type RequestData = {
shouldUseSecure?: boolean;
successData?: OnyxUpdate[];
failureData?: OnyxUpdate[];
+ finallyData?: OnyxUpdate[];
idempotencyKey?: string;
resolve?: (value: Response) => void;
diff --git a/src/types/onyx/Response.ts b/src/types/onyx/Response.ts
index b06ec9766842..5e606738c56d 100644
--- a/src/types/onyx/Response.ts
+++ b/src/types/onyx/Response.ts
@@ -11,6 +11,7 @@ type Response = {
jsonCode?: number | string;
onyxData?: OnyxUpdate[];
requestID?: string;
+ reportID?: string;
shouldPauseQueue?: boolean;
authToken?: string;
encryptedAuthToken?: string;
diff --git a/tests/actions/IOUTest.js b/tests/actions/IOUTest.js
index 0a1ac84d52f9..3ba19199c30a 100644
--- a/tests/actions/IOUTest.js
+++ b/tests/actions/IOUTest.js
@@ -1991,7 +1991,8 @@ describe('actions/IOU', () => {
});
createIOUAction = _.find(reportActionsForReport, (reportAction) => reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.IOU);
- expect(createIOUAction).toBeFalsy();
+ // Then the IOU Action should be truthy for offline support.
+ expect(createIOUAction).toBeTruthy();
// Then we check if the transaction is removed from the transactions collection
const t = await new Promise((resolve) => {
@@ -2009,6 +2010,7 @@ describe('actions/IOU', () => {
// Given fetch operations are resumed
fetch.resume();
+ await waitForBatchedUpdates();
// Then we recheck the IOU report action from the report actions collection
reportActionsForReport = await new Promise((resolve) => {
@@ -2059,11 +2061,12 @@ describe('actions/IOU', () => {
});
});
- // Then the report should be falsy (indicating deletion)
- expect(report).toBeFalsy();
+ // Then the report should be truthy for offline support
+ expect(report).toBeTruthy();
// Given the resumed fetch state
fetch.resume();
+ await waitForBatchedUpdates();
report = await new Promise((resolve) => {
const connectionID = Onyx.connect({
@@ -2076,7 +2079,7 @@ describe('actions/IOU', () => {
});
});
- // Then the report should still be falsy (confirming deletion persisted)
+ // Then the report should be falsy so that there is no trace of the money request.
expect(report).toBeFalsy();
});
diff --git a/tests/actions/PolicyTest.js b/tests/actions/PolicyTest.js
new file mode 100644
index 000000000000..5a994aaf600e
--- /dev/null
+++ b/tests/actions/PolicyTest.js
@@ -0,0 +1,191 @@
+import _ from 'lodash';
+import Onyx from 'react-native-onyx';
+import CONST from '@src/CONST';
+import OnyxUpdateManager from '../../src/libs/actions/OnyxUpdateManager';
+import * as Policy from '../../src/libs/actions/Policy';
+import ONYXKEYS from '../../src/ONYXKEYS';
+import * as TestHelper from '../utils/TestHelper';
+import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';
+
+const ESH_EMAIL = 'eshgupta1217@gmail.com';
+const ESH_ACCOUNT_ID = 1;
+const WORKSPACE_NAME = "Esh's Workspace";
+
+OnyxUpdateManager();
+describe('actions/Policy', () => {
+ beforeAll(() => {
+ Onyx.init({
+ keys: ONYXKEYS,
+ });
+ });
+
+ beforeEach(() => {
+ global.fetch = TestHelper.getGlobalFetchMock();
+ return Onyx.clear().then(waitForBatchedUpdates);
+ });
+
+ describe('createWorkspace', () => {
+ it('creates a new workspace', async () => {
+ fetch.pause();
+ Onyx.set(ONYXKEYS.SESSION, {email: ESH_EMAIL, accountID: ESH_ACCOUNT_ID});
+ await waitForBatchedUpdates();
+
+ let adminReportID;
+ let announceReportID;
+ let expenseReportID;
+ const policyID = Policy.generatePolicyID();
+
+ Policy.createWorkspace(ESH_EMAIL, true, WORKSPACE_NAME, policyID);
+ await waitForBatchedUpdates();
+
+ let policy = await new Promise((resolve) => {
+ const connectionID = Onyx.connect({
+ key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
+ waitForCollectionCallback: true,
+ callback: (workspace) => {
+ Onyx.disconnect(connectionID);
+ resolve(workspace);
+ },
+ });
+ });
+
+ // check if policy was created with correct values
+ expect(policy.id).toBe(policyID);
+ expect(policy.name).toBe(WORKSPACE_NAME);
+ expect(policy.type).toBe(CONST.POLICY.TYPE.FREE);
+ expect(policy.role).toBe(CONST.POLICY.ROLE.ADMIN);
+ expect(policy.owner).toBe(ESH_EMAIL);
+ expect(policy.isPolicyExpenseChatEnabled).toBe(true);
+ expect(policy.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);
+
+ const policyMembers = await new Promise((resolve) => {
+ const connectionID = Onyx.connect({
+ key: `${ONYXKEYS.COLLECTION.POLICY_MEMBERS}${policyID}`,
+ waitForCollectionCallback: true,
+ callback: (members) => {
+ Onyx.disconnect(connectionID);
+ resolve(members);
+ },
+ });
+ });
+
+ // check if the user was added as an admin to the policy
+ expect(policyMembers[ESH_ACCOUNT_ID].role).toBe(CONST.POLICY.ROLE.ADMIN);
+
+ let allReports = await new Promise((resolve) => {
+ const connectionID = Onyx.connect({
+ key: ONYXKEYS.COLLECTION.REPORT,
+ waitForCollectionCallback: true,
+ callback: (reports) => {
+ Onyx.disconnect(connectionID);
+ resolve(reports);
+ },
+ });
+ });
+
+ // Three reports should be created: #announce, #admins and expense report
+ const workspaceReports = _.filter(allReports, (report) => report.policyID === policyID);
+ expect(_.size(workspaceReports)).toBe(3);
+ _.forEach(workspaceReports, (report) => {
+ expect(report.pendingFields.addWorkspaceRoom).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);
+ expect(report.participantAccountIDs).toEqual([ESH_ACCOUNT_ID]);
+ switch (report.chatType) {
+ case CONST.REPORT.CHAT_TYPE.POLICY_ADMINS: {
+ adminReportID = report.reportID;
+ break;
+ }
+ case CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE: {
+ announceReportID = report.reportID;
+ break;
+ }
+ case CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT: {
+ expenseReportID = report.reportID;
+ break;
+ }
+ default:
+ break;
+ }
+ });
+
+ let reportActions = await new Promise((resolve) => {
+ const connectionID = Onyx.connect({
+ key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
+ waitForCollectionCallback: true,
+ callback: (actions) => {
+ Onyx.disconnect(connectionID);
+ resolve(actions);
+ },
+ });
+ });
+
+ // Each of the three reports should have a a `CREATED` action.
+ let adminReportActions = _.values(reportActions[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${adminReportID}`]);
+ let announceReportActions = _.values(reportActions[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${announceReportID}`]);
+ let expenseReportActions = _.values(reportActions[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReportID}`]);
+ let workspaceReportActions = _.concat(adminReportActions, announceReportActions, expenseReportActions);
+ _.forEach([adminReportActions, announceReportActions, expenseReportActions], (actions) => {
+ expect(_.size(actions)).toBe(1);
+ });
+ _.forEach([...adminReportActions, ...announceReportActions, ...expenseReportActions], (reportAction) => {
+ expect(reportAction.actionName).toBe(CONST.REPORT.ACTIONS.TYPE.CREATED);
+ expect(reportAction.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);
+ expect(reportAction.actorAccountID).toBe(ESH_ACCOUNT_ID);
+ });
+
+ // Check for success data
+ fetch.resume();
+ await waitForBatchedUpdates();
+
+ policy = await new Promise((resolve) => {
+ const connectionID = Onyx.connect({
+ key: ONYXKEYS.COLLECTION.POLICY,
+ waitForCollectionCallback: true,
+ callback: (workspace) => {
+ Onyx.disconnect(connectionID);
+ resolve(workspace);
+ },
+ });
+ });
+
+ // Check if the policy pending action was cleared
+ expect(policy.pendingAction).toBeFalsy();
+
+ allReports = await new Promise((resolve) => {
+ const connectionID = Onyx.connect({
+ key: ONYXKEYS.COLLECTION.REPORT,
+ waitForCollectionCallback: true,
+ callback: (reports) => {
+ Onyx.disconnect(connectionID);
+ resolve(reports);
+ },
+ });
+ });
+
+ // Check if the report pending action and fields were cleared
+ _.forEach(allReports, (report) => {
+ expect(report.pendingAction).toBeFalsy();
+ expect(report.pendingFields.addWorkspaceRoom).toBeFalsy();
+ });
+
+ reportActions = await new Promise((resolve) => {
+ const connectionID = Onyx.connect({
+ key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
+ waitForCollectionCallback: true,
+ callback: (actions) => {
+ Onyx.disconnect(connectionID);
+ resolve(actions);
+ },
+ });
+ });
+
+ // Check if the report action pending action was cleared
+ adminReportActions = _.values(reportActions[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${adminReportID}`]);
+ announceReportActions = _.values(reportActions[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${announceReportID}`]);
+ expenseReportActions = _.values(reportActions[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReportID}`]);
+ workspaceReportActions = _.concat(adminReportActions, announceReportActions, expenseReportActions);
+ _.forEach(workspaceReportActions, (reportAction) => {
+ expect(reportAction.pendingAction).toBeFalsy();
+ });
+ });
+ });
+});
diff --git a/tests/perf-test/ReportScreen.perf-test.js b/tests/perf-test/ReportScreen.perf-test.js
index 88f3fe99b347..46716c243b1a 100644
--- a/tests/perf-test/ReportScreen.perf-test.js
+++ b/tests/perf-test/ReportScreen.perf-test.js
@@ -208,7 +208,7 @@ test.skip('[ReportScreen] should render ReportScreen with composer interactions'
[`${ONYXKEYS.COLLECTION.REPORT}${mockRoute.params.reportID}`]: report,
[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${mockRoute.params.reportID}`]: reportActions,
[ONYXKEYS.PERSONAL_DETAILS_LIST]: LHNTestUtils.fakePersonalDetails,
- [ONYXKEYS.BETAS]: [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS],
+ [ONYXKEYS.BETAS]: [CONST.BETAS.DEFAULT_ROOMS],
[`${ONYXKEYS.COLLECTION.POLICY}${policy.policyID}`]: policy,
[`${ONYXKEYS.COLLECTION.REPORT_METADATA}${mockRoute.params.reportID}`]: {
isLoadingReportActions: false,
@@ -273,7 +273,7 @@ test.skip('[ReportScreen] should press of the report item', () => {
[`${ONYXKEYS.COLLECTION.REPORT}${mockRoute.params.reportID}`]: report,
[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${mockRoute.params.reportID}`]: reportActions,
[ONYXKEYS.PERSONAL_DETAILS_LIST]: LHNTestUtils.fakePersonalDetails,
- [ONYXKEYS.BETAS]: [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS],
+ [ONYXKEYS.BETAS]: [CONST.BETAS.DEFAULT_ROOMS],
[`${ONYXKEYS.COLLECTION.POLICY}${policy.policyID}`]: policy,
[`${ONYXKEYS.COLLECTION.REPORT_METADATA}${mockRoute.params.reportID}`]: {
isLoadingReportActions: false,
diff --git a/tests/perf-test/SidebarLinks.perf-test.js b/tests/perf-test/SidebarLinks.perf-test.js
index c6e6c024c597..1f529b08e6b3 100644
--- a/tests/perf-test/SidebarLinks.perf-test.js
+++ b/tests/perf-test/SidebarLinks.perf-test.js
@@ -67,7 +67,7 @@ test('[SidebarLinks] should render Sidebar with 500 reports stored', () => {
Onyx.multiSet({
[ONYXKEYS.NVP_PRIORITY_MODE]: CONST.PRIORITY_MODE.DEFAULT,
[ONYXKEYS.PERSONAL_DETAILS_LIST]: LHNTestUtils.fakePersonalDetails,
- [ONYXKEYS.BETAS]: [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS],
+ [ONYXKEYS.BETAS]: [CONST.BETAS.DEFAULT_ROOMS],
[ONYXKEYS.NVP_PRIORITY_MODE]: CONST.PRIORITY_MODE.GSD,
[ONYXKEYS.IS_LOADING_REPORT_DATA]: false,
...mockedResponseMap,
@@ -111,7 +111,7 @@ test('[SidebarLinks] should scroll and click some of the items', () => {
Onyx.multiSet({
[ONYXKEYS.NVP_PRIORITY_MODE]: CONST.PRIORITY_MODE.DEFAULT,
[ONYXKEYS.PERSONAL_DETAILS_LIST]: LHNTestUtils.fakePersonalDetails,
- [ONYXKEYS.BETAS]: [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS],
+ [ONYXKEYS.BETAS]: [CONST.BETAS.DEFAULT_ROOMS],
[ONYXKEYS.NVP_PRIORITY_MODE]: CONST.PRIORITY_MODE.GSD,
[ONYXKEYS.IS_LOADING_REPORT_DATA]: false,
...mockedResponseMap,
diff --git a/tests/perf-test/SidebarUtils.perf-test.ts b/tests/perf-test/SidebarUtils.perf-test.ts
index 5606863f42e2..6722cbf493a5 100644
--- a/tests/perf-test/SidebarUtils.perf-test.ts
+++ b/tests/perf-test/SidebarUtils.perf-test.ts
@@ -64,7 +64,7 @@ test('[SidebarUtils] getOptionData on 5k reports', async () => {
test('[SidebarUtils] getOrderedReportIDs on 5k reports', async () => {
const currentReportId = '1';
const allReports = getMockedReports();
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
const policies = createCollection(
(item) => `${ONYXKEYS.COLLECTION.POLICY}${item.id}`,
diff --git a/tests/unit/PhoneNumberTest.js b/tests/unit/PhoneNumberTest.js
new file mode 100644
index 000000000000..f720dc6a88e1
--- /dev/null
+++ b/tests/unit/PhoneNumberTest.js
@@ -0,0 +1,43 @@
+import {parsePhoneNumber} from '@libs/PhoneNumber';
+
+describe('PhoneNumber', () => {
+ describe('parsePhoneNumber', () => {
+ it('Should return valid phone number', () => {
+ const validNumbers = [
+ '+1 (234) 567-8901',
+ '+12345678901',
+ '+54 11 8765-4321',
+ '+49 30 123456',
+ '+44 20 8759 9036',
+ '+34 606 49 95 99',
+ ' + 1 2 3 4 5 6 7 8 9 0 1',
+ '+ 4 4 2 0 8 7 5 9 9 0 3 6',
+ '+1 ( 2 3 4 ) 5 6 7 - 8 9 0 1',
+ ];
+
+ validNumbers.forEach((givenPhone) => {
+ const parsedPhone = parsePhoneNumber(givenPhone);
+ expect(parsedPhone.valid).toBe(true);
+ expect(parsedPhone.possible).toBe(true);
+ });
+ });
+ it('Should return invalid phone number if US number has extra 1 after country code', () => {
+ const validNumbers = ['+1 1 (234) 567-8901', '+112345678901', '+115550123355', '+ 1 1 5 5 5 0 1 2 3 3 5 5'];
+
+ validNumbers.forEach((givenPhone) => {
+ const parsedPhone = parsePhoneNumber(givenPhone);
+ expect(parsedPhone.valid).toBe(false);
+ expect(parsedPhone.possible).toBe(false);
+ });
+ });
+ it('Should return invalid phone number', () => {
+ const invalidNumbers = ['+165025300001', 'John Doe', '123', 'email@domain.com'];
+
+ invalidNumbers.forEach((givenPhone) => {
+ const parsedPhone = parsePhoneNumber(givenPhone);
+ expect(parsedPhone.valid).toBe(false);
+ expect(parsedPhone.possible).toBe(false);
+ });
+ });
+ });
+});
diff --git a/tests/unit/ReportActionsUtilsTest.js b/tests/unit/ReportActionsUtilsTest.js
index 545d442e4799..b8b6eb5e7673 100644
--- a/tests/unit/ReportActionsUtilsTest.js
+++ b/tests/unit/ReportActionsUtilsTest.js
@@ -288,7 +288,7 @@ describe('ReportActionsUtils', () => {
expect(result).toStrictEqual(input);
});
- it('should filter out deleted and delete-pending comments', () => {
+ it('should filter out deleted, non-pending comments', () => {
const input = [
{
created: '2022-11-13 22:27:01.825',
@@ -312,7 +312,6 @@ describe('ReportActionsUtils', () => {
];
const result = ReportActionsUtils.getSortedReportActionsForDisplay(input);
input.pop();
- input.pop();
expect(result).toStrictEqual(input);
});
});
diff --git a/tests/unit/SidebarFilterTest.js b/tests/unit/SidebarFilterTest.js
index dd2985ea34a8..088e5a1af4d0 100644
--- a/tests/unit/SidebarFilterTest.js
+++ b/tests/unit/SidebarFilterTest.js
@@ -154,20 +154,6 @@ describe('Sidebar', () => {
const optionRows = screen.queryAllByAccessibilityHint(hintText);
expect(optionRows).toHaveLength(1);
})
-
- // When the user is added to the policy rooms beta and the sidebar re-renders
- .then(() =>
- Onyx.multiSet({
- [ONYXKEYS.BETAS]: [CONST.BETAS.POLICY_ROOMS],
- }),
- )
-
- // Then the report is still rendered in the LHN
- .then(() => {
- const hintText = Localize.translateLocal('accessibilityHints.navigatesToChat');
- const optionRows = screen.queryAllByAccessibilityHint(hintText);
- expect(optionRows).toHaveLength(1);
- })
);
});
@@ -286,7 +272,7 @@ describe('Sidebar', () => {
};
// Given the user is in all betas
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
// Given there are 6 boolean variables tested in the filtering logic:
// 1. isArchived
@@ -488,7 +474,7 @@ describe('Sidebar', () => {
};
LHNTestUtils.getDefaultRenderedSidebarLinks();
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
return (
waitForBatchedUpdates()
@@ -551,7 +537,7 @@ describe('Sidebar', () => {
};
LHNTestUtils.getDefaultRenderedSidebarLinks();
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
return (
waitForBatchedUpdates()
@@ -609,7 +595,7 @@ describe('Sidebar', () => {
};
// Given the user is in all betas
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
// Given there are 6 boolean variables tested in the filtering logic:
// 1. isArchived
@@ -700,7 +686,7 @@ describe('Sidebar', () => {
};
// Given the user is in all betas
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
return (
waitForBatchedUpdates()
@@ -751,7 +737,7 @@ describe('Sidebar', () => {
};
// Given the user is in all betas
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
return (
waitForBatchedUpdates()
@@ -800,7 +786,7 @@ describe('Sidebar', () => {
};
// Given the user is in all betas
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
return (
waitForBatchedUpdates()
@@ -845,7 +831,7 @@ describe('Sidebar', () => {
};
// Given the user is in all betas
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
return (
waitForBatchedUpdates()
diff --git a/tests/unit/SidebarOrderTest.js b/tests/unit/SidebarOrderTest.js
index 44d6dd57de91..4d49cb3ad516 100644
--- a/tests/unit/SidebarOrderTest.js
+++ b/tests/unit/SidebarOrderTest.js
@@ -752,7 +752,7 @@ describe('Sidebar', () => {
Report.addComment(report3.reportID, 'Hi, this is a comment');
// Given the user is in all betas
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
LHNTestUtils.getDefaultRenderedSidebarLinks('0');
return (
waitForBatchedUpdates()
@@ -844,7 +844,7 @@ describe('Sidebar', () => {
const report3 = LHNTestUtils.getFakeReport([5, 6], 1, true);
// Given the user is in all betas
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
LHNTestUtils.getDefaultRenderedSidebarLinks('0');
return (
waitForBatchedUpdates()
diff --git a/tests/unit/SidebarTest.js b/tests/unit/SidebarTest.js
index 106b2c3b69a9..56009ee382d5 100644
--- a/tests/unit/SidebarTest.js
+++ b/tests/unit/SidebarTest.js
@@ -56,7 +56,7 @@ describe('Sidebar', () => {
};
// Given the user is in all betas
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
LHNTestUtils.getDefaultRenderedSidebarLinks('0');
return (
waitForBatchedUpdates()
@@ -99,7 +99,7 @@ describe('Sidebar', () => {
};
// Given the user is in all betas
- const betas = [CONST.BETAS.DEFAULT_ROOMS, CONST.BETAS.POLICY_ROOMS];
+ const betas = [CONST.BETAS.DEFAULT_ROOMS];
LHNTestUtils.getDefaultRenderedSidebarLinks('0');
return (
waitForBatchedUpdates()
diff --git a/tests/unit/enhanceParametersTest.js b/tests/unit/enhanceParametersTest.js
index 513206b42614..6829732f1633 100644
--- a/tests/unit/enhanceParametersTest.js
+++ b/tests/unit/enhanceParametersTest.js
@@ -18,6 +18,7 @@ test('Enhance parameters adds correct parameters for Log command with no authTok
testParameter: 'test',
api_setCookie: false,
email,
+ isFromDevEnv: true,
platform: 'ios',
referer: CONFIG.EXPENSIFY.EXPENSIFY_CASH_REFERER,
});
@@ -36,6 +37,7 @@ test('Enhance parameters adds correct parameters for a command that requires aut
testParameter: 'test',
api_setCookie: false,
email,
+ isFromDevEnv: true,
platform: 'ios',
authToken,
referer: CONFIG.EXPENSIFY.EXPENSIFY_CASH_REFERER,