diff --git a/.detoxrc.js b/.detoxrc.js new file mode 100644 index 0000000..808d772 --- /dev/null +++ b/.detoxrc.js @@ -0,0 +1,92 @@ +/** @type {Detox.DetoxConfig} */ +const dotenv = require('dotenv'); +dotenv.config(); + +module.exports = { + testRunner: { + args: { + '$0': 'jest', + config: 'e2e/jest.config.ts' + }, + jest: { + setupTimeout: 120000 + } + }, + apps: { + 'ios.release': { + type: 'ios.app', + binaryPath: process.env.IOS_BINARY_PATH, + build: 'xcodebuild -workspace ios/inruptwalletfrontend.xcworkspace -scheme inruptwalletfrontend -configuration Release -sdk iphonesimulator -derivedDataPath ios/build' + }, + 'android.release': { + type: 'android.apk', + binaryPath: 'android/app/build/outputs/apk/release/app-release.apk', + testBinaryPath: 'android/app/build/outputs/apk/androidTest/release/app-release-androidTest.apk', + build: 'cd android && ./gradlew assembleRelease assembleAndroidTest -DtestBuildType=release && cd ..' + }, + 'android.debug': { + type: 'android.apk', + binaryPath: 'android/app/build/outputs/apk/debug/app-debug.apk', + testBinaryPath: 'android/app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk', + build: 'cd android && ./gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug && cd ..' + } + }, + devices: { + simulator: { + type: 'ios.simulator', + device: { + type: process.env.TEST_IOS_SIM + } + }, + attached: { + type: 'android.attached', + device: { + adbName: '.*' + } + }, + emulator: { + type: 'android.emulator', + device: { + avdName: process.env.TEST_ANDROID_EMU + }, + } + }, + configurations: { + 'ios.sim.release': { + device: 'simulator', + app: 'ios.release' + }, + 'android.att.release': { + device: 'attached', + app: 'android.release' + }, + 'android.emu.release': { + device: 'emulator', + app: 'android.release' + }, + 'android.emu.debug': { + device: 'emulator', + app: 'android.debug' + } + }, + custom: { + defaultTestTimeout: 15000 + }, + artifacts: { + rootDir: "./screenshots/", + plugins: { + log: {"enabled": true}, + uiHierarchy: {"enabled": true}, + screenshot: { + keepOnlyFailedTestsArtifacts: false, + takeWhen: { + "testStart": true, + "testDone": true + } + }, + video: { + enabled: true + } + } + } +}; diff --git a/.env.sample b/.env.sample new file mode 100644 index 0000000..132aee8 --- /dev/null +++ b/.env.sample @@ -0,0 +1,13 @@ +EXPO_PUBLIC_LOGIN_URL=https://datawallet.dev.inrupt.com/oauth2/authorization/wallet-app +EXPO_PUBLIC_WALLET_API=https://datawallet.dev.inrupt.com +TEST_ACCOUNT_USERNAME= +TEST_ACCOUNT_PASSWORD= +IOS_BINARY_PATH= +TEST_IOS_SIM= +# The following should align with a device emulator in Android Studio, +# e.g. 'Android_34' or 'Pixel_3a_API_34' +TEST_ANDROID_EMU= +SIGNING_CONFIG_PATH=/absolute/path/to/android-config/signing-config.gradle +KEYSTORE_PATH=/absolute/path/to/wallet.keystore +KEYSTORE_PASSWORD= +EAS_PROJECT_ID="project-id-from-eas" diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..99119ea --- /dev/null +++ b/.eslintignore @@ -0,0 +1,2 @@ +.eslintrc.js +metro.config.js \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..4724071 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,60 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +module.exports = { + extends: ["expo", "@inrupt/eslint-config-lib"], + parserOptions: { + ecmaFeatures: { + jsx: true, + }, + project: "./tsconfig.eslint.json", + }, + ignorePatterns: [ + "expo-env.d.ts", // Exclude expo-env.d.ts from ESLint checks + ], + rules: { + "no-undef": "off", // TypeScript handles this + "no-use-before-define": "off", // Disable the base rule + "@typescript-eslint/no-use-before-define": [ + "error", + { functions: false, variables: false, classes: true, typedefs: true }, + ], + "no-shadow": "off", // Disable the base rule + "@typescript-eslint/no-shadow": ["error"], + "@typescript-eslint/no-unused-vars": [ + "error", + { + vars: "all", + varsIgnorePattern: "^_", + args: "after-used", + ignoreRestSiblings: true, + caughtErrors: "none", + argsIgnorePattern: "^_", + }, + ], + "@typescript-eslint/no-var-requires": [ + "error", { + // These exceptions cover imports from CJS configuration modules (e.g. app.config.js, plugins/*.js) + allow: ["plugins", "fs"] + } + ], + "import/prefer-default-export": "off", + "no-console": "off", + + // Ensure all code has a license header: + "header/header": ["warn", require.resolve("./header-license.js")], + }, +}; diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..04bf232 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +node_modules/ +.expo/ +dist/ +/build/ +ios/ +android/ +artifacts/ +npm-debug.* +*.jks +*.p8 +*.p12 +*.key +*.mobileprovision +*.orig.* +web-build/ +.idea +.vscode/ +ios/certs/* +credentials.json + +# macOS +.DS_Store +.env.local + +# @generated expo-cli sync-2b81b286409207a5da26e14c78851eb30d8ccbdb +# The following patterns were generated by expo-cli + +expo-env.d.ts +# @end expo-cli + +.env + +*.keystore +*.apk + +# Folder where the UI tests get stored. +screenshots/ diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..2edeafb --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +20 \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..fd6a940 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,23 @@ +{ + "arrowParens": "always", + "bracketSpacing": true, + "endOfLine": "lf", + "htmlWhitespaceSensitivity": "css", + "insertPragma": false, + "singleAttributePerLine": false, + "bracketSameLine": false, + "jsxBracketSameLine": false, + "jsxSingleQuote": false, + "printWidth": 80, + "proseWrap": "preserve", + "quoteProps": "as-needed", + "requirePragma": false, + "semi": true, + "singleQuote": false, + "tabWidth": 2, + "trailingComma": "es5", + "useTabs": false, + "embeddedLanguageFormatting": "auto", + "vueIndentScriptAndStyle": false, + "parser": "typescript" + } \ No newline at end of file diff --git a/CODE-OF-CONDUCT.md b/CODE-OF-CONDUCT.md new file mode 100644 index 0000000..adccdcc --- /dev/null +++ b/CODE-OF-CONDUCT.md @@ -0,0 +1,132 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our project and community +a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, geographic location, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or advances of + any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, + without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Project members are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Project members have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all project spaces, and also applies when +an individual is officially representing the project and the community in public spaces. +Examples of representing our project and our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the project members responsible for enforcement at +[engineering@inrupt.com](mailto:engineering@inrupt.com). +All complaints will be reviewed and investigated promptly and fairly. + +All project members are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Project members will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from project members, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in project and community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the project and the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including but not limited to sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the project and the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][mozilla coc]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][faq]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[mozilla coc]: https://github.com/mozilla/diversity +[faq]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0b7b05c --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Inrupt, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ad7ce45 --- /dev/null +++ b/README.md @@ -0,0 +1,290 @@ +# Inrupt Data Wallet + +This project produces a mobile React Native application for use with the Inrupt Data Wallet service. +This README provides information on: + +* [Setup and configuration](#setup-and-configuration) + * [Prerequisites](#prerequisites) + * [Install dependencies](#install-dependencies) + * [Configure build environment](#configure-build-environment) + * [Create keystore for Android](#create-keystore-for-android) + * [Make the keystore available to CI](#make-the-keystore-available-to-ci) +* [Running the application locally](#running-the-application-locally) + * [On a device with Expo Go](#on-a-device-with-expo-go) + * [On an Android emulator](#on-an-android-emulator) + * [On an iOS simulator](#on-an-ios-simulator) +* [Build the app on EAS](#build-the-app-on-eas) +* [Testing with Detox](#testing-with-detox) + * [On Android](#on-android) + * [On iOS](#on-ios) +* [UI overview](#ui-overview) + * [Home](#home) + * [Profile](#profile) + * [Requests](#requests) + * [Access](#access) +* [Issues & Help](#issues--help) + * [Bugs and Feature Requests](#bugs-and-feature-requests) + * [Documentation](#documentation) + * [Changelog](#changelog) + * [License](#license) + +## Setup and configuration + +### Prerequisites + +In order to log into the Wallet, and for it to be able to persist data, you will need a +[Podspaces Account](https://start.inrupt.com/profile?utm_campaign=Data%20Wallet%20PodSpaces&utm_source=github). +Ensure that you have the following dependencies installed and configured: + +##### On the mobile device + +- [Expo Go](https://expo.dev/go) - app to be installed on a real device (iOS and Android supported) + +##### On the dev machine (iOS) + +If you are only running the app in Expo Go: +- [NodeJS and NPM](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) + +If you are building the app locally, you'll also need: +- [Xcode](https://apps.apple.com/us/app/xcode/id497799835) +- [iOS simulators](https://developer.apple.com/documentation/safari-developer-tools/installing-xcode-and-simulators) + +#### On the dev machine (Android) + +If you are only running the app in Expo Go: +- [NodeJS and NPM](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) + +If you are building the app locally, you'll also need: +- A Java JDK +- [Android emulators](https://developer.android.com/studio/install) + +### Install dependencies + +First, install all the project dependencies. + +```bash +npm ci +``` + +### Configure build environment + +Copy the `.env.sample` file to `.env` and fill in any relevant values. + +If you are testing manually, the minimal configuration is the URLs for the wallet's backend service. +``` +EXPO_PUBLIC_LOGIN_URL= +EXPO_PUBLIC_WALLET_API= +``` + +Automated testing also requires access credentials for the Data Wallet: +```bash +TEST_ACCOUNT_USERNAME= +TEST_ACCOUNT_PASSWORD= +``` + +For testing with iOS simulators, you will need: +```bash +IOS_BINARY_PATH= +TEST_IOS_SIM= +``` + +For testing with Android emulators, you will need: +```bash +ANDROID_BINARY_PATH= +ANDROID_TEST_BINARY_PATH= +TEST_ANDROID_EMU= +``` +Ensure that the ``TEST_ANDROID_EMU`` configuration aligns with a device emulator in Android Studio. +For example: ``TEST_ANDROID_EMU=Android_34``. If the emulated device is called "Test Emulator 33", +the EMU name will be ``Test_Emulator_33``. + +#### Create keystore for Android + +The Android app will need to be signed for it to be installed. See: https://reactnative.dev/docs/signed-apk-android +for more information on this. + +__WARNING:__ The following is only to be used for development. In production the keystore should +be generated and configured in a more secure manner. + +To generate a keystore with a key and cert run the following from the root of the project (this requires a Java JDK +installation): + +```bash +keytool -genkeypair -v -storetype PKCS12 \ + -keystore android/app/wallet.keystore \ + -alias wallet -keyalg RSA -keysize 2048 -validity 100 \ + -noprompt -dname "CN=wallet.example.com" +``` + +Add the following to: `.env` and update the placeholders. +```text +KEYSTORE_PATH=/inrupt-data-wallet/android/app/wallet.keystore +KEYSTORE_PASSWORD= +``` + +## Running the application locally + +Start the application: + +```bash +npx expo start +``` + +In the output, you'll find options to open the app in a +- [Expo Go](https://expo.dev/go), a limited sandbox for trying out app development with Expo. +- [Development build](https://docs.expo.dev/develop/development-builds/introduction/) +- [Android emulator](https://docs.expo.dev/workflow/android-studio-emulator/) +- [iOS simulator](https://docs.expo.dev/workflow/ios-simulator/) + +### On a device with Expo Go + +After expo has started, make sure it targets the Expo Go environment (as opposed to "development build"). +This will display a QR code which you will need to scan with your device. + +The Wallet application will then build and install into your device for you to test & debug. + +### On an Android emulator + +For Android, ensure that a virtual device has been added to the Android emulator by opening the new Device Manager with +the following actions: +* Go to the Android Studio Welcome screen +* Select **More Actions > Virtual Device Manager.** + +```bash +npm run android +``` +Note: When running on the android emulator, there is a special loopback IP, 10.0.2.2, which points to the host machine 127.0.0.1. You can use it if the emulator complains about cleartext communication to the local network IP of the host. + +### On an iOS simulator + +To build the iOS wallet app in an iOS simulator, run the following command: + +```bash +npm run ios +``` + +This will install the necessary CocoaPods and compile the application. Upon completion, the iOS simulator should be open and the wallet app running. + +## Build the app on the Expo Application Service (EAS) + +**Prerequisite**: All the following instructions are only applicable if you have an EAS account. By default, +the project is configured to be built on an Inrupt EAS project. In order to build a custom version in your +own EAS account, you'll need to create a new EAS project, and make sure that EAS project and the data (e.g. +`name`, `slug`, `project-id`...) in your copy of `app.config.ts` are aligned. + +Both the Android and the iOS versions of the app can be built using EAS. To do so, follow the instructions +from the [EAS documentation](https://docs.expo.dev/build/setup/) to setup your environment. + +By default, the EAS CLI will trigger a build on the EAS infrastructure. It is also possible to +[run a build locally](https://docs.expo.dev/build-reference/local-builds/), which results in the built binary +being available on the developer machine. This requires all the environment setup for being able to build +the app locally, similar to `npx expo run:`. + +The project ID is not hard-coded in the `app.config.ts`, but provided as an environment variable instead. +In order to trigger an EAS build, please add the appropriate project ID in your environment variables, e.g. + +``` +EAS_PROJECT_ID="..." eas build --platform android --local --profile preview +``` + +## Testing with Detox + +### On Android + +Run the following command to build the Android app. This process may take up to 30 minutes to complete. + +```bash +npx detox build --configuration=android.emu.release +``` + +For local development (a back-end server running on localhost or at an alternative location), use +the `android.emu.debug` configuration. If running the debug configuration, make sure to run the +development server (`npx expo start`). + +Once built, run the detox tests for the relevant configuration: + +```bash +npx detox test --configuration=android.emu.release +``` + +After completion, the binary apps will be located in: +```bash +./android/app/build/outputs +``` + +You can share the .apk files with others who need to run the Detox tests without building the Android app locally. + +### On iOS + +If you want to generate the iOS binary, run the following commands. Note that this process may take around 30 minutes to complete. + +```bash +xcodebuild -workspace ios/inruptwalletfrontend.xcworkspace -scheme inruptwalletfrontend -configuration Release -sdk iphonesimulator -derivedDataPath ios/build +``` + +After completion, the iOS binary should be located at: + +```bash +inrupt-data-wallet/ios/build/Build/Products/inruptwalletfrontend.app +``` + +You can share the .app file with others who need to run the Detox tests without building the iOS app locally. + +Execute the command below to start Detox test on iOS. +```bash +npx detox test --configuration=ios.sim.release +``` + +## UI overview + +Upon execution, the application prompts the user to log in. After successful authentication, the wallet app presents various views, located in the `app/(tabs)` directory: +- [Home](#home) +- [Profile](#profile) +- [Requests](#requests) +- [Access](#access) + +### Home +This page allows users to see all their assets within the wallet. + +For each item, users can share it via QR code, download it, or delete it. +Additionally, users can add new items: they can upload an existing photo, take a new one using the camera, upload an existing file, or use the QR scanner to request access to one. + +### Profile + +This page displays the profile information of the wallet owner. + +Here, users can see their webId and profile picture, if it is available. A QR code is also provided which can be used to share the user's wallet. Additionally, users can log out from this page. + +### Requests + +This page displays the access requests for items within the wallet or for the wallet itself. + +From here, the user can view all the requests along with their details (requestor, access mode, resource, and expiry date) and either confirm or deny access. If the user confirms the request, the requestor will be granted the specified access mode to the resource. + +### Access + +This page shows what access has been granted to other agents. + +For each authorized agent, there is a list of the wallet resources to which they have access. Users also have the option to revoke access to each resource from this page. + +## Issues & Help + +### Bugs and Feature Requests + +- For public feedback, bug reports, and feature requests please file an issue + via [Github](https://github.com/inrupt/inrupt-data-wallet/issues/). +- For non-public feedback or support inquiries please use the + [Inrupt Service Desk](https://inrupt.atlassian.net/servicedesk). + +### Documentation + +- [Inrupt Data Wallet](https://docs.inrupt.com/data-wallet/) +- [Homepage](https://docs.inrupt.com/) + +### Changelog + +See [the release notes](https://github.com/inrupt/inrupt-data-wallet/releases). + +### License + +Apache 2.0 © [Inrupt](https://inrupt.com) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..6e4bc40 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,15 @@ +# Security policy + +Inrupt takes the security of our software products and services seriously. This includes all source code repositories managed through our [GitHub organization](https://github.com/inrupt). + +If you believe you have found a security vulnerability in any Inrupt-owned repository please report it to us as described below. + +## Reporting a vulnerability + +Please do not report security vulnerabilities through public GitHub issues. + +Instead, if you discover a vulnerability in our code, or experience a bug related to security, please report it following the instructions provided on [Inrupt’s security page](https://inrupt.com/security/). + +## Preferred Languages + +We prefer all communications to be in English. diff --git a/android-config/extend-build.gradle b/android-config/extend-build.gradle new file mode 100644 index 0000000..4bb53eb --- /dev/null +++ b/android-config/extend-build.gradle @@ -0,0 +1,4 @@ +if(project.hasProperty("inrupt.wallet.frontend.signing") + && new File(project.property("inrupt.wallet.frontend.signing")).exists()) { + apply from: project.property("inrupt.wallet.frontend.signing"); +} diff --git a/android-config/signing-config.gradle b/android-config/signing-config.gradle new file mode 100644 index 0000000..177b7fc --- /dev/null +++ b/android-config/signing-config.gradle @@ -0,0 +1,18 @@ +android { + signingConfigs { + release { + if (project.hasProperty('inrupt.wallet.frontend.keystore.file')) { + storeFile file(project.property('inrupt.wallet.frontend.keystore.file')) + storePassword project.property('inrupt.wallet.frontend.keystore.password') + keyAlias project.property('inrupt.wallet.frontend.key.alias') + keyPassword project.property('inrupt.wallet.frontend.key.password') + } + } + } + + buildTypes { + release { + signingConfig signingConfigs.release + } + } +} diff --git a/api/accessGrant.ts b/api/accessGrant.ts new file mode 100644 index 0000000..aa56576 --- /dev/null +++ b/api/accessGrant.ts @@ -0,0 +1,63 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import type { AccessGrant, AccessGrantGroup } from "@/types/accessGrant"; +import { makeApiRequest } from "./apiRequest"; + +export const getAccessGrants = async (): Promise => { + const accessGrants = await makeApiRequest("accessgrants"); + const groups = accessGrants.reduce( + (result, grant) => { + if (result[grant.webId]) { + result[grant.webId].items.push(grant); + } else { + // eslint-disable-next-line no-param-reassign + result[grant.webId] = { + webId: grant.webId, + logo: grant.logo, + ownerName: grant.ownerName, + items: [grant], + }; + } + return result; + }, + {} as Record + ); + return Object.values(groups); +}; + +export const revokeAccessGrant = async (params: { + requestId: string; +}): Promise => { + const { requestId } = params; + + const url = `accessgrants/${requestId}/revoke`; + await makeApiRequest(url, "PUT"); +}; + +export const revokeAccessGrantList = async (params: { + requestId: string[]; +}): Promise => { + const { requestId } = params; + + const url = `accessgrants/revoke`; + await makeApiRequest( + url, + "PUT", + JSON.stringify({ + uuids: requestId, + }) + ); +}; diff --git a/api/accessPrompt.ts b/api/accessPrompt.ts new file mode 100644 index 0000000..5bbafa9 --- /dev/null +++ b/api/accessPrompt.ts @@ -0,0 +1,39 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import type { AccessRequest } from "@/types/accessRequest"; +import type { AccessPromptResource } from "@/types/accessPrompt"; +import { makeApiRequest, objectToParams } from "./apiRequest"; + +export const getAccessPromptResource = async (accessPrompt: { + webId: string; + type: string; +}): Promise => { + return makeApiRequest( + `accessprompt/resource?${objectToParams(accessPrompt)}`, + "GET" + ); +}; + +export const requestAccessPrompt = async (params: { + resource: string; + client: string; +}): Promise => { + await makeApiRequest( + "accessprompt", + "POST", + JSON.stringify(params) + ); +}; diff --git a/api/accessRequest.ts b/api/accessRequest.ts new file mode 100644 index 0000000..254f674 --- /dev/null +++ b/api/accessRequest.ts @@ -0,0 +1,31 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import type { AccessRequest } from "@/types/accessRequest"; +import { makeApiRequest } from "./apiRequest"; + +export const getAccessRequests = async (): Promise => { + return makeApiRequest("inbox"); +}; + +export const updateAccessRequests = async (params: { + requestId: string; + action: "CONFIRM" | "DENY"; +}): Promise => { + const { action, requestId } = params; + + const url = `inbox/${requestId}/${action === "CONFIRM" ? "grantAccess" : "denyAccess"}`; + await makeApiRequest(url, "PUT"); +}; diff --git a/api/apiRequest.ts b/api/apiRequest.ts new file mode 100644 index 0000000..8667ab7 --- /dev/null +++ b/api/apiRequest.ts @@ -0,0 +1,99 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import * as SecureStore from "expo-secure-store"; +import { router } from "expo-router"; +import { handleErrorResponse } from "@inrupt/solid-client-errors"; + +export const SESSION_KEY = "session"; + +export const makeApiRequest = async ( + endpoint: string, + method: string = "GET", + body: unknown = null, + contentType: string | null = "application/json", + isBlob: boolean = false +): Promise => { + const session = await SecureStore.getItemAsync(SESSION_KEY); + if (!session) return {} as T; + + const headers: HeadersInit = {}; + + if (contentType) { + headers["Content-Type"] = contentType; + } + + const options: RequestInit = { + method, + headers, + }; + + if (body !== null) { + options.body = body as BodyInit; + } + + const response = await fetch( + `${process.env.EXPO_PUBLIC_WALLET_API}/${endpoint}`, + options + ); + + if (response.status === 401) { + router.replace(`/login?logout=${Date.now()}`); + throw new Error(`Unauthorized: ${response.status}`); + } + + if (!response.ok) { + throw handleErrorResponse( + response, + await response.text(), + `${endpoint} returned an error response.` + ); + } + + if (isBlob) { + return (await response.blob()) as unknown as T; + } + + const responseType = response.headers.get("content-type"); + if ( + responseType?.includes("application/json") || + responseType?.includes("application/ld+json") + ) { + const result: T = await response.json(); + return result; + } + if ( + responseType?.includes("text/plain") || + responseType?.includes("text/turtle") + ) { + const result: T = (await response.text()) as unknown as T; + return result; + } + + const result: T = (await response.blob()) as unknown as T; + return result; +}; + +export const objectToParams = (obj: object): string => { + const params = new URLSearchParams(); + + Object.entries(obj).forEach(([key, value]) => { + if (value !== null && value !== undefined) { + params.append(key, String(value)); + } + }); + + return params.toString(); +}; diff --git a/api/files.ts b/api/files.ts new file mode 100644 index 0000000..80a7528 --- /dev/null +++ b/api/files.ts @@ -0,0 +1,113 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import mime from "mime"; +import FormData from "form-data"; +import type { WalletFile } from "@/types/WalletFile"; +import { handleErrorResponse } from "@inrupt/solid-client-errors"; +import { utf8EncodeResourceName } from "@/utils/fileUtils"; +import { makeApiRequest } from "./apiRequest"; + +interface FileObject { + uri: string; + name: string; + type?: string; +} + +export const fetchFiles = async (): Promise => { + return makeApiRequest("wallet"); +}; + +export const postFile = async (fileMetadata: FileObject): Promise => { + const acceptValue = fileMetadata.type ?? mime.getType(fileMetadata.name); + const acceptHeader = new Headers(); + if (acceptValue !== null) { + acceptHeader.append("Accept", acceptValue); + } + // Make a HEAD request to the file to report on potential errors + // in more details than the fetch with the FormData. + const fileResponse = await fetch(fileMetadata.uri, { + headers: acceptHeader, + method: "HEAD", + }); + if (!fileResponse.ok) { + throw handleErrorResponse( + fileResponse, + await fileResponse.text(), + "Failed to fetch file to upload" + ); + } + // The following is declared as `any` because there is a type inconsistency, + // and the global FormData (expected by the fetch body) is actually not compliant + // with the Web spec and its TS declarations. formData.set doesn't exist, and + // formData.append doesn't support a Blob being passed. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const formData: any = new FormData(); + formData.append("file", { + name: utf8EncodeResourceName(fileMetadata.name), + type: + fileMetadata.type || + mime.getType(fileMetadata.name) || + "application/octet-stream", + uri: fileMetadata.uri, + }); + formData.append("fileName", fileMetadata.name); + let response: Response; + try { + response = await fetch( + new URL("wallet", process.env.EXPO_PUBLIC_WALLET_API), + { + method: "PUT", + body: formData, + } + ); + } catch (e) { + console.debug("Resolving the file and uploading it to the wallet failed."); + throw e; + } + + if (response.ok) { + console.debug( + `Uploaded file to Wallet. HTTP response status:${response.status}` + ); + } else { + throw handleErrorResponse( + response, + await response.text(), + "Failed to upload file to Wallet" + ); + } +}; + +export const deleteFile = async (fileId: string): Promise => { + return makeApiRequest(`wallet/${encodeURIComponent(fileId)}`, "DELETE"); +}; + +export const getFile = async (fileId: string): Promise => { + return makeApiRequest( + `wallet/${encodeURIComponent(fileId)}?raw=true`, + "GET" + ); +}; + +export const downloadFile = async (fileId: string): Promise => { + return makeApiRequest( + `wallet/${encodeURIComponent(fileId)}?raw=true`, + "GET", + null, + null, + true + ); +}; diff --git a/api/user.ts b/api/user.ts new file mode 100644 index 0000000..3559fdc --- /dev/null +++ b/api/user.ts @@ -0,0 +1,29 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import type { UserInfo } from "@/constants/user"; +import { makeApiRequest } from "./apiRequest"; + +export const getUserInfo = async (): Promise => { + return makeApiRequest("login/userInfo"); +}; + +export const logout = async () => { + return makeApiRequest("logout", "post"); +}; + +export const signup = async () => { + return makeApiRequest("signup", "POST"); +}; diff --git a/app.config.ts b/app.config.ts new file mode 100644 index 0000000..69eda2b --- /dev/null +++ b/app.config.ts @@ -0,0 +1,122 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import type { ExpoConfig, ConfigContext } from "expo/config"; + +const isDevelopmentMode = + process.env.NODE_ENV === "development" || + process.env.EAS_BUILD_PROFILE === "development"; +const isTestMode = + !isDevelopmentMode && + process.env.EAS_BUILD_PROFILE !== "production" && + process.env.EAS_BUILD_PROFILE === "preview"; + +function validateEnv() { + if ( + typeof process.env.EXPO_PUBLIC_WALLET_API !== "string" || + !URL.canParse(process.env.EXPO_PUBLIC_WALLET_API) + ) { + throw new Error( + `Missing or invalid environment variable EXPO_PUBLIC_WALLET_API. Expected a valid URL, found ${process.env.EXPO_PUBLIC_WALLET_API}` + ); + } + if ( + typeof process.env.EXPO_PUBLIC_LOGIN_URL !== "string" || + !URL.canParse(process.env.EXPO_PUBLIC_LOGIN_URL) + ) { + throw new Error( + `Missing or invalid environment variable EXPO_PUBLIC_LOGIN_URL. Expected a valid URL, found ${process.env.EXPO_PUBLIC_LOGIN_URL}` + ); + } + if (typeof process.env.EAS_PROJECT_ID !== "string") { + throw new Error(`Missing environment variable EAS_PROJECT_ID.`); + } +} +if (process.env.EAS_BUILD === "true") { + // Check that all required environment variables are defined at build time. + validateEnv(); +} + +const baseConfig: ExpoConfig = { + name: "inrupt-data-wallet", + slug: "inrupt-data-wallet", + version: "1.0.0", + orientation: "portrait", + icon: "./assets/images/logo.png", + scheme: "inrupt-data-wallet", + userInterfaceStyle: "automatic", + splash: { + image: "./assets/images/splash.png", + resizeMode: "contain", + backgroundColor: "#ffffff", + }, + ios: { + supportsTablet: true, + bundleIdentifier: "com.inrupt.inrupt-data-wallet", + }, + android: { + adaptiveIcon: { + foregroundImage: "./assets/images/adaptive-icon.png", + backgroundColor: "#ffffff", + }, + package: "com.inrupt.inrupt_data_wallet", + permissions: [ + "android.permission.CAMERA", + // Not including the following prevents from taking pictures + // and reading the media gallery in Android 12. + "android.permission.WRITE_EXTERNAL_STORAGE", + ], + blockedPermissions: [ + "android.permission.RECORD_AUDIO", + "android.permission.READ_EXTERNAL_STORAGE", + ], + allowBackup: false, + }, + web: { + bundler: "metro", + output: "static", + favicon: "./assets/images/logo.png", + }, + plugins: [ + "expo-router", + "expo-secure-store", + [ + "expo-build-properties", + { + android: { + usesCleartextTraffic: isDevelopmentMode, + }, + }, + ], + "./plugins/withSigningConfig", + // The detox plugin interferes with the generated output, so + // only include it when actually building for tests. + ...(isTestMode ? ["@config-plugins/detox"] : []), + ], + experiments: { + typedRoutes: true, + }, + extra: { + eas: { + projectId: process.env.EAS_PROJECT_ID, + }, + }, + owner: "inrupt", +}; + +export default ({ config }: ConfigContext): ExpoConfig => ({ + ...config, + ...baseConfig, +}); diff --git a/app/(tabs)/_layout.tsx b/app/(tabs)/_layout.tsx new file mode 100644 index 0000000..8efcd77 --- /dev/null +++ b/app/(tabs)/_layout.tsx @@ -0,0 +1,191 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import { router, Tabs } from "expo-router"; +import type { MutableRefObject } from "react"; +import React, { useRef, useState } from "react"; +import HouseOutLine from "@/assets/images/house-outline.svg"; +import AccessOutLine from "@/assets/images/access-outline.svg"; +import AccessSolid from "@/assets/images/access-solid.svg"; + +import { FontAwesome6 } from "@expo/vector-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome"; +import { faBell } from "@fortawesome/free-solid-svg-icons/faBell"; +import { faUser } from "@fortawesome/free-solid-svg-icons/faUser"; +import { TouchableOpacity } from "react-native"; +import PopupMenu from "@/components/PopupMenu"; + +export default function TabLayout() { + const [menuVisible, setMenuVisible] = useState(false); + const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 }); + + const [positionType, setPositionType] = useState< + "topMiddle" | "bottomLeft" | "bottomMiddle" + >("bottomMiddle"); + const tabBarAddButtonRef = useRef(null); + const rightHeaderAddButtonRef = useRef(null); + const toggleMenu = ( + type: "topMiddle" | "bottomLeft" | "bottomMiddle" = "topMiddle", + buttonRef: MutableRefObject = rightHeaderAddButtonRef + ) => { + if (buttonRef && buttonRef.current) { + ( + buttonRef.current as unknown as { + measure: ( + callback: ( + _fx: number, + _fy: number, + _width: number, + _height: number, + px: number, + py: number + ) => void + ) => void; + } + ).measure( + ( + _fx: number, + _fy: number, + _width: number, + _height: number, + px: number, + py: number + ) => { + setMenuPosition({ x: px, y: py }); + setPositionType(type); + setMenuVisible(!menuVisible); + } + ); + } + }; + + return ( + <> + + + focused ? ( + + ) : ( + + ), + headerTitle: "Wallet", + headerRight: () => ( + + toggleMenu("bottomLeft", rightHeaderAddButtonRef) + } + > + + + ), + headerRightContainerStyle: { paddingRight: 16 }, + }} + /> + + + focused ? ( + + ) : ( + + ), + }} + /> + , + tabBarButton: (props) => ( + toggleMenu("topMiddle", tabBarAddButtonRef)} + /> + ), + }} + redirect={false} + /> + + focused ? ( + + ) : ( + + ), + }} + /> + + focused ? ( + + ) : ( + + ), + }} + /> + + { + toggleMenu( + "topMiddle", + tabBarAddButtonRef || rightHeaderAddButtonRef + ); + }} + onUploadSuccess={() => { + router.replace("/home"); + }} + position={menuPosition} + positionType={positionType} + /> + + ); +} diff --git a/app/(tabs)/accesses/[webId].tsx b/app/(tabs)/accesses/[webId].tsx new file mode 100644 index 0000000..1f3ccee --- /dev/null +++ b/app/(tabs)/accesses/[webId].tsx @@ -0,0 +1,229 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import React, { + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, +} from "react"; +import { StyleSheet, TouchableOpacity, View } from "react-native"; +import { useLocalSearchParams, useNavigation } from "expo-router"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import AccessGrantList from "@/components/accessGrants/AccessGrantList"; +import { FontAwesome6 } from "@expo/vector-icons"; +import BottomModal from "@/components/accessGrants/modal/BottomModal"; +import { BottomSheetModal } from "@gorhom/bottom-sheet"; +import { revokeAccessGrant, revokeAccessGrantList } from "@/api/accessGrant"; +import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome"; +import { faEllipsis } from "@fortawesome/free-solid-svg-icons/faEllipsis"; +import WebIdDisplay from "@/components/common/WebIdDisplay"; +import ConfirmModal from "@/components/common/ConfirmModal"; +import Loading from "@/components/LoadingButton"; +import type { AccessGrant, AccessGrantGroup } from "@/types/accessGrant"; + +interface AccessGrantProps {} + +const Page: React.FC = () => { + const navigation = useNavigation(); + const parentNavigation = useNavigation("/(tabs)"); + const { webId } = useLocalSearchParams(); + const { data = [], refetch } = useQuery({ + queryKey: ["accessGrants"], + enabled: false, + }); + const selectedRequest = data && data.find((r) => r.webId === webId); + + const [selectedAG, setSelectedAG] = useState(); + const [selectedWebId, setSelectedWebId] = useState(); + const [isUpdating, setUpdating] = useState(false); + const [modalVisible, setModalVisible] = useState(false); + const bottomSheetModalRef = useRef(null); + const snapPoints = useMemo(() => [200, 200], []); + + const mutationRevokeAccessGrant = useMutation({ + mutationFn: revokeAccessGrant, + onSuccess: async () => { + setModalVisible(false); + setUpdating(false); + if (selectedRequest && selectedRequest.items.length <= 1) { + navigation.goBack(); + } else { + // eslint-disable-next-line no-console + refetch().catch(() => console.error("Error while refetching data")); + } + }, + }); + + const mutationRevokeAccessGrantList = useMutation({ + mutationFn: revokeAccessGrantList, + onSuccess: async () => { + setModalVisible(false); + setUpdating(false); + navigation.goBack(); + }, + }); + + useLayoutEffect(() => { + navigation.setOptions({ + headerTitle: selectedRequest?.ownerName, + headerLeft: () => ( + navigation.goBack()} + style={{ width: 60, paddingLeft: 8 }} + > + + + ), + headerRight: () => ( + { + setSelectedAG(undefined); + setSelectedWebId(selectedRequest?.webId); + bottomSheetModalRef.current?.present(); + }} + > + + + ), + }); + }, [navigation, selectedRequest]); + + useEffect(() => { + parentNavigation.setOptions({ + headerShown: false, + }); + return () => { + parentNavigation.setOptions({ headerShown: true }); + }; + }, [parentNavigation]); + + const closeMenu = () => bottomSheetModalRef.current?.close(); + + const handleRevoke = () => { + setModalVisible(true); + closeMenu(); + }; + + const handleConfirmToRevoke = (item: AccessGrant) => { + setUpdating(true); + setSelectedAG(undefined); + mutationRevokeAccessGrant.mutate({ requestId: item.uuid as string }); + }; + + const handleConfirmToRevokeAGList = (group: AccessGrantGroup) => { + setUpdating(true); + setSelectedWebId(undefined); + mutationRevokeAccessGrantList.mutate({ + requestId: group.items.map((item: AccessGrant) => item.uuid), + }); + }; + + const handleSelectedItem = (item: AccessGrant) => { + setSelectedAG(item); + setSelectedWebId(undefined); + bottomSheetModalRef.current?.present(); + }; + + return selectedRequest ? ( + <> + + + + + ( + bottomSheetModalRef.current?.close()} + /> + )} + > + + + {selectedAG && ( + handleConfirmToRevoke(selectedAG!)} + confirmLabel={"Revoke Access"} + onClose={() => setModalVisible(false)} + /> + )} + + {selectedWebId && ( + handleConfirmToRevokeAGList(selectedRequest)} + confirmLabel={"Revoke All Access"} + onClose={() => setModalVisible(false)} + /> + )} + + + ) : ( + + + + ); +}; + +const styles = StyleSheet.create({ + loadingContainer: { + ...StyleSheet.absoluteFillObject, + zIndex: 1, + position: "absolute", + justifyContent: "center", + alignItems: "center", + backgroundColor: "rgba(255, 255, 255, 0.5)", // Semi-transparent background + }, + container: { + flex: 1, + padding: 24, + justifyContent: "space-between", + backgroundColor: "#fff", + }, + content: { + flex: 1, + }, + bottomSheetContainer: { + shadowColor: "#000000", + shadowOffset: { width: 4, height: 9 }, + shadowOpacity: 0.2, + shadowRadius: 24, + elevation: 5, + borderRadius: 26, + }, +}); + +export default Page; diff --git a/app/(tabs)/accesses/_layout.tsx b/app/(tabs)/accesses/_layout.tsx new file mode 100644 index 0000000..656bf53 --- /dev/null +++ b/app/(tabs)/accesses/_layout.tsx @@ -0,0 +1,38 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import { Stack } from "expo-router"; +import React from "react"; +import Loading from "@/components/LoadingButton"; +import { useIsMutating } from "@tanstack/react-query"; + +export default function TabLayout() { + const isMutatingFiles = useIsMutating({ mutationKey: ["filesMutation"] }); + return ( + <> + + + + + + + ); +} diff --git a/app/(tabs)/accesses/index.test.tsx b/app/(tabs)/accesses/index.test.tsx new file mode 100644 index 0000000..6de2c94 --- /dev/null +++ b/app/(tabs)/accesses/index.test.tsx @@ -0,0 +1,128 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import * as React from "react"; +import { screen } from "@testing-library/react-native"; + +import { jest, describe, it, expect } from "@jest/globals"; +import type * as ExpoRouter from "expo-router"; +import type * as ReactQuery from "@tanstack/react-query"; + +import { render } from "@/test/providers"; +import { AccessRequestMode } from "@/types/enums"; +import type { AccessGrant } from "@/types/accessGrant"; +import GrantsScreen from "./index"; + +const mockRefetch = jest.fn().mockImplementation(() => { + return Promise.resolve({ data: [], status: "success" }); +}); + +function mockUseQuery( + data: AccessGrant[] +): ReturnType { + return { + data, + isLoading: false, + isFetching: false, + refetch: mockRefetch, + } as unknown as ReturnType; +} + +jest.mock("@tanstack/react-query", () => { + const actualReactQuery = jest.requireActual( + "@tanstack/react-query" + ) as typeof ReactQuery; + return { + ...actualReactQuery, + // Only mock the subset of the module relevant to the test. + useIsMutating: jest.fn(), + useMutation: jest.fn(), + useQueryClient: jest.fn(), + useQuery: jest.fn(), + }; +}); + +jest.mock("expo-router", () => { + const actualExpoRouter = jest.requireActual( + "expo-router" + ) as typeof ExpoRouter; + return { + ...actualExpoRouter, + useRouter: jest.fn().mockReturnValue({ + // Only mock a subset of the Expo Router + navigate: jest.fn(), + } as unknown as ReturnType<(typeof ExpoRouter)["useRouter"]>), + useFocusEffect: jest.fn(), + useLocalSearchParams: jest + .fn() + .mockReturnValue({ forceLogout: undefined }), + useNavigation: jest + .fn() + .mockReturnValue({ setOptions: jest.fn() }), + Redirect: jest.fn(), + }; +}); + +describe("Snapshot testing the home screen", () => { + it("shows text when no access granted", async () => { + // Mocks begin... + const { useQuery: mockedUseQuery } = jest.requireMock( + "@tanstack/react-query" + ) as jest.Mocked; + mockedUseQuery.mockReturnValue(mockUseQuery([])); + // ... mocks end + + render(); + await expect( + screen.findByTestId("no-access-grants-text") + ).resolves.toBeVisible(); + }); + + it("shows pending requests", async () => { + // Mocks begin... + const { useQuery: mockedUseQuery } = jest.requireMock( + "@tanstack/react-query" + ) as jest.Mocked; + mockedUseQuery.mockReturnValue( + mockUseQuery([ + { + uuid: "0000-0000-0000-0000", + webId: "https://example.org/id/some-username", + ownerName: "Some Owner", + expirationDate: new Date("2024-08-22:12:00:00Z"), + issuedDate: new Date("2024-08-22:12:00:00Z"), + forPurpose: "https://example.org/ns/some-purpose", + modes: [AccessRequestMode.Read], + logo: "https://example.org/id/some-username#some-profile-pic", + identifier: "some-identifier", + resource: "https://example.org/storage/some-resource", + resourceName: "some-resource", + isRDFResource: false, + }, + ]) + ); + // ... mocks end + + render(); + await expect( + screen.findByTestId("access-grants-list") + ).resolves.toBeVisible(); + await expect(screen.findByText("Some Owner")).resolves.toBeVisible(); + await expect( + screen.findByText("https://example.org/id/some-username") + ).resolves.toBeVisible(); + }); +}); diff --git a/app/(tabs)/accesses/index.tsx b/app/(tabs)/accesses/index.tsx new file mode 100644 index 0000000..e75e988 --- /dev/null +++ b/app/(tabs)/accesses/index.tsx @@ -0,0 +1,62 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import { getAccessGrants } from "@/api/accessGrant"; +import { useQuery } from "@tanstack/react-query"; +import { StyleSheet, View } from "react-native"; +import WebIdAccessGrantList from "@/components/accessGrants/WebIdAccessGrantList"; +import useRefreshOnFocus from "@/hooks/useRefreshOnFocus"; +import type { AccessGrantGroup } from "@/types/accessGrant"; +import { useEffect } from "react"; + +export default function AccessGrantScreen() { + const { + data = [], + isLoading, + isFetching, + refetch, + } = useQuery({ + queryKey: ["accessGrants"], + queryFn: getAccessGrants, + enabled: false, + }); + + useEffect(() => { + refetch().catch((err) => console.log(err)); + return () => { + console.debug("Unmount AccessGrantScreen"); + }; + }, [refetch]); + + useRefreshOnFocus(refetch); + + return ( + + refetch()} + refreshing={false} + /> + + ); +} +const styles = StyleSheet.create({ + container: { + flex: 1, + padding: 24, + backgroundColor: "#fff", + }, +}); diff --git a/app/(tabs)/add.tsx b/app/(tabs)/add.tsx new file mode 100644 index 0000000..37c5496 --- /dev/null +++ b/app/(tabs)/add.tsx @@ -0,0 +1,27 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import { View, StyleSheet } from "react-native"; + +export default function HomeScreen() { + return ; +} +const styles = StyleSheet.create({ + container: { + flex: 1, + + backgroundColor: "#fff", + }, +}); diff --git a/app/(tabs)/home/[fileName].tsx b/app/(tabs)/home/[fileName].tsx new file mode 100644 index 0000000..0c4f2b3 --- /dev/null +++ b/app/(tabs)/home/[fileName].tsx @@ -0,0 +1,219 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import React, { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { View, StyleSheet, TouchableOpacity, Image } from "react-native"; +import { useIsMutating, useQuery } from "@tanstack/react-query"; +import { getFile } from "@/api/files"; +import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome"; +import { faEllipsis } from "@fortawesome/free-solid-svg-icons/faEllipsis"; +import { useLocalSearchParams, useNavigation } from "expo-router"; +import { BottomSheetModal } from "@gorhom/bottom-sheet"; +import { isImageFile } from "@/utils/fileUtils"; +import { FontAwesome6 } from "@expo/vector-icons"; +import { Colors } from "@/constants/Colors"; +import VcCard from "@/components/files/VcCard"; +import BottomModal from "@/components/files/BottomModal"; +import type { WalletFile } from "@/types/WalletFile"; +import Loading from "@/components/LoadingButton"; +import { ThemedText } from "@/components/ThemedText"; + +interface FileDetailProps { + file: WalletFile; + onClose: () => void; + onOpenMenu: (file: WalletFile) => void; +} +const blobToBase64 = (blob: Blob): Promise => { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + const result = reader.result as string; + resolve(result.split(",")[1]); + }; + reader.onerror = reject; + reader.readAsDataURL(blob); + }); +}; + +const Page: React.FC = () => { + const isMutatingFiles = useIsMutating({ mutationKey: ["filesMutation"] }); + + const { fileName, isRDFResourceStr, identifier } = useLocalSearchParams(); + const isRDFResource: boolean = isRDFResourceStr === "true"; + const [imageUri, setImageUri] = useState(null); + + const bottomSheetModalRef = useRef(null); + const { setOptions, goBack } = useNavigation("/(tabs)"); + const currentNavigation = useNavigation(); + // data can be a json file from server so need to use any + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const { data } = useQuery({ + queryKey: ["file", fileName], + queryFn: () => getFile(fileName as string), + }); + + useEffect(() => { + setOptions({ headerShown: false }); + return () => { + setOptions({ headerShown: true }); + }; + }, [setOptions]); + useLayoutEffect(() => { + currentNavigation.setOptions({ + headerRight: () => ( + bottomSheetModalRef.current?.present()} + > + + + ), + headerBackVisible: false, + headerTitleAlign: "center", + headerTitleStyle: { + alignItems: "center", + justifyContent: "center", + }, + headerTitle: () => ( + + + {data?.name || fileName} + + + ), + headerLeft: () => ( + currentNavigation.goBack()} + style={{ paddingLeft: 8 }} + > + + + ), + }); + }, [currentNavigation, data?.name, fileName]); + useEffect(() => { + const fetchImageAsBlob = async () => { + try { + const base64Data = await blobToBase64(data); + setImageUri(`data:image/png;base64,${base64Data}`); + } catch (error) { + /* empty */ + } + }; + + if (data && isImageFile(fileName as string)) { + fetchImageAsBlob().catch(() => { + /* empty */ + }); + } + }, [data, fileName]); + + return ( + + {isImageFile(fileName as string) && imageUri && ( + + )} + {isRDFResource && data && } + + ( + bottomSheetModalRef.current?.close()} + /> + )} + enablePanDownToClose + > + bottomSheetModalRef.current?.close()} + onDeleteSuccessfully={goBack} + onChangeSnapPoint={(snapHeight: number) => { + if (snapHeight === 360) bottomSheetModalRef.current?.snapToIndex(2); + else if (snapHeight <= 260) + bottomSheetModalRef.current?.snapToIndex(1); + else bottomSheetModalRef.current?.snapToPosition(snapHeight); + }} + /> + + + ); +}; + +const styles = StyleSheet.create({ + modalContainer: { + flex: 1, + height: "100%", + paddingHorizontal: 32, + backgroundColor: "#FFF", + justifyContent: "center", + }, + fileName: { + flex: 1, + textAlign: "center", + fontWeight: "bold", + }, + + modalContent: { + flex: 1, + }, + + modalImage: { + width: "100%", + height: "100%", + }, + bottomSheetContainer: { + shadowColor: "#000000", + shadowOffset: { width: 4, height: 9 }, + shadowOpacity: 0.2, + shadowRadius: 24, + elevation: 5, + borderRadius: 26, + position: "absolute", + }, + backdrop: {}, + cardContent: { + backgroundColor: Colors.light.secondaryBackground, + justifyContent: "center", + flexDirection: "column", + padding: 24, + borderRadius: 16, + }, + cardHeader: { + justifyContent: "space-between", + flexDirection: "row", + }, +}); + +export default Page; diff --git a/app/(tabs)/home/_layout.tsx b/app/(tabs)/home/_layout.tsx new file mode 100644 index 0000000..5540a90 --- /dev/null +++ b/app/(tabs)/home/_layout.tsx @@ -0,0 +1,32 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import { Stack } from "expo-router"; +import React from "react"; + +export default function TabLayout() { + return ( + + + + + + ); +} diff --git a/app/(tabs)/home/download.tsx b/app/(tabs)/home/download.tsx new file mode 100644 index 0000000..09d2b35 --- /dev/null +++ b/app/(tabs)/home/download.tsx @@ -0,0 +1,187 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import React, { useEffect, useLayoutEffect } from "react"; +import { View, StyleSheet, TouchableOpacity } from "react-native"; +import { useLocalSearchParams, useNavigation, useRouter } from "expo-router"; +import { ThemedText } from "@/components/ThemedText"; +import CustomButton from "@/components/Button"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { postFile } from "@/api/files"; +import { FontAwesome6 } from "@expo/vector-icons"; +import IconResourceName from "@/components/common/IconResourceName"; +import { RDF_CONTENT_TYPE } from "@/utils/constants"; +import type { WalletFile } from "@/types/WalletFile"; +import { isDownloadQR } from "@/types/accessPrompt"; +import { useError } from "@/hooks/useError"; +import { hasProblemDetails } from "@inrupt/solid-client-errors"; + +interface FileDetailProps { + file: WalletFile; + onClose: () => void; + onOpenMenu: (file: WalletFile) => void; +} + +const Page: React.FC = () => { + const params = useLocalSearchParams(); + const { showErrorMsg } = useError(); + if (!isDownloadQR(params)) { + throw new Error( + "Incorrect params for download request: uri and contentType are required" + ); + } + const queryClient = useQueryClient(); + const currentNavigation = useNavigation(); + const parentNavigation = useNavigation("/(tabs)"); + const { replace } = useRouter(); + + const mutation = useMutation({ + mutationFn: postFile, + onSuccess: async () => { + await queryClient.invalidateQueries({ queryKey: ["files"] }); + }, + onError: (error) => { + if (hasProblemDetails(error)) { + console.debug( + `${error.problemDetails.status}: ${error.problemDetails.title}.` + ); + console.debug(error.problemDetails.detail); + } else { + console.debug("A non-HTTP error happened."); + console.debug(error); + } + showErrorMsg("Unable to save the file into your Wallet."); + }, + mutationKey: ["filesMutation"], + }); + const fileName = params.uri?.substring(params.uri.lastIndexOf("/") + 1); + const contentType: string = params.contentType.split(";")[0].trim(); + const isRdfFile = + (contentType && RDF_CONTENT_TYPE.includes(contentType)) || false; + const onSaveToWallet = async () => { + mutation.mutate({ + uri: params.uri, + name: fileName, + type: params.contentType, + }); + // This used to be goBack() but that leaves the download page on the stack so subsequent file uploads are blocked by it. + // Using replace to return to the homepage my not be ideal, but it works (here and in the cancel handler below). + replace("/"); + }; + useLayoutEffect(() => { + currentNavigation.setOptions({ + headerTitleAlign: "center", + headerTitle: "Save to Wallet", + headerLeft: () => ( + currentNavigation.goBack()} + style={{ width: 60, paddingLeft: 8 }} + > + + + ), + }); + }, [currentNavigation]); + + useEffect(() => { + parentNavigation.setOptions({ headerShown: false }); + return () => { + parentNavigation.setOptions({ headerShown: true }); + }; + }, [parentNavigation]); + return ( + + + + SAVE + + + DOWNLOAD FROM + + + {params.uri} + + + + onSaveToWallet()} + customStyle={styles.button} + /> + replace("/")} + customStyle={styles.button} + /> + + + + ); +}; + +const styles = StyleSheet.create({ + modalContainer: { + flex: 1, + paddingHorizontal: 16, + backgroundColor: "#FFF", + }, + header: { + flexDirection: "row", + alignItems: "center", + justifyContent: "space-between", + backgroundColor: "white", + }, + fileName: { + flex: 1, + textAlign: "center", + fontWeight: "bold", + }, + container: { + flex: 1, + padding: 24, + justifyContent: "space-between", + backgroundColor: "#fff", + }, + content: { + flex: 1, + }, + title: { + paddingTop: 20, + paddingBottom: 8, + fontSize: 10, + }, + button: { width: 210, marginBottom: 24, paddingHorizontal: 36 }, + name: { + fontSize: 16, + }, + detail: { + fontWeight: 400, + fontSize: 16, + lineHeight: 30, + }, + buttonContainer: { + flex: 1, + flexDirection: "column", + justifyContent: "flex-end", + }, +}); + +export default Page; diff --git a/app/(tabs)/home/index.test.tsx b/app/(tabs)/home/index.test.tsx new file mode 100644 index 0000000..2d3c1aa --- /dev/null +++ b/app/(tabs)/home/index.test.tsx @@ -0,0 +1,124 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import * as React from "react"; +import { screen } from "@testing-library/react-native"; + +import { jest, describe, it, expect } from "@jest/globals"; +import type * as ExpoRouter from "expo-router"; +import type * as ReactQuery from "@tanstack/react-query"; + +import { render } from "@/test/providers"; + +import type { WalletFile } from "@/types/WalletFile"; +import HomeScreen from "./index"; + +jest.mock("expo-router", () => { + const actualExpoRouter = jest.requireActual( + "expo-router" + ) as typeof ExpoRouter; + return { + ...actualExpoRouter, + useRouter: jest.fn().mockReturnValue({ + // Only mock a subset of the Expo Router + navigate: jest.fn(), + } as unknown as ReturnType<(typeof ExpoRouter)["useRouter"]>), + useFocusEffect: jest.fn(), + Redirect: jest.fn(), + }; +}); + +const mockRefetch = jest.fn().mockImplementation(() => { + return Promise.resolve({ data: [], status: "success" }); +}); + +function mockUseQuery( + data: WalletFile[] +): ReturnType { + return { + data, + isLoading: false, + isFetching: false, + refetch: mockRefetch, + } as unknown as ReturnType; +} + +jest.mock("@tanstack/react-query", () => { + const actualReactQuery = jest.requireActual( + "@tanstack/react-query" + ) as typeof ReactQuery; + return { + ...actualReactQuery, + // Only mock the subset of the module relevant to the test. + useIsMutating: jest.fn(), + useMutation: jest.fn(), + useQueryClient: jest.fn(), + useQuery: jest.fn(), + }; +}); + +// This module is ESM-only, which is problematic for Jest imports. +jest.mock("@fortawesome/react-native-fontawesome", () => ({ + FontAwesomeIcon: jest.fn(), +})); + +// This module is ESM-only, which is problematic for Jest imports. +jest.mock("react-native-safe-area-context", () => ({ + useSafeAreaInsets: jest.fn(), +})); + +// This module is ESM-only, which is problematic for Jest imports. +jest.mock("mime", () => ({ + default: jest.fn(), +})); + +describe("Snapshot testing the home screen", () => { + it("shows the given file list", async () => { + // Mocks begin... + const { useQuery: mockedUseQuery } = jest.requireMock( + "@tanstack/react-query" + ) as jest.Mocked; + mockedUseQuery.mockReturnValue( + mockUseQuery([ + { + identifier: "some-file-identifier", + fileName: "some-file-name", + isRDFResource: true, + }, + ]) + ); + // ... mocks end + + render(); + await expect(screen.findByText("some-file-name")).resolves.toBeVisible(); + }); + + it("shows add button on an empty file list", async () => { + // Mocks begin... + const { useQuery: mockedUseQuery } = jest.requireMock( + "@tanstack/react-query" + ) as jest.Mocked; + mockedUseQuery.mockReturnValue(mockUseQuery([])); + // ... mocks end + + render(); + await expect( + screen.findByTestId("default-add-button") + ).resolves.toBeVisible(); + // Because the way the menu should show up is tied to native behavior, + // snapshot tests cannot check whether the button works or not. + }); +}); diff --git a/app/(tabs)/home/index.tsx b/app/(tabs)/home/index.tsx new file mode 100644 index 0000000..43a394a --- /dev/null +++ b/app/(tabs)/home/index.tsx @@ -0,0 +1,164 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import CustomButton from "@/components/Button"; +import PopupMenu from "@/components/PopupMenu"; +import { ThemedText } from "@/components/ThemedText"; +import React, { useEffect, useRef, useState } from "react"; +import { View, StyleSheet, TouchableOpacity } from "react-native"; +import { useQuery } from "@tanstack/react-query"; +import { fetchFiles } from "@/api/files"; +import FileList from "@/components/files/FileList"; +import useRefreshOnFocus from "@/hooks/useRefreshOnFocus"; +import { Colors } from "@/constants/Colors"; +import type { WalletFile } from "@/types/WalletFile"; + +const HomeScreen = () => { + const { data, isLoading, isFetching, refetch } = useQuery({ + queryKey: ["files"], + queryFn: fetchFiles, + enabled: false, + }); + + useEffect(() => { + refetch().catch((err) => console.error(err)); + return () => { + console.debug("Unmount HomeScreen"); + }; + }, [refetch]); + + useRefreshOnFocus(refetch); + + const [menuVisible, setMenuVisible] = useState(false); + const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 }); + const [positionType, setPositionType] = useState< + "topMiddle" | "bottomLeft" | "bottomMiddle" + >("bottomMiddle"); + const addButtonRef = useRef(null); + + const toggleMenu = (type: "topMiddle" | "bottomLeft" | "bottomMiddle") => { + if (addButtonRef && addButtonRef.current) { + // Because addButtonRef is passed as the `ref` prop of a component, + // addButtonRef.current references the component itself. + ( + addButtonRef.current as unknown as { + measure: ( + callback: ( + _fx: number, + _fy: number, + _width: number, + _height: number, + px: number, + py: number + ) => void + ) => void; + } + ).measure( + ( + _fx: number, + _fy: number, + _width: number, + _height: number, + px: number, + py: number + ) => { + setMenuPosition({ x: px, y: py }); + setPositionType(type); + setMenuVisible(true); + } + ); + } + }; + + return ( + + {(data && data.length > 0) || isLoading ? ( + refetch()} + refreshing={false} + /> + ) : ( + + + Add your own data, such as photos, files, or notes. + + + toggleMenu("topMiddle")} + testID="default-add-button" + > + + + )} + + setMenuVisible(false)} + onUploadSuccess={refetch} + position={menuPosition} + positionType={positionType} + /> + + ); +}; + +const styles = StyleSheet.create({ + container: { + backgroundColor: "white", + flex: 1, + padding: 10, + }, + emptyStateContainer: { + backgroundColor: "white", + flex: 1, + justifyContent: "center", + alignItems: "center", + padding: 20, + paddingHorizontal: 70, + }, + text: { + fontSize: 18, + textAlign: "center", + marginBottom: 28, + color: Colors.light.grey, + }, + button: { + paddingVertical: 10, + paddingHorizontal: 20, + backgroundColor: "#007bff", + borderRadius: 5, + }, + buttonText: { + color: "#fff", + fontSize: 16, + }, + list: { + flexGrow: 1, + }, + item: { + padding: 15, + borderBottomWidth: 1, + borderBottomColor: "#ccc", + }, + itemText: { + fontSize: 16, + }, +}); + +export default HomeScreen; diff --git a/app/(tabs)/profile.test.tsx b/app/(tabs)/profile.test.tsx new file mode 100644 index 0000000..db5bd7f --- /dev/null +++ b/app/(tabs)/profile.test.tsx @@ -0,0 +1,129 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import * as React from "react"; +import { screen } from "@testing-library/react-native"; + +import { jest, describe, it, expect } from "@jest/globals"; +import type * as ExpoRouter from "expo-router"; +import type * as ReactQuery from "@tanstack/react-query"; + +import { render } from "@/test/providers"; +import * as SessionHooks from "@/hooks/session"; +import type { UserInfo } from "@/constants/user"; +import ProfileScreen from "./profile"; + +const { useSession } = SessionHooks; + +const mockRefetch = jest.fn().mockImplementation(() => { + return Promise.resolve({ data: {}, status: "success" }); +}); + +function mockUseQuery(data: UserInfo): ReturnType { + return { + data, + isLoading: false, + isFetching: false, + refetch: mockRefetch, + } as unknown as ReturnType; +} + +jest.mock("@tanstack/react-query", () => { + const actualReactQuery = jest.requireActual( + "@tanstack/react-query" + ) as typeof ReactQuery; + return { + ...actualReactQuery, + // Only mock the subset of the module relevant to the test. + useIsMutating: jest.fn(), + useMutation: jest.fn(), + useQueryClient: jest.fn(), + useQuery: jest.fn(), + }; +}); + +jest.mock("expo-router", () => { + const actualExpoRouter = jest.requireActual( + "expo-router" + ) as typeof ExpoRouter; + return { + ...actualExpoRouter, + useRouter: jest.fn().mockReturnValue({ + // Only mock a subset of the Expo Router + navigate: jest.fn(), + } as unknown as ReturnType<(typeof ExpoRouter)["useRouter"]>), + useFocusEffect: jest.fn(), + useLocalSearchParams: jest + .fn() + .mockReturnValue({ forceLogout: undefined }), + useNavigation: jest + .fn() + .mockReturnValue({ setOptions: jest.fn() }), + Redirect: jest.fn(), + }; +}); + +jest.mock("@/hooks/session", () => { + const actualSessionModule = jest.requireActual( + "@/hooks/session" + ) as typeof SessionHooks; + const actualSessionProvider = actualSessionModule.SessionProvider; + return { + useSession: jest.fn().mockReturnValue({ + signOut: jest.fn(), + signIn: jest.fn(), + session: "some-session-id", + }), + SessionProvider: actualSessionProvider, + }; +}); + +// This module is ESM-only, which is problematic for Jest imports. +jest.mock("@fortawesome/react-native-fontawesome", () => ({ + FontAwesomeIcon: jest.fn(), +})); + +// Jest chokes on importing native SVG. +jest.mock("@/assets/images/access-solid.svg", () => { + return jest.fn(); +}); + +describe("Snapshot testing the home screen", () => { + it("shows user profile", async () => { + // Mocks begin... + const { useQuery: mockedUseQuery } = jest.requireMock( + "@tanstack/react-query" + ) as jest.Mocked; + mockedUseQuery.mockReturnValue( + mockUseQuery({ + webId: "https://example.org/id/some-username", + name: "some-username", + logo: "https://example.org/id/some-username#some-profile-pic", + signupRequired: true, + }) + ); + // ... mocks end + + render(); + await expect(screen.findByTestId("username")).resolves.toHaveTextContent( + "some-username" + ); + await expect(screen.findByTestId("webid")).resolves.toHaveTextContent( + "https://example.org/id/some-username" + ); + await expect(screen.findByTestId("qrCode")).resolves.toBeVisible(); + }); +}); diff --git a/app/(tabs)/profile.tsx b/app/(tabs)/profile.tsx new file mode 100644 index 0000000..25540ac --- /dev/null +++ b/app/(tabs)/profile.tsx @@ -0,0 +1,214 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import { View, StyleSheet, Image, TouchableOpacity } from "react-native"; +import { router, useNavigation } from "expo-router"; +import React, { useEffect, useRef } from "react"; +import { ThemedText } from "@/components/ThemedText"; +import QRCode from "react-native-qrcode-svg"; +import Logo from "@/assets/images/future_co.svg"; +import { faEllipsis } from "@fortawesome/free-solid-svg-icons/faEllipsis"; +import { faRightFromBracket } from "@fortawesome/free-solid-svg-icons/faRightFromBracket"; + +import { useIsMutating, useQuery } from "@tanstack/react-query"; +import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome"; +import { BottomSheetModal, BottomSheetView } from "@gorhom/bottom-sheet"; +import type { UserInfo } from "@/constants/user"; +import AccessSolid from "@/assets/images/access-solid.svg"; +import { formatResourceName } from "@/utils/fileUtils"; +import { getUserInfo } from "@/api/user"; +import Loading from "@/components/LoadingButton"; + +export default function Profile() { + const { data: userInfo, refetch } = useQuery({ + queryKey: ["userInfo"], + queryFn: getUserInfo, + enabled: false, + }); + + useEffect(() => { + refetch().catch((err) => console.error(err)); + return () => { + console.debug("Unmount Profile"); + }; + }, [refetch]); + + const bottomSheetModalRef = useRef(null); + const navigation = useNavigation(); + + useEffect(() => { + navigation.setOptions({ + headerTitle: "", + headerLeft: () => ( + + + + Future CO + + + ), + headerRight: () => ( + bottomSheetModalRef.current?.present()} + > + + + ), + headerRightContainerStyle: { paddingRight: 16 }, + }); + }, [navigation]); + + const isMutatingFiles = useIsMutating({ mutationKey: ["filesMutation"] }); + + const { logo, name, webId } = userInfo || {}; + + return ( + + + + {logo ? ( + + ) : ( + + )} + + + {name || webId + ? formatResourceName(name || webId || "", false, webId) + : null} + + + {webId} + + + + + + + + + ( + bottomSheetModalRef.current?.close()} + /> + )} + enablePanDownToClose + > + + { + bottomSheetModalRef.current?.close(); + router.navigate(`/login?logout=${Date.now()}`); + }} + > + + Logout + + + + + ); +} +const styles = StyleSheet.create({ + container: { + flex: 1, + padding: 24, + justifyContent: "center", + alignItems: "center", + backgroundColor: "#fff", + }, + logo: { + paddingLeft: 16, + flexDirection: "row", + alignItems: "center", + }, + headerTitle: { + textTransform: "uppercase", + color: "#1C2033", + fontWeight: 700, + paddingLeft: 12, + fontSize: 18, + }, + cardContainer: { + backgroundColor: "#E7F1F7", + flexDirection: "column", + paddingHorizontal: 16, + paddingVertical: 24, + width: "100%", + borderRadius: 37.5, + }, + profileContainer: { + alignItems: "center", + flexDirection: "row", + marginBottom: 28, + }, + profileName: { + fontSize: 24, + lineHeight: 30, + marginBottom: 4, + }, + profileUri: { + width: 75, + height: 75, + }, + profileDetail: { + flex: 1, + flexDirection: "column", + marginLeft: 12, + }, + profileWebId: { lineHeight: 22, fontSize: 18 }, + QR: { + marginBottom: 16, + alignItems: "center", + justifyContent: "center", + }, + bottomSheetContainer: { + shadowColor: "#000000", + shadowOffset: { width: 4, height: 9 }, + shadowOpacity: 0.2, + shadowRadius: 24, + elevation: 5, + borderRadius: 26, + position: "absolute", + }, + bottomSheetContent: { + flex: 1, + paddingHorizontal: 32, + paddingTop: 8, + paddingBottom: 30, + justifyContent: "center", + }, + logoutContainer: { + flexDirection: "row", + }, +}); diff --git a/app/(tabs)/requests/[requestId].tsx b/app/(tabs)/requests/[requestId].tsx new file mode 100644 index 0000000..fd19572 --- /dev/null +++ b/app/(tabs)/requests/[requestId].tsx @@ -0,0 +1,205 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import React, { useLayoutEffect } from "react"; +import { View, StyleSheet, TouchableOpacity } from "react-native"; +import { useLocalSearchParams, useNavigation } from "expo-router"; +import { FontAwesome6 } from "@expo/vector-icons"; +import { ThemedText } from "@/components/ThemedText"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import CustomButton from "@/components/Button"; +import { updateAccessRequests } from "@/api/accessRequest"; +import { formatDate } from "@/utils/dateFormatUtils"; +import WebIdDisplay from "@/components/common/WebIdDisplay"; +import type { AccessRequest } from "@/types/accessRequest"; +import IconResourceName from "@/components/common/IconResourceName"; +import CardInfo from "@/components/common/CardInfo"; +import { faEye } from "@fortawesome/free-solid-svg-icons/faEye"; +import { faFloppyDisk } from "@fortawesome/free-solid-svg-icons/faFloppyDisk"; + +import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome"; +import { isAccessContainer, isWriteMode } from "@/utils/fileUtils"; + +const Page: React.FC = () => { + const { requestId } = useLocalSearchParams(); + const navigation = useNavigation(); + const parentNavigation = useNavigation("/(tabs)"); + + const { data = [], refetch } = useQuery({ + queryKey: ["accessRequests"], + enabled: false, + }); + const mutation = useMutation({ + mutationFn: updateAccessRequests, + mutationKey: ["accessRequestsMutation"], + onSuccess: async () => { + await refetch(); + }, + }); + + useLayoutEffect(() => { + navigation.setOptions({ + headerTitle: "Confirm Access", + headerLeft: () => ( + navigation.goBack()} + style={{ width: 60, paddingLeft: 8 }} + > + + + ), + headerTitleAlign: "center", + }); + }, [navigation]); + + useLayoutEffect(() => { + parentNavigation.setOptions({ + headerShown: false, + }); + return () => { + parentNavigation.setOptions({ headerShown: true }); + }; + }, [parentNavigation]); + + const onUpdateRequest = (action: "CONFIRM" | "DENY") => { + mutation.mutate({ requestId: requestId as string, action }); + navigation.goBack(); + }; + const selectedRequest = data && data.find((r) => r.uuid === requestId); + if (!selectedRequest) return null; + + const formattedExpiryDate = formatDate(selectedRequest.expirationDate); + const { ownerName, logo, webId, modes } = selectedRequest; + + return ( + + + + REQUESTOR + + + + + Access Mode + + + } + /> + + {isAccessContainer(selectedRequest.resource) + ? "APPLICATION" + : "RESOURCE"} + + + + + + PURPOSE + + + {selectedRequest.forPurpose} + + + EXPIRY + + + {formattedExpiryDate} + + + + onUpdateRequest("CONFIRM")} + customStyle={styles.button} + /> + onUpdateRequest("DENY")} + customStyle={styles.button} + /> + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + paddingHorizontal: 24, + justifyContent: "space-between", + backgroundColor: "#fff", + }, + content: { + flex: 1, + }, + card: { + flexDirection: "row", + alignItems: "center", + padding: 16, + marginVertical: 10, + borderRadius: 10, + backgroundColor: "#E7F1F7", + }, + title: { + paddingTop: 20, + paddingBottom: 8, + fontSize: 10, + textTransform: "uppercase", + }, + logo: { + width: 40, + height: 40, + marginRight: 12, + }, + textContainer: { + flex: 1, + paddingLeft: 12, + }, + button: { marginBottom: 16, width: 211 }, + name: { + fontSize: 16, + }, + detail: { + fontWeight: 400, + fontSize: 16, + lineHeight: 30, + }, + buttonContainer: { + paddingTop: 16, + flex: 1, + flexDirection: "column", + justifyContent: "flex-end", + }, +}); + +export default Page; diff --git a/app/(tabs)/requests/_layout.tsx b/app/(tabs)/requests/_layout.tsx new file mode 100644 index 0000000..204e2e1 --- /dev/null +++ b/app/(tabs)/requests/_layout.tsx @@ -0,0 +1,40 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import { Stack } from "expo-router"; +import React from "react"; +import { useIsMutating } from "@tanstack/react-query"; +import Loading from "@/components/LoadingButton"; + +export default function TabLayout() { + const isMutatingFiles = useIsMutating({ mutationKey: ["filesMutation"] }); + return ( + <> + + + + + + + ); +} diff --git a/app/(tabs)/requests/index.test.tsx b/app/(tabs)/requests/index.test.tsx new file mode 100644 index 0000000..e1b6755 --- /dev/null +++ b/app/(tabs)/requests/index.test.tsx @@ -0,0 +1,128 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import * as React from "react"; +import { screen } from "@testing-library/react-native"; + +import { jest, describe, it, expect } from "@jest/globals"; +import type * as ExpoRouter from "expo-router"; +import type * as ReactQuery from "@tanstack/react-query"; + +import { render } from "@/test/providers"; +import type { AccessRequest } from "@/types/accessRequest"; +import { AccessRequestMode } from "@/types/enums"; +import RequestsScreen from "./index"; + +const mockRefetch = jest.fn().mockImplementation(() => { + return Promise.resolve({ data: [], status: "success" }); +}); + +function mockUseQuery( + data: AccessRequest[] +): ReturnType { + return { + data, + isLoading: false, + isFetching: false, + refetch: mockRefetch, + } as unknown as ReturnType; +} + +jest.mock("@tanstack/react-query", () => { + const actualReactQuery = jest.requireActual( + "@tanstack/react-query" + ) as typeof ReactQuery; + return { + ...actualReactQuery, + // Only mock the subset of the module relevant to the test. + useIsMutating: jest.fn(), + useMutation: jest.fn(), + useQueryClient: jest.fn(), + useQuery: jest.fn(), + }; +}); + +jest.mock("expo-router", () => { + const actualExpoRouter = jest.requireActual( + "expo-router" + ) as typeof ExpoRouter; + return { + ...actualExpoRouter, + useRouter: jest.fn().mockReturnValue({ + // Only mock a subset of the Expo Router + navigate: jest.fn(), + } as unknown as ReturnType<(typeof ExpoRouter)["useRouter"]>), + useFocusEffect: jest.fn(), + useLocalSearchParams: jest + .fn() + .mockReturnValue({ forceLogout: undefined }), + useNavigation: jest + .fn() + .mockReturnValue({ setOptions: jest.fn() }), + Redirect: jest.fn(), + }; +}); + +describe("Snapshot testing the home screen", () => { + it("shows text when no requests are pending", async () => { + // Mocks begin... + const { useQuery: mockedUseQuery } = jest.requireMock( + "@tanstack/react-query" + ) as jest.Mocked; + mockedUseQuery.mockReturnValue(mockUseQuery([])); + // ... mocks end + + render(); + await expect( + screen.findByTestId("no-access-requests-text") + ).resolves.toBeVisible(); + }); + + it("shows pending requests", async () => { + // Mocks begin... + const { useQuery: mockedUseQuery } = jest.requireMock( + "@tanstack/react-query" + ) as jest.Mocked; + mockedUseQuery.mockReturnValue( + mockUseQuery([ + { + uuid: "0000-0000-0000-0000", + webId: "https://example.org/id/some-username", + ownerName: "Some Owner", + expirationDate: new Date("2024-08-22:12:00:00Z"), + issuedDate: new Date("2024-08-22:12:00:00Z"), + forPurpose: "https://example.org/ns/some-purpose", + modes: [AccessRequestMode.Read], + logo: "https://example.org/id/some-username#some-profile-pic", + identifier: "some-identifier", + resource: "https://example.org/storage/some-resource", + resourceName: "some-resource", + isRDFResource: false, + }, + ]) + ); + // ... mocks end + + render(); + await expect( + screen.findByTestId("access-requests-list") + ).resolves.toBeVisible(); + await expect(screen.findByText("Some Owner")).resolves.toBeVisible(); + await expect( + screen.findByText("https://example.org/id/some-username") + ).resolves.toBeVisible(); + }); +}); diff --git a/app/(tabs)/requests/index.tsx b/app/(tabs)/requests/index.tsx new file mode 100644 index 0000000..12a2822 --- /dev/null +++ b/app/(tabs)/requests/index.tsx @@ -0,0 +1,77 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import { getAccessRequests } from "@/api/accessRequest"; +import RequestList from "@/components/accessRequests/AccessRequestList"; +import useRefreshOnFocus from "@/hooks/useRefreshOnFocus"; +import type { AccessRequest } from "@/types/accessRequest"; +import { FontAwesome6 } from "@expo/vector-icons"; +import { useQuery } from "@tanstack/react-query"; +import { useNavigation } from "expo-router"; +import React, { useEffect } from "react"; +import { View, StyleSheet, TouchableOpacity } from "react-native"; + +export default function AccessRequestScreen() { + const { + data = [], + isLoading, + isFetching, + refetch, + } = useQuery({ + queryKey: ["accessRequests"], + queryFn: getAccessRequests, + enabled: false, + }); + + useEffect(() => { + refetch().catch((err) => console.error(err)); + return () => { + console.debug("Unmount AccessRequestScreen"); + }; + }, [refetch]); + + useRefreshOnFocus(refetch); + + const navigation = useNavigation("/(tabs)"); + + useEffect(() => { + navigation.setOptions({ + headerRight: () => ( + refetch()}> + + + ), + headerRightContainerStyle: { paddingRight: 16 }, + }); + }, [navigation, refetch]); + return ( + + refetch()} + refreshing={false} + /> + + ); +} +const styles = StyleSheet.create({ + container: { + flex: 1, + paddingVertical: 24, + paddingHorizontal: 8, + backgroundColor: "#fff", + }, +}); diff --git a/app/+html.tsx b/app/+html.tsx new file mode 100644 index 0000000..c75ed8a --- /dev/null +++ b/app/+html.tsx @@ -0,0 +1,57 @@ +// +// Copyright Inrupt Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +import { ScrollViewStyleReset } from "expo-router/html"; +import { type PropsWithChildren } from "react"; + +/** + * This file is web-only and used to configure the root HTML for every web page during static rendering. + * The contents of this function only run in Node.js environments and do not have access to the DOM or browser APIs. + */ +export default function Root({ children }: PropsWithChildren) { + return ( + + + + + + + {/* + Disable body scrolling on web. This makes ScrollView components work closer to how they do on native. + However, body scrolling is often nice to have for mobile web. If you want to enable it, remove this line. + */} + + + {/* Using raw CSS styles as an escape-hatch to ensure the background color never flickers in dark-mode. */} +