diff --git a/.forgejo/workflows/bump-libmpv.yml b/.forgejo/workflows/bump-libmpv.yml new file mode 100644 index 0000000..71a3865 --- /dev/null +++ b/.forgejo/workflows/bump-libmpv.yml @@ -0,0 +1,24 @@ +name: "Bump the Windows build's libmpv" + +on: + schedule: + - cron: "0 6 * * 1" + workflow_dispatch: + +jobs: + bump-libmpv: + runs-on: ["small", "debian-13-x86_64"] + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Lix GHA Installer Action + uses: samueldr/lix-gha-installer-action@v2026-02-22 + with: + extra_nix_config: experimental-features = nix-command flakes flake-self-attrs + + - name: Open a PR if there's a newer libmpv build + env: + TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: nix run .#bump-libmpv diff --git a/.forgejo/workflows/e2e.yml b/.forgejo/workflows/e2e.yml new file mode 100644 index 0000000..14d96d2 --- /dev/null +++ b/.forgejo/workflows/e2e.yml @@ -0,0 +1,28 @@ +name: "End-to-end tests" + +on: + schedule: + - cron: "0 6 * * 1" + pull_request: + workflow_dispatch: + +jobs: + e2e: + runs-on: ["large-mem", "debian-13-x86_64"] + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + submodules: recursive + + - name: Lix GHA Installer Action + uses: samueldr/lix-gha-installer-action@v2026-02-22 + with: + extra_nix_config: experimental-features = nix-command flakes flake-self-attrs + + - name: Generate code + run: nix develop --command bash -c "flutter pub get && dart scripts/generate.dart && flutter pub run build_runner build" + + - name: Run end-to-end tests + run: nix run .#e2e-headless diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index cf64422..5cb03be 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -15,6 +15,7 @@ jobs: uses: actions/checkout@v6 with: submodules: recursive + fetch-depth: 0 - name: Lix GHA Installer Action uses: samueldr/lix-gha-installer-action@v2026-02-22 @@ -26,8 +27,30 @@ jobs: env: KEYSTORE_CONTENT: ${{ secrets.KEYSTORE_CONTENT }} + # The NDK's path ends up in the native libraries' build IDs, so put it where F-Droid has it. + # It's copied rather than linked, as clang finds its headers from its resolved location. + - name: Set up Android SDK + run: | + ndk=$(nix develop --command printenv ANDROID_NDK_HOME) + sudo mkdir -p /opt/android-sdk/ndk + sudo chown -R "$USER" /opt/android-sdk + for entry in "${ndk%/ndk/*}"/*; do + [[ $entry == */ndk ]] || ln -s "$entry" /opt/android-sdk/ + done + cp -rL "$ndk" /opt/android-sdk/ndk/ + - name: Build app - run: nix develop --command bash -c "flutter pub get && dart scripts/generate.dart && flutter pub run build_runner build && flutter build apk --target-platform android-arm64 --split-per-abi --dart-define=GIT_COMMIT=${{ github.sha }}" + run: | + export PUB_CACHE=$PWD/.pub-cache + export GOTOOLCHAIN=go$(sed -n -E 's/^toolchain go([0-9.]+)$/\1/p' gomuks/go.mod) + nix develop --command bash -c ' + set -e + export ANDROID_HOME=/opt/android-sdk ANDROID_SDK_ROOT=/opt/android-sdk ANDROID_NDK_HOME=/opt/android-sdk/ndk/${ANDROID_NDK_HOME##*/} + flutter pub get --enforce-lockfile + bash scripts/build_avif_native.sh + dart scripts/generate.dart + flutter pub run build_runner build + flutter build apk --target-platform android-arm64 --split-per-abi --dart-define=GIT_COMMIT=$GITHUB_SHA' env: KEYSTORE_PATH: ../../keystore.jks KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }} diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml index 28344ea..662cff6 100644 --- a/.github/workflows/ios.yml +++ b/.github/workflows/ios.yml @@ -19,7 +19,7 @@ jobs: - name: Set up Flutter uses: subosito/flutter-action@v2 with: - flutter-version: 3.47.4 + flutter-version-file: pubspec.yaml - name: Set up Go uses: actions/setup-go@v6 diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index b56f16f..5437318 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -19,7 +19,7 @@ jobs: - name: Set up Flutter uses: subosito/flutter-action@v2 with: - flutter-version: 3.47.4 + flutter-version-file: pubspec.yaml - name: Set up Go uses: actions/setup-go@v6 diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index db339b9..79032d5 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -19,7 +19,7 @@ jobs: - name: Set up Flutter uses: subosito/flutter-action@v2 with: - flutter-version: 3.47.4 + flutter-version-file: pubspec.yaml - name: Set up Go uses: actions/setup-go@v6 @@ -36,7 +36,7 @@ jobs: - name: Go build run: | cd gomuks/pkg/ffi - go build -tags goolm,sqlite_fts5 -o ../../../libgomuks.dll -buildmode=c-shared + go build -tags sqlite_fts5 -o ../../../libgomuks.dll -buildmode=c-shared - name: Build with Flutter run: | @@ -45,6 +45,17 @@ jobs: flutter pub run build_runner build flutter build windows --dart-define=GIT_COMMIT=${{ github.sha }} + # better_player plays videos with libmpv, but doesn't bundle it + - name: Download libmpv + shell: powershell + run: | + $archive = "$env:RUNNER_TEMP\mpv.7z" + Invoke-WebRequest "https://github.com/shinchiro/mpv-winbuild-cmake/releases/download/20261111/mpv-dev-x86_64-20261111-git-bcde6b93cc.7z" -OutFile $archive + if ((Get-FileHash $archive -Algorithm SHA256).Hash -ne "273c079b11ea5575822f972756f4c9a71149a5c10130353abeb8586738938452") { + throw "libmpv checksum mismatch" + } + 7z e $archive libmpv-2.dll -obuild/windows/x64/runner/Release + - name: Copy MinGW runtime DLLs shell: msys2 {0} run: | diff --git a/.gitmodules b/.gitmodules index 06dd51a..b300a1f 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,4 @@ [submodule "gomuks"] path = gomuks url = https://github.com/gomuks/gomuks + branch = quad/nexus diff --git a/.vscode/settings.json b/.vscode/settings.json index a5cac8a..2d6d7e3 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -12,6 +12,7 @@ "prefs", "recents", "unban", + "underride", "unifiedpush", "unredact", "webpush" diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index fa4a0a1..0f73f6a 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -12,6 +12,16 @@ You can run the following command to update the Gomuks submodule: git submodule update --remote ``` +## Releasing + +To make a release, run the following command with the new version, either `X.Y.Z` or a pre-release like `X.Y.Z-alpha1`: + +```sh +scripts/release.sh 1.2.0 +``` + +This sets the version in `pubspec.yaml` (along with the Android version code), the Windows installer, the AppStream metainfo and the README, then commits and tags it. Push it with the command it prints, then attach the artifacts from the tag's CI run to the release. + ## Code Style See [Effective Dart: Style](https://dart.dev/effective-dart/style) for general rules. There are some extra rules detailed below: diff --git a/README.md b/README.md index a0c111d..4fd61e4 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,9 @@ A simple and user-friendly Matrix client made with Flutter and a Gomuks backend. ## Screenshots -| Dark Mode | Light Mode | -| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------: | -| ![Screenshot of Nexus Client in dark mode, showing users talking, with a sidebar showing rooms and spaces, and another sidebar showing members](./assets/screenshotDark.png) | ![The same screenshot as above, but in light mode](./assets/screenshotLight.png) | +| Dark Mode | Light Mode | +| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------: | +| ![Screenshot of Nexus Client in dark mode, showing users talking, with a sidebar showing rooms and spaces, and another sidebar showing members](./assets/screenshots/desktop-dark.png) | ![The same screenshot as above, but in light mode](./assets/screenshots/desktop-light.png) | ## Try it out @@ -49,7 +49,7 @@ nexus = { This tracks the latest commit on `main`. To stay on a release instead, pin the input to its tag: ```nix -url = "git+https://git.federated.nexus/Nexus/nexus?ref=refs/tags/v1.0.0"; +url = "git+https://git.federated.nexus/Nexus/nexus?ref=refs/tags/v1.1.3"; ``` Then import the module and enable it in your NixOS configuration: @@ -75,7 +75,7 @@ This installs Nexus system-wide. With `enableNotifications`, it also installs KU #### Linux - On NixOS: Either use direnv and `direnv allow`, or `nix develop` -- On other distros: Install Flutter, Go, Git, Libclang, Libass, MPV, and Glibc. Do not use any Snap packages, they cause various compilation issues. +- On other distros: Install Flutter, Go, Git, Libclang, MPV, GStreamer (with its base, good and libav plugins), and Glibc. Do not use any Snap packages, they cause various compilation issues. #### Windows @@ -83,12 +83,11 @@ You will need: - Flutter - Git -- Libass -- MPV - Go - Visual Studio 2022 (Desktop development with C++) - [MSYS2/MinGW-w64 GCC](https://www.msys2.org/) (for CGO) - [LLVM/Clang + libclang](https://clang.llvm.org/get_started.html) (for `ffigen`) +- `libmpv-2.dll`, for playing videos, next to `nexus.exe` (CI uses a build from [mpv-winbuild-cmake](https://github.com/shinchiro/mpv-winbuild-cmake/releases)) On Windows, make sure these are available in your shell `PATH`: @@ -157,3 +156,6 @@ Join the [Nexus Client Matrix room](https://matrix.to/#/#nexus:federated.nexus) Thank you Hylke Bons (https://planetpeanut.studio) for making the amazing icon for Nexus! Thank you Tulir Asokan for making [Gomuks](https://github.com/gomuks/gomuks), and helping us integrate it into Nexus! +Thank you [Feline Build Services](https://felinebuildservices.org/) for providing CI for the Nexus Forgejo repo! + +The Nexus icon, including its source files in `assets/` and the platform app icons generated from them, is © Hylke Bons. The screenshots are © Henry Hiles. Both are licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 9c0d96c..35d2638 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -16,7 +16,7 @@ if (keystorePropertiesFile.exists()) { android { namespace = "nexus.federated.nexus" - compileSdk = 36 + compileSdk = 37 ndkVersion = flutter.ndkVersion compileOptions { @@ -57,9 +57,14 @@ android { } } + dependenciesInfo { + includeInApk = false + } + buildTypes { release { - signingConfig = signingConfigs.getByName("release") + // Unsigned without a keystore, e.g. for F-Droid, which signs it itself + signingConfig = signingConfigs.getByName("release").takeIf { it.storeFile != null } } debug { diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index b471fb4..7638ad6 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,5 +1,13 @@ - + + + + @@ -18,7 +26,7 @@ + + + + + + + (FLUTTER_VIEW_ID) ?: return - view.post { view.rootWindowInsets?.let(view::onApplyWindowInsets) } + view.post { view.requestApplyInsets() } } } diff --git a/android/gradle.properties b/android/gradle.properties index 1551eb0..440f99f 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -5,3 +5,5 @@ android.enableJetifier=true android.builtInKotlin=false # This newDsl flag was added automatically by Flutter migrator android.newDsl=false +# Leaves proprietary Google Play services out of the location plugin +location.playServices=false diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts index b59bc94..f07087d 100644 --- a/android/settings.gradle.kts +++ b/android/settings.gradle.kts @@ -23,4 +23,16 @@ plugins { id("org.jetbrains.kotlin.android") version "2.4.10" apply false } -include(":app") \ No newline at end of file +include(":app") + +// Flutter's plugin loader includes dev dependency plugins like integration_test as projects even in +// release builds (where they're never linked in). integration_test lives in the Flutter SDK, which +// is read-only under Nix, and Gradle 9+ refuses to configure a project whose directory isn't writable. +findProject(":integration_test")?.let { project -> + if (!project.projectDir.canWrite()) { + val copy = file("../build/integration_test_android") + copy.deleteRecursively() + project.projectDir.copyRecursively(copy) + project.projectDir = copy + } +} \ No newline at end of file diff --git a/assets/bundled/federated_nexus.svg b/assets/bundled/federated_nexus.svg new file mode 100644 index 0000000..0effd9a --- /dev/null +++ b/assets/bundled/federated_nexus.svg @@ -0,0 +1,150 @@ + + + + diff --git a/assets/bundled/matrix.svg b/assets/bundled/matrix.svg new file mode 100644 index 0000000..bfe705e --- /dev/null +++ b/assets/bundled/matrix.svg @@ -0,0 +1,11 @@ + + + + + diff --git a/assets/screenshotDark.png b/assets/screenshotDark.png deleted file mode 100644 index 48be6e5..0000000 Binary files a/assets/screenshotDark.png and /dev/null differ diff --git a/assets/screenshotLight.png b/assets/screenshotLight.png deleted file mode 100644 index 5aae7a0..0000000 Binary files a/assets/screenshotLight.png and /dev/null differ diff --git a/assets/screenshots/desktop-dark.png b/assets/screenshots/desktop-dark.png new file mode 100644 index 0000000..e9753bd Binary files /dev/null and b/assets/screenshots/desktop-dark.png differ diff --git a/assets/screenshots/desktop-light.png b/assets/screenshots/desktop-light.png new file mode 100644 index 0000000..2d5c876 Binary files /dev/null and b/assets/screenshots/desktop-light.png differ diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt new file mode 100644 index 0000000..e310d29 --- /dev/null +++ b/fastlane/metadata/android/en-US/full_description.txt @@ -0,0 +1,10 @@ +

Nexus is a simple and user-friendly client for Matrix, the open and decentralized chat network. It's made with Flutter, with gomuks handling the Matrix side.

+ +

Features include:

+
    +
  • Spaces, threads, replies and reactions
  • +
  • End-to-end encryption, with verification and recovery keys
  • +
  • Polls, location sharing, and custom emoji and sticker packs
  • +
  • Multiple accounts
  • +
  • Notifications through UnifiedPush, or Firebase Cloud Messaging
  • +
diff --git a/fastlane/metadata/android/en-US/images/icon.png b/fastlane/metadata/android/en-US/images/icon.png new file mode 100644 index 0000000..6b1b81c Binary files /dev/null and b/fastlane/metadata/android/en-US/images/icon.png differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png new file mode 100644 index 0000000..c6688a0 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png new file mode 100644 index 0000000..1d4ff07 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png new file mode 100644 index 0000000..f969bf1 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png new file mode 100644 index 0000000..82915b6 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png differ diff --git a/fastlane/metadata/android/en-US/short_description.txt b/fastlane/metadata/android/en-US/short_description.txt new file mode 100644 index 0000000..570387a --- /dev/null +++ b/fastlane/metadata/android/en-US/short_description.txt @@ -0,0 +1 @@ +A simple and user-friendly Matrix client diff --git a/fastlane/metadata/android/en-US/title.txt b/fastlane/metadata/android/en-US/title.txt new file mode 100644 index 0000000..755a6d7 --- /dev/null +++ b/fastlane/metadata/android/en-US/title.txt @@ -0,0 +1 @@ +Nexus diff --git a/flake.lock b/flake.lock index 066f38b..b6443af 100644 --- a/flake.lock +++ b/flake.lock @@ -1,15 +1,130 @@ { "nodes": { + "advisory-db": { + "flake": false, + "locked": { + "lastModified": 1793979272, + "narHash": "sha256-oUcBtPbtS7PlEMuSrgTAN4wv49cXYbwKbQqhH2pah5w=", + "owner": "rustsec", + "repo": "advisory-db", + "rev": "309392b18f6b17022f82c701f300433126901068", + "type": "github" + }, + "original": { + "owner": "rustsec", + "repo": "advisory-db", + "type": "github" + } + }, + "continuwuity": { + "inputs": { + "advisory-db": "advisory-db", + "crane": "crane", + "fenix": "fenix", + "flake-compat": "flake-compat", + "flake-parts": "flake-parts", + "nixpkgs": [ + "nixpkgs" + ], + "treefmt-nix": "treefmt-nix" + }, + "locked": { + "lastModified": 1794436491, + "narHash": "sha256-1Gbe5ys68lljaWtwn8Z4RhkUnWDfw8AaHQJDKVzzmVA=", + "ref": "ea3beb628a3cab6fbc4142b725c9edb043846eb6", + "rev": "ea3beb628a3cab6fbc4142b725c9edb043846eb6", + "revCount": 8146, + "type": "git", + "url": "https://forgejo.ellis.link/Continuwuation/Continuwuity" + }, + "original": { + "ref": "ea3beb628a3cab6fbc4142b725c9edb043846eb6", + "type": "git", + "url": "https://forgejo.ellis.link/Continuwuation/Continuwuity" + } + }, + "crane": { + "locked": { + "lastModified": 1793836618, + "narHash": "sha256-TREenflwEjxOSq292FYwbc3kEm7TDRtXCZRNWEdjBmg=", + "owner": "ipetkov", + "repo": "crane", + "rev": "79fd63528501446749c09f08cad486a58c7d173e", + "type": "github" + }, + "original": { + "owner": "ipetkov", + "repo": "crane", + "type": "github" + } + }, + "fenix": { + "inputs": { + "nixpkgs": [ + "continuwuity", + "nixpkgs" + ], + "rust-analyzer-src": "rust-analyzer-src" + }, + "locked": { + "lastModified": 1794142885, + "narHash": "sha256-xWFSr7q8IerDAVRk4W7/CgTmi05hMy2qjZ0z3VYpOVk=", + "owner": "nix-community", + "repo": "fenix", + "rev": "f7d416b5073152c7f2e4de1a28d1a4330dd30a26", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "fenix", + "type": "github" + } + }, + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1767039857, + "narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab", + "type": "github" + }, + "original": { + "owner": "edolstra", + "ref": "master", + "repo": "flake-compat", + "type": "github" + } + }, "flake-parts": { "inputs": { "nixpkgs-lib": "nixpkgs-lib" }, "locked": { - "lastModified": 1788450739, - "narHash": "sha256-glZLQlzIn1fXH6PazR2iUmTo7kzzyYSshrWhLS9TqCU=", + "lastModified": 1793576659, + "narHash": "sha256-V1h85lUaJBQoHFrB2vpXZOE0Ju1MYSnIpsehoVZYlDo=", "owner": "hercules-ci", "repo": "flake-parts", - "rev": "31729ca8cbdb4fa927b34e5f4353e6a83f39e993", + "rev": "ea2630b7470978622c7689a1ff75d2b389175399", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "flake-parts_2": { + "inputs": { + "nixpkgs-lib": "nixpkgs-lib_2" + }, + "locked": { + "lastModified": 1793576659, + "narHash": "sha256-V1h85lUaJBQoHFrB2vpXZOE0Ju1MYSnIpsehoVZYlDo=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "ea2630b7470978622c7689a1ff75d2b389175399", "type": "github" }, "original": { @@ -39,7 +154,9 @@ "nix2flatpak": { "inputs": { "flake-utils": "flake-utils", - "nixpkgs": "nixpkgs" + "nixpkgs": [ + "nixpkgs" + ] }, "locked": { "lastModified": 1791751882, @@ -57,15 +174,15 @@ }, "nixpkgs": { "locked": { - "lastModified": 1773389992, - "narHash": "sha256-wvfdLLWJ2I9oEpDd9PfMA8osfIZicoQ5MT1jIwNs9Tk=", - "owner": "NixOS", + "lastModified": 1793540411, + "narHash": "sha256-fiPJ88izTVucjeo2EQ3jk4aWmLg03I1D4vxnX2QjEgE=", + "owner": "nixos", "repo": "nixpkgs", - "rev": "c06b4ae3d6599a672a6210b7021d699c351eebda", + "rev": "0bb2eedc20e4739f29e8045034f2828ad7054f8f", "type": "github" }, "original": { - "owner": "NixOS", + "owner": "nixos", "ref": "nixos-unstable", "repo": "nixpkgs", "type": "github" @@ -73,11 +190,11 @@ }, "nixpkgs-lib": { "locked": { - "lastModified": 1788057806, - "narHash": "sha256-DTQSMxzDWmT0zhguthvegnVkn7CFqGCv4IHCzk5ZUpM=", + "lastModified": 1793504054, + "narHash": "sha256-ThkfL3D/FhCiZFc9+3BtxwuMmpuK+/bGtXCSo1+yVew=", "owner": "nix-community", "repo": "nixpkgs.lib", - "rev": "596e2e3940e09b2abbeb03f75fa1828c57fcd72c", + "rev": "7851ba61fd862b277cb6a9cef37394bc18bb94e4", "type": "github" }, "original": { @@ -86,27 +203,44 @@ "type": "github" } }, - "nixpkgs_2": { + "nixpkgs-lib_2": { "locked": { - "lastModified": 1790689126, - "narHash": "sha256-ilerN1WLSvF+HMjziC/Wv99J5y02maDH+6hZPwsORKg=", - "owner": "nixos", - "repo": "nixpkgs", - "rev": "b4fd65b198c599cbe814fcb9f42d25d021595ec9", + "lastModified": 1793504054, + "narHash": "sha256-ThkfL3D/FhCiZFc9+3BtxwuMmpuK+/bGtXCSo1+yVew=", + "owner": "nix-community", + "repo": "nixpkgs.lib", + "rev": "7851ba61fd862b277cb6a9cef37394bc18bb94e4", "type": "github" }, "original": { - "owner": "nixos", - "ref": "nixos-unstable", - "repo": "nixpkgs", + "owner": "nix-community", + "repo": "nixpkgs.lib", "type": "github" } }, "root": { "inputs": { - "flake-parts": "flake-parts", + "continuwuity": "continuwuity", + "flake-parts": "flake-parts_2", "nix2flatpak": "nix2flatpak", - "nixpkgs": "nixpkgs_2" + "nixpkgs": "nixpkgs" + } + }, + "rust-analyzer-src": { + "flake": false, + "locked": { + "lastModified": 1794096810, + "narHash": "sha256-dWC+YtMX+cwH3e9ndiFB77ijTsKtO5I2OxfcvUY4j3k=", + "owner": "rust-lang", + "repo": "rust-analyzer", + "rev": "03ae6be57aa063bb373f69eead3b8e15168a45d2", + "type": "github" + }, + "original": { + "owner": "rust-lang", + "ref": "nightly", + "repo": "rust-analyzer", + "type": "github" } }, "systems": { @@ -123,6 +257,27 @@ "repo": "default", "type": "github" } + }, + "treefmt-nix": { + "inputs": { + "nixpkgs": [ + "continuwuity", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1791885023, + "narHash": "sha256-C3alQ2MEt0zVrUSho5NUDo3jmhbff72++bfwoqT9Omo=", + "owner": "numtide", + "repo": "treefmt-nix", + "rev": "0d6d739a833ba9a9c93034862e4a7b061a062a1c", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "treefmt-nix", + "type": "github" + } } }, "root": "root", diff --git a/flake.nix b/flake.nix index e4cae8a..2ee3373 100644 --- a/flake.nix +++ b/flake.nix @@ -5,7 +5,15 @@ self.submodules = true; nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; flake-parts.url = "github:hercules-ci/flake-parts"; - nix2flatpak.url = "github:neobrain/nix2flatpak"; + nix2flatpak = { + url = "github:neobrain/nix2flatpak"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + # TEMPORARY: the e2e tests against Continuwuity from the forge, till there's a new full release in nixpkgs + continuwuity = { + url = "git+https://forgejo.ellis.link/Continuwuation/Continuwuity?ref=ea3beb628a3cab6fbc4142b725c9edb043846eb6"; + inputs.nixpkgs.follows = "nixpkgs"; + }; }; outputs = diff --git a/gomuks b/gomuks index 53cae0e..2a76e97 160000 --- a/gomuks +++ b/gomuks @@ -1 +1 @@ -Subproject commit 53cae0e0334aef5ac376ea84f19ba1cff8a92310 +Subproject commit 2a76e97eb3e955ec14775ce4027ed446865ed7fa diff --git a/hook/build.dart b/hook/build.dart index 8726642..2181e8a 100644 --- a/hook/build.dart +++ b/hook/build.dart @@ -64,10 +64,14 @@ Future main(List args) => build(args, (input, output) async { final targetNdkApi = codeConfig.android.targetNdkApi; + // Treats empty variables as unset, since e.g. F-Droid sets ANDROID_NDK_HOME to "" without an NDK + String? env(String name) => switch (Platform.environment[name]) { + "" => null, + final value => value, + }; + Future findNdkFromSdk() async { - final androidHome = - Platform.environment["ANDROID_HOME"] ?? - Platform.environment["ANDROID_SDK_ROOT"]; + final androidHome = env("ANDROID_HOME") ?? env("ANDROID_SDK_ROOT"); if (androidHome == null) return null; final ndkDir = Directory(join(androidHome, "ndk")); @@ -78,9 +82,9 @@ Future main(List args) => build(args, (input, output) async { } final ndkHome = - Platform.environment["ANDROID_NDK_HOME"] ?? - Platform.environment["ANDROID_NDK_ROOT"] ?? - Platform.environment["NDK_HOME"] ?? + env("ANDROID_NDK_HOME") ?? + env("ANDROID_NDK_ROOT") ?? + env("NDK_HOME") ?? await findNdkFromSdk(); if (ndkHome == null) { @@ -91,8 +95,7 @@ Future main(List args) => build(args, (input, output) async { // TODO: Someone please give me a way to detect host architecture so I can change this final hostTag = - Platform.environment["ANDROID_HOST_TAG"] ?? - "${Platform.operatingSystem}-x86_64"; + env("ANDROID_HOST_TAG") ?? "${Platform.operatingSystem}-x86_64"; final ccTriple = switch (targetArch) { Architecture.arm64 => "aarch64-linux-android", Architecture.arm => "armv7a-linux-androideabi", @@ -120,7 +123,6 @@ Future main(List args) => build(args, (input, output) async { final tags = [ "sqlite_fts5", - "goolm", // goheif/dav1d is not supported on Android or iOS, would need to be fixed upstream "noheic", ].join(","); diff --git a/integration_test/helpers/fakes.dart b/integration_test/helpers/fakes.dart new file mode 100644 index 0000000..050eb99 --- /dev/null +++ b/integration_test/helpers/fakes.dart @@ -0,0 +1,47 @@ +import "dart:async"; + +import "package:app_links_platform_interface/app_links_platform_interface.dart"; +import "package:url_launcher_platform_interface/link.dart"; +import "package:url_launcher_platform_interface/url_launcher_platform_interface.dart"; + +/// Delivers links to the app as if the OS had opened them. +class FakeAppLinks extends AppLinksPlatform { + final _links = StreamController.broadcast(); + + void open(Uri uri) => _links.add(uri); + + @override + Future getInitialLink() async => null; + + @override + Future getInitialLinkString() async => null; + + @override + Future getLatestLink() async => null; + + @override + Future getLatestLinkString() async => null; + + @override + Stream get uriLinkStream => _links.stream; + + @override + Stream get stringLinkStream => + _links.stream.map((uri) => uri.toString()); +} + +/// Hands launched URLs to [onLaunch] instead of opening a browser. +class FakeUrlLauncher(final void Function(Uri url) onLaunch) + extends UrlLauncherPlatform { + @override + LinkDelegate? get linkDelegate => null; + + @override + Future canLaunch(String url) async => true; + + @override + Future launchUrl(String url, LaunchOptions options) async { + onLaunch(.parse(url)); + return true; + } +} diff --git a/integration_test/helpers/matrix_user.dart b/integration_test/helpers/matrix_user.dart new file mode 100644 index 0000000..bd2692c --- /dev/null +++ b/integration_test/helpers/matrix_user.dart @@ -0,0 +1,174 @@ +import "dart:convert"; + +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:http/http.dart" as http; + +const homeserver = String.fromEnvironment("NEXUS_E2E_HOMESERVER"); + +/// A user acting over the client-server API directly, as a control for the +/// tests: it doesn't go through gomuks or any other Nexus code, so it sets +/// things up and checks the server's side independently of what's being +/// tested. That includes Nexus' models, so the JSON it sends is written out +/// here rather than built the way Nexus builds it. +class const MatrixUser(final String userId, final String accessToken) { + static Future login(String username, String password) async { + final json = await request( + "POST", + "/_matrix/client/v3/login", + body: { + "type": "m.login.password", + "identifier": {"type": "m.id.user", "user": username}, + "password": password, + }, + ); + return MatrixUser(json["user_id"], json["access_token"]); + } + + static Future> request( + String method, + String path, { + String? accessToken, + Object? body, + }) async { + final httpRequest = + http.Request(method, Uri.parse(homeserver).resolve(path)) + ..headers.addAll({ + "Content-Type": "application/json", + if (accessToken != null) "Authorization": "Bearer $accessToken", + }); + if (method != "GET") httpRequest.body = jsonEncode(body ?? {}); + final response = await http.Response.fromStream(await httpRequest.send()); + + if (response.statusCode == 429) { + final retryAfter = jsonDecode(response.body)["retry_after_ms"] ?? 1000; + await Future.delayed(.new(milliseconds: retryAfter)); + return request(method, path, accessToken: accessToken, body: body); + } + if (response.statusCode >= 300) { + throw StateError( + "$method $path failed with ${response.statusCode}: ${response.body}", + ); + } + return jsonDecode(response.body); + } + + Future createRoom(String name) async => (await request( + "POST", + "/_matrix/client/v3/createRoom", + accessToken: accessToken, + body: {"name": name, "preset": "private_chat"}, + ))["room_id"]; + + Future invite(String roomId, String userId) => request( + "POST", + "/_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/invite", + accessToken: accessToken, + body: {"user_id": userId}, + ); + + Future join(String roomId) => request( + "POST", + "/_matrix/client/v3/join/${Uri.encodeComponent(roomId)}", + accessToken: accessToken, + ); + + Future logout() => + request("POST", "/_matrix/client/v3/logout", accessToken: accessToken); + + Future sendEvent( + String roomId, + String type, + Map content, + ) async => (await request( + "PUT", + "/_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/send/$type/" + "${DateTime.now().microsecondsSinceEpoch}", + accessToken: accessToken, + body: content, + ))["event_id"]; + + /// Sends a text message. With [threadRoot] it's a reply in that thread, and + /// otherwise with [replyTo] it's a reply to that event. + Future send( + String roomId, + String body, { + String? threadRoot, + String? replyTo, + }) => sendEvent(roomId, "m.room.message", { + "msgtype": "m.text", + "body": body, + "m.relates_to": ?switch ((threadRoot, replyTo)) { + (final threadRoot?, _) => { + "rel_type": "m.thread", + "event_id": threadRoot, + "is_falling_back": true, + "m.in_reply_to": {"event_id": threadRoot}, + }, + (null, final replyTo?) => { + "m.in_reply_to": {"event_id": replyTo}, + }, + (null, null) => null, + }, + }); + + /// Sends [rootBody], then [replies] in a thread from it, oldest first. + Future<({String rootId, IList replyIds})> sendThread( + String roomId, + String rootBody, + IList replies, + ) async { + final rootId = await send(roomId, rootBody); + // One at a time, so they're in order (oops earlier tests weren't reproducable) + final replyIds = await Stream.fromIterable(replies) + .asyncMap((body) => send(roomId, body, threadRoot: rootId)) + .toList(); + return (rootId: rootId, replyIds: replyIds.toIList()); + } + + /// Edits the text message [eventId] to say [body]. + Future edit(String roomId, String eventId, String body) => + sendEvent(roomId, "m.room.message", { + "msgtype": "m.text", + "body": "* $body", + "m.new_content": {"msgtype": "m.text", "body": body}, + "m.relates_to": {"rel_type": "m.replace", "event_id": eventId}, + }); + + Future redact(String roomId, String eventId) => request( + "PUT", + "/_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/redact/" + "${Uri.encodeComponent(eventId)}/${DateTime.now().microsecondsSinceEpoch}", + accessToken: accessToken, + ); + + /// The bodies of the replies in the thread from [threadRoot], oldest first. + Future> threadReplies(String roomId, String threadRoot) async { + final json = await request( + "GET", + "/_matrix/client/v1/rooms/${Uri.encodeComponent(roomId)}/relations/" + "${Uri.encodeComponent(threadRoot)}/m.thread?dir=f&limit=100", + accessToken: accessToken, + ); + return (json["chunk"] as List) + .map((event) => event["content"]["body"] as String) + .toIList(); + } + + Future> threadRepliesIncluding( + String roomId, + String threadRoot, + String body, { + int attempts = 20, + }) async { + final replies = await threadReplies(roomId, threadRoot); + if (replies.contains(body) || attempts <= 1) return replies; + + await Future.delayed(const .new(milliseconds: 500)); + return threadRepliesIncluding( + roomId, + threadRoot, + body, + attempts: attempts - 1, + ); + } +} diff --git a/integration_test/helpers/oauth.dart b/integration_test/helpers/oauth.dart new file mode 100644 index 0000000..be652d7 --- /dev/null +++ b/integration_test/helpers/oauth.dart @@ -0,0 +1,68 @@ +import "package:http/http.dart" as http; + +import "fakes.dart"; + +/// Fake platforms that do the browser's part of OAuth on Continuwuity, logging +/// in as [username], then hand the redirect back to Nexus. +class OAuthFakes(final String username, final String password) { + final links = FakeAppLinks(); + late final launcher = FakeUrlLauncher(onLaunch); + + Future onLaunch(Uri url) async { + if (!url.queryParameters.containsKey("code_challenge")) return; + + final redirect = await authorize(url); + // Nexus listens for the redirect after the launch returns + await Future.delayed(const .new(milliseconds: 500)); + links.open(redirect); + } + + /// Logs in on [authorizationUrl], then confirms the grant, returning the URI + /// Continuwuity redirects back to the app with. + Future authorize(Uri authorizationUrl) async { + final client = http.Client(); + String? cookie; + + Future followRedirect( + String method, + Uri url, [ + Map? form, + ]) async { + final request = http.Request(method, url) + ..followRedirects = false + ..headers.addAll({ + // Continuwuity only accepts its forms from top-level navigations + "Sec-Fetch-Site": "same-origin", + "Sec-Fetch-Mode": "navigate", + "Sec-Fetch-Dest": "document", + "Cookie": ?cookie, + }); + if (form != null) request.bodyFields = form; + + final response = await http.Response.fromStream( + await client.send(request), + ); + if (response.headers["set-cookie"] case final setCookie?) { + cookie = setCookie.split(";").first; + } + + return switch ((response.statusCode, response.headers["location"])) { + (302 || 303 || 307, final location?) => url.resolve(location), + (final status, _) => throw StateError( + "Expected $method $url to redirect, got $status: ${response.body}", + ), + }; + } + + try { + final loginUrl = await followRedirect("GET", authorizationUrl); + final grantUrl = await followRedirect("POST", loginUrl, { + "identifier": username, + "password": password, + }); + return await followRedirect("POST", grantUrl, {"stage": "confirm"}); + } finally { + client.close(); + } + } +} diff --git a/integration_test/helpers/pump_until.dart b/integration_test/helpers/pump_until.dart new file mode 100644 index 0000000..95c4944 --- /dev/null +++ b/integration_test/helpers/pump_until.dart @@ -0,0 +1,70 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_test/flutter_test.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; + +// Custom because `patrol_finder` gives me jQuery vibes, and that's Not GoodTM +extension PumpUntil on WidgetTester { + /// Pumps until [finder] finds something, failing if it doesn't within 30 + /// seconds, or if the app shows an error. + Future pumpUntil(Finder finder) async { + const timeout = Duration(seconds: 30); + + String textsIn(Finder finder) => + widgetList( + find.descendant( + of: finder, + matching: find.byWidgetPredicate( + (widget) => widget is Text || widget is SelectableText, + ), + ), + ) + .map( + (widget) => switch (widget) { + Text(:final data) || SelectableText(:final data) => data, + _ => null, + }, + ) + .nonNulls + .join("\n"); + + final stopwatch = Stopwatch()..start(); + while (stopwatch.elapsed < timeout) { + await pump(const .new(milliseconds: 100)); + + if (finder.evaluate().isNotEmpty) return; + + final errorDialog = find.byType(ErrorDialog); + if (errorDialog.evaluate().isNotEmpty) { + fail( + "The app showed an error while waiting for $finder:\n" + "${textsIn(errorDialog)}", + ); + } + } + + final snackBar = find.byType(SnackBar); + final shown = find + .byType(RichText) + .hitTestable() + .evaluate() + .map((element) => (element.widget as RichText).text.toPlainText()) + .where((text) => text.trim().isNotEmpty) + .toIList() + .removeDuplicates() + .join(" | "); + fail( + "Timed out after $timeout waiting for $finder" + "${snackBar.evaluate().isEmpty ? "" : "\nSnack bar: ${textsIn(snackBar)}"}" + "\nShown: $shown", + ); + } + + /// Taps [finder] once it can be tapped, like after animating in. + Future tapWhenShown(Finder finder) async { + final tappable = finder.hitTestable(); + await pumpUntil(tappable); + await tap(tappable.first); + await pump(); + } +} diff --git a/integration_test/helpers/test_app.dart b/integration_test/helpers/test_app.dart new file mode 100644 index 0000000..27e3027 --- /dev/null +++ b/integration_test/helpers/test_app.dart @@ -0,0 +1,113 @@ +import "package:app_links_platform_interface/app_links_platform_interface.dart"; +import "package:flutter_test/flutter_test.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/active_account.dart"; +import "package:nexus/main.dart" as nexus; +import "package:nexus/widgets/account_scope.dart"; +import "package:nexus/widgets/pages/chat.dart"; +import "package:nexus/widgets/pages/select_server.dart"; +import "package:nexus/widgets/pages/verify.dart"; +import "package:nexus/widgets/room_chat/room_chat.dart"; +import "package:url_launcher_platform_interface/url_launcher_platform_interface.dart"; + +import "matrix_user.dart"; +import "oauth.dart"; +import "pump_until.dart"; + +/// Nexus, run as the account [username], which is set up through the UI the +/// first time it's opened. +class TestApp(final String username, final String password) { + late final fakes = OAuthFakes(username, password); + + void setUp() { + nexus.isInBackground = false; + AppLinksPlatform.instance = fakes.links; + UrlLauncherPlatform.instance = fakes.launcher; + + // A tap that misses would otherwise only warn + WidgetController.hitTestWarningShouldBeFatal = true; + } + + Future join(MatrixUser inviter, String roomId) async { + final user = await MatrixUser.login(username, password); + await inviter.invite(roomId, user.userId); + await user.join(roomId); + await user.logout(); + } + + /// Starts Nexus like [open], then opens [roomName]. + Future openRoom(WidgetTester tester, String roomName) async { + await open(tester); + await selectRoom(tester, roomName); + } + + /// Taps [roomName] in the room list, opening the drawer it's in first when + /// the window is narrow enough for the mobile layout. + Future selectRoom(WidgetTester tester, String roomName) async { + // Shown once the first sync is done, as is the drawer button on mobile + await tester.pumpUntil(find.byType(RoomChat)); + + final drawerButton = find + .byTooltip(const DefaultMaterialLocalizations().openAppDrawerTooltip) + .hitTestable(); + if (drawerButton.evaluate().isNotEmpty) await tester.tap(drawerButton); + await tester.tapWhenShown(find.text(roomName)); + } + + /// Starts Nexus, logged in and verified, logging in and setting up + /// encryption through the UI first if it isn't. + Future open(WidgetTester tester) async { + await tester.pumpWidget( + AccountScope( + initialAccountId: await ActiveAccountController.stored(), + retry: (_, _) => null, + child: nexus.App(), + ), + ); + + await tester.pumpUntil( + find.byWidgetPredicate( + (widget) => + widget is SelectServerPage || + widget is VerifyPage || + widget is ChatPage, + ), + ); + if (find.byType(SelectServerPage).evaluate().isNotEmpty) { + await logIn(tester); + } + if (find.byType(VerifyPage).evaluate().isNotEmpty) { + await setUpEncryption(tester); + } + await tester.pumpUntil(find.byType(ChatPage)); + } + + Future logIn(WidgetTester tester) async { + final homeserverField = find.widgetWithText(TextField, "Homeserver URL"); + await tester.pumpUntil(homeserverField); + await tester.enterText(homeserverField, homeserver); + await tester.testTextInput.receiveAction(.done); + + // Discovery only uses HTTPS, which the test homeserver doesn't serve, so + // Nexus offers to log in with the URL as typed + await tester.tapWhenShown(find.text("Attempt log in anyways")); + + // Nexus opens the authorization page, which fakes authorizes + await tester.pumpUntil( + find.byWidgetPredicate( + (widget) => widget is VerifyPage || widget is ChatPage, + ), + ); + } + + /// Sets up encryption from the verify page, for an account without it. + Future setUpEncryption(WidgetTester tester) async { + await tester.pumpUntil(find.text("Set Up Encryption")); + await tester.tapWhenShown(find.widgetWithText(TextButton, "Set Up")); + + await tester.tapWhenShown(find.text("I've saved my recovery key")); + await tester.tapWhenShown(find.widgetWithText(TextButton, "Set Up")); + + await tester.tapWhenShown(find.widgetWithText(TextButton, "Done")); + } +} diff --git a/integration_test/helpers/threads.dart b/integration_test/helpers/threads.dart new file mode 100644 index 0000000..d2eee0d --- /dev/null +++ b/integration_test/helpers/threads.dart @@ -0,0 +1,34 @@ +import "package:flutter_test/flutter_test.dart"; +import "package:material_ui/material_ui.dart"; + +import "pump_until.dart"; + +extension MessageFinders on CommonFinders { + Finder message(String body) => textContaining(body, findRichText: true); +} + +extension RelativeFinders on Finder { + Finder inside(Type type) => + find.descendant(of: find.byType(type), matching: this); + + /// The [InkWell] ancestor around what this finds + Finder get inkWell => find.ancestor(of: this, matching: find.byType(InkWell)); +} + +extension ReplyCounts on WidgetTester { + /// Waits for a reply count in widgets of [type], then checks it, so a wrong + /// count fails straight away with what was shown. + Future expectReplyCount(Type type, int expected) async { + final repliesLabel = RegExp(r"^(\d+) repl(?:y|ies)$"); + final labels = find.textContaining(repliesLabel).inside(type); + await pumpUntil(labels); + + final shown = widgetList(labels) + .map((label) => label.data) + .nonNulls + .map(repliesLabel.firstMatch) + .nonNulls + .map((match) => int.parse(match[1]!)); + expect(shown, everyElement(expected), reason: "Reply count in $type"); + } +} diff --git a/integration_test/links_test.dart b/integration_test/links_test.dart new file mode 100644 index 0000000..4137fff --- /dev/null +++ b/integration_test/links_test.dart @@ -0,0 +1,56 @@ +import "package:flutter_test/flutter_test.dart"; +import "package:integration_test/integration_test.dart"; +import "package:nexus/widgets/room_chat/room_chat.dart"; +import "package:nexus/widgets/rooms/room_summary_sheet.dart"; +import "package:nexus/widgets/users/user_bottom_sheet.dart"; + +import "helpers/matrix_user.dart"; +import "helpers/test_app.dart"; +import "helpers/pump_until.dart"; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + final app = TestApp("dave", "davepass"); + setUpAll(app.setUp); + final run = DateTime.now().millisecondsSinceEpoch; + Future bob() => MatrixUser.login("bob", "bobpass"); + + Future openLink(WidgetTester tester, String link) async { + await app.open(tester); + app.fakes.links.open(.parse(link)); + } + + group("a link opened by the OS", () { + testWidgets("to a user opens their popover", (tester) async { + await openLink(tester, "matrix:u/bob:localhost"); + + await tester.pumpUntil(find.byType(UserBottomSheet)); + }); + + testWidgets("to a joined room opens it", (tester) async { + final inviter = await bob(); + final roomId = await inviter.createRoom("Linked $run"); + // Joined before Nexus starts, so the room is there once it syncs + await app.join(inviter, roomId); + + await openLink(tester, "matrix:roomid/${roomId.substring(1)}"); + + await tester.pumpUntil( + find.byWidgetPredicate( + (widget) => widget is RoomChat && widget.roomId == roomId, + ), + ); + }); + + testWidgets("to a room that isn't joined shows its summary", ( + tester, + ) async { + final roomId = await (await bob()).createRoom("Unjoined $run"); + + await openLink(tester, "matrix:roomid/${roomId.substring(1)}"); + + await tester.pumpUntil(find.byType(RoomSummarySheet)); + }); + }); +} diff --git a/integration_test/long_thread_test.dart b/integration_test/long_thread_test.dart new file mode 100644 index 0000000..49e450a --- /dev/null +++ b/integration_test/long_thread_test.dart @@ -0,0 +1,115 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_test/flutter_test.dart"; +import "package:integration_test/integration_test.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/widgets/room_chat/room_chat.dart"; +import "package:nexus/widgets/threads/thread_drawer.dart"; +import "package:nexus/widgets/threads/threads_drawer.dart"; + +import "helpers/matrix_user.dart"; +import "helpers/test_app.dart"; +import "helpers/pump_until.dart"; +import "helpers/threads.dart"; + +/// A thread longer than gomuks' initial sync, which gets the latest 100 +/// events, so its start only reaches Nexus through `/relations`. That needs +/// an account whose first sync is after the thread exists, so it's not the one +/// other tests use. +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + final app = TestApp("carol", "carolpass"); + setUpAll(app.setUp); + final run = DateTime.now().millisecondsSinceEpoch; + final roomName = "Long thread $run"; + final rootBody = "Long thread root $run"; + const replyCount = 120; + // Among the first replies, which aren't synced + const jumpedTo = 10; + // Padded, so no reply's text contains another's (oops those failures were confusing when I didn't do that) + String reply(int number) => "Long reply ${number.toString().padLeft(3, "0")}"; + + setUpAll(() async { + final bob = await MatrixUser.login("bob", "bobpass"); + final roomId = await bob.createRoom(roomName); + await app.join(bob, roomId); + + final thread = await bob.sendThread( + roomId, + rootBody, + Iterable.generate(replyCount, (index) => reply(index + 1)).toIList(), + ); + // In the room's timeline, so there's something to jump from, to a reply + // with others on both sides that aren't synced either + await bob.send( + roomId, + "Quoting an old reply", + replyTo: thread.replyIds[jumpedTo - 1], + ); + }); + + /// Drags the open thread by [offset] until [finder] is shown in it, loading + /// more replies as it goes, for up to 30 seconds. + Future scrollThread( + WidgetTester tester, + Finder finder, + Offset offset, + ) => tester.dragUntilVisible( + finder.inside(ThreadDrawer), + find.byType(CustomScrollView).inside(ThreadDrawer).first, + offset, + maxIteration: 60, + duration: const .new(milliseconds: 500), + ); + + Future openThreadsDrawer(WidgetTester tester) async { + await app.openRoom(tester, roomName); + await tester.tapWhenShown(find.byTooltip("Open threads")); + await tester.pumpUntil(find.message(rootBody).inside(ThreadsDrawer)); + } + + testWidgets("lists the thread with all of its replies", (tester) async { + await openThreadsDrawer(tester); + + await tester.expectReplyCount(ThreadsDrawer, replyCount); + }); + + // Before the whole thread is loaded by scrolling through it below + testWidgets("jumps to a reply in the thread that isn't loaded", ( + tester, + ) async { + await app.openRoom(tester, roomName); + + // The quote of the reply is fetched on its own, then tapped + await tester.tapWhenShown( + find.message(reply(jumpedTo)).inside(RoomChat).inkWell, + ); + + // The thread opens around the reply, with replies on both sides + await tester.pumpUntil( + find.message(reply(jumpedTo)).inside(ThreadDrawer).hitTestable(), + ); + await tester.pumpUntil( + find.message(reply(jumpedTo - 1)).inside(ThreadDrawer), + ); + await tester.pumpUntil( + find.message(reply(jumpedTo + 1)).inside(ThreadDrawer), + ); + + await scrollThread(tester, find.message(reply(60)), const .new(0, -400)); + }); + + testWidgets("loads older replies back to the root", (tester) async { + await openThreadsDrawer(tester); + await tester.tapWhenShown( + find.message(rootBody).inside(ThreadsDrawer).inkWell, + ); + await tester.pumpUntil( + find.message(reply(replyCount)).inside(ThreadDrawer), + ); + + // Dragging down scrolls up the reversed timeline, to older replies + await scrollThread(tester, find.message(rootBody), const .new(0, 400)); + expect(find.message(reply(1)).inside(ThreadDrawer), findsWidgets); + }); +} diff --git a/integration_test/screenshots/avatars/SOURCES.md b/integration_test/screenshots/avatars/SOURCES.md new file mode 100644 index 0000000..e6094db --- /dev/null +++ b/integration_test/screenshots/avatars/SOURCES.md @@ -0,0 +1,22 @@ +# Screenshot avatars + +Avatars for the people, rooms and spaces in the screenshots, cropped from photos on Wikimedia Commons and Public Domain Pictures that are in the public domain or CC0, so they need no attribution. + +| File | License | Source | +| ---------------------- | ------------- | -------------------------------------------------------------------------------------------------------- | +| pumpkin.webp | Public domain | https://commons.wikimedia.org/wiki/File:Cucurbita_2011_G1.jpg | +| orange.webp | Public domain | https://commons.wikimedia.org/wiki/File:Orange-fruit-2.jpg | +| log-1.webp | CC0 | https://commons.wikimedia.org/wiki/File:Tabby_cat_with_blue_eyes-3336579.jpg (tinted green) | +| strudel.webp | CC0 | https://commons.wikimedia.org/wiki/File:Strudel-de-maca-2.png | +| opal.webp | Public domain | https://commons.wikimedia.org/wiki/File:Opal_6.jpg | +| cinnamon.webp | CC0 | https://commons.wikimedia.org/wiki/File:Cassia_bark_(2).jpg | +| green-tea.webp | CC0 | https://www.publicdomainpictures.net/en/view-image.php?image=165622&picture=hot-green-tea-with-heart-art | +| development.webp | CC0 | https://commons.wikimedia.org/wiki/File:Code_on_computer_monitor_(Unsplash).jpg | +| fediverse.webp | Public domain | https://commons.wikimedia.org/wiki/File:Blackeyegalaxy.jpg | +| flutter-devs.webp | CC0 | https://commons.wikimedia.org/wiki/File:Anna%27s_Hummingbird_Feeding.jpg | +| linux-mobile.webp | CC0 | https://commons.wikimedia.org/wiki/File:Gentoo_penguin_with_a_feather_in_its_beak.jpg | +| matrix-community.webp | Public domain | https://commons.wikimedia.org/wiki/File:Earth_at_Night,_Asia_(8270740728).jpg | +| off-topic.webp | CC0 | https://commons.wikimedia.org/wiki/File:Coffee_cup_surrounded_by_coffee_beans.jpg | +| open-source-games.webp | Public domain | https://commons.wikimedia.org/wiki/File:LodgeNet-Nintendo-N64-Controller.jpg | +| rust.webp | CC0 | https://commons.wikimedia.org/wiki/File:Carcinus_maenas_146434844.jpg | +| self-hosting.webp | CC0 | https://commons.wikimedia.org/wiki/File:Legrand_S.A._server_rack.jpg | diff --git a/integration_test/screenshots/avatars/cinnamon.webp b/integration_test/screenshots/avatars/cinnamon.webp new file mode 100644 index 0000000..8520f24 Binary files /dev/null and b/integration_test/screenshots/avatars/cinnamon.webp differ diff --git a/integration_test/screenshots/avatars/development.webp b/integration_test/screenshots/avatars/development.webp new file mode 100644 index 0000000..21a47b1 Binary files /dev/null and b/integration_test/screenshots/avatars/development.webp differ diff --git a/integration_test/screenshots/avatars/fediverse.webp b/integration_test/screenshots/avatars/fediverse.webp new file mode 100644 index 0000000..8952d99 Binary files /dev/null and b/integration_test/screenshots/avatars/fediverse.webp differ diff --git a/integration_test/screenshots/avatars/flutter-devs.webp b/integration_test/screenshots/avatars/flutter-devs.webp new file mode 100644 index 0000000..79634a2 Binary files /dev/null and b/integration_test/screenshots/avatars/flutter-devs.webp differ diff --git a/integration_test/screenshots/avatars/green-tea.webp b/integration_test/screenshots/avatars/green-tea.webp new file mode 100644 index 0000000..d58801c Binary files /dev/null and b/integration_test/screenshots/avatars/green-tea.webp differ diff --git a/integration_test/screenshots/avatars/linux-mobile.webp b/integration_test/screenshots/avatars/linux-mobile.webp new file mode 100644 index 0000000..8a525bd Binary files /dev/null and b/integration_test/screenshots/avatars/linux-mobile.webp differ diff --git a/integration_test/screenshots/avatars/log-1.webp b/integration_test/screenshots/avatars/log-1.webp new file mode 100644 index 0000000..e954d0c Binary files /dev/null and b/integration_test/screenshots/avatars/log-1.webp differ diff --git a/integration_test/screenshots/avatars/matrix-community.webp b/integration_test/screenshots/avatars/matrix-community.webp new file mode 100644 index 0000000..2e58828 Binary files /dev/null and b/integration_test/screenshots/avatars/matrix-community.webp differ diff --git a/integration_test/screenshots/avatars/off-topic.webp b/integration_test/screenshots/avatars/off-topic.webp new file mode 100644 index 0000000..ea9ec17 Binary files /dev/null and b/integration_test/screenshots/avatars/off-topic.webp differ diff --git a/integration_test/screenshots/avatars/opal.webp b/integration_test/screenshots/avatars/opal.webp new file mode 100644 index 0000000..807223f Binary files /dev/null and b/integration_test/screenshots/avatars/opal.webp differ diff --git a/integration_test/screenshots/avatars/open-source-games.webp b/integration_test/screenshots/avatars/open-source-games.webp new file mode 100644 index 0000000..3b92ac7 Binary files /dev/null and b/integration_test/screenshots/avatars/open-source-games.webp differ diff --git a/integration_test/screenshots/avatars/orange.webp b/integration_test/screenshots/avatars/orange.webp new file mode 100644 index 0000000..1f9c199 Binary files /dev/null and b/integration_test/screenshots/avatars/orange.webp differ diff --git a/integration_test/screenshots/avatars/pumpkin.webp b/integration_test/screenshots/avatars/pumpkin.webp new file mode 100644 index 0000000..d300ec9 Binary files /dev/null and b/integration_test/screenshots/avatars/pumpkin.webp differ diff --git a/integration_test/screenshots/avatars/quadradical.webp b/integration_test/screenshots/avatars/quadradical.webp new file mode 100644 index 0000000..79e26c1 Binary files /dev/null and b/integration_test/screenshots/avatars/quadradical.webp differ diff --git a/integration_test/screenshots/avatars/rust.webp b/integration_test/screenshots/avatars/rust.webp new file mode 100644 index 0000000..5089187 Binary files /dev/null and b/integration_test/screenshots/avatars/rust.webp differ diff --git a/integration_test/screenshots/avatars/self-hosting.webp b/integration_test/screenshots/avatars/self-hosting.webp new file mode 100644 index 0000000..30535e9 Binary files /dev/null and b/integration_test/screenshots/avatars/self-hosting.webp differ diff --git a/integration_test/screenshots/avatars/strudel.webp b/integration_test/screenshots/avatars/strudel.webp new file mode 100644 index 0000000..e69e842 Binary files /dev/null and b/integration_test/screenshots/avatars/strudel.webp differ diff --git a/integration_test/screenshots/screenshot_data.dart b/integration_test/screenshots/screenshot_data.dart new file mode 100644 index 0000000..fbabe4b --- /dev/null +++ b/integration_test/screenshots/screenshot_data.dart @@ -0,0 +1,365 @@ +import "dart:convert"; + +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:nexus/models/client_state.dart"; +import "package:nexus/models/room.dart"; +import "package:nexus/models/space_edge.dart"; + +/// What the screenshots show: the Nexus space, with its room mid-conversation. +/// Rooms are written as gomuks reports them. +class ScreenshotData(final DateTime now) { + static const me = "@quadradical:federated.nexus"; + static const bot = "@nexusbot:federated.nexus"; + static const alice = "@alice:example.org"; + static const pumpkin = "@pumpkin:example.org"; + static const strudel = "@strudel:example.org"; + static const opal = "@opal:example.org"; + static const greenTea = "@greentea:example.org"; + + static const nexusSpace = "!nexus-space:federated.nexus"; + static const nexusRoom = "!nexus-client:federated.nexus"; + + /// Nexus' own avatar, the app icon. Every other `mxc://screenshots/` is + /// a file in avatars/, see avatars/SOURCES.md. + static const nexusAvatar = "mxc://screenshots/nexus"; + static const myAvatar = "mxc://screenshots/quadradical.webp"; + static const issueUrl = "https://git.federated.nexus/Nexus/nexus/issues/174"; + static const commitUrl = + "https://git.federated.nexus/Nexus/nexus/commit/41f5225420"; + + static const topic = + "A simple and user-friendly Matrix client made with Flutter and a Gomuks backend."; + + /// The users shown, with their power level in the Nexus room. Those without + /// an avatar get Nexus' fallback. Everyone but QuadRadical and NexusBot is + /// made up, on example.org so as not to be anyone real. + static const users = IListConst([ + (id: me, name: "QuadRadical", powerLevel: 100, avatar: myAvatar), + (id: alice, name: "Alice", powerLevel: 100, avatar: null), + (id: bot, name: "NexusBot", powerLevel: 50, avatar: nexusAvatar), + ( + id: pumpkin, + name: "Pumpkin", + powerLevel: 0, + avatar: "mxc://screenshots/pumpkin.webp", + ), + ( + id: strudel, + name: "Strudel", + powerLevel: 0, + avatar: "mxc://screenshots/strudel.webp", + ), + ( + id: opal, + name: "Opal", + powerLevel: 0, + avatar: "mxc://screenshots/opal.webp", + ), + ( + id: "@orange:example.org", + name: "Orange", + powerLevel: 0, + avatar: "mxc://screenshots/orange.webp", + ), + ( + id: "@log1:example.org", + name: "log(1)", + powerLevel: 0, + avatar: "mxc://screenshots/log-1.webp", + ), + ( + id: greenTea, + name: "Green Tea", + powerLevel: 0, + avatar: "mxc://screenshots/green-tea.webp", + ), + ( + id: "@cinnamon:example.org", + name: "Cinnamon", + powerLevel: 0, + avatar: "mxc://screenshots/cinnamon.webp", + ), + ]); + + /// The Nexus space's other rooms + static const otherRooms = IListConst([ + (name: "Off-topic", unread: 3), + (name: "Development", unread: 0), + ]); + + /// Spaces shown in the rail besides Nexus, so it doesn't look empty + static const otherSpaces = IListConst([ + "Matrix Community", + "Flutter Devs", + "Linux Mobile", + "Rust", + "Open Source Games", + "Fediverse", + "Self-Hosting", + ]); + + static const clientState = ClientState( + isInitialized: true, + isLoggedIn: true, + isVerified: true, + userId: me, + deviceId: "SCREENSHOTS", + homeserverUrl: "https://federated.nexus", + ); + + static final IList topLevelSpaces = .new([ + nexusSpace, + ...otherSpaces.map(_roomId), + ]); + + static final IMap> spaceEdges = .new({ + nexusSpace: .new( + [ + nexusRoom, + ...otherRooms.map((room) => _roomId(room.name)), + ].map((id) => .new(childId: id)), + ), + }); + + /// The rooms, with the Nexus room's state already fetched so it isn't + /// requested + late final IMap rooms = { + nexusSpace: _room(nexusSpace, "Nexus Client", topic: topic), + nexusRoom: _room( + nexusRoom, + "Nexus Client", + topic: topic, + lastEvent: timeline.last, + extra: { + "timeline": timeline + .map( + (event) => { + "timeline_rowid": event["rowid"], + "event_rowid": event["rowid"], + }, + ) + .toList(), + "events": [...nexusState, ...timeline], + "state": _stateIndex(nexusState), + "receipts": { + timeline.last["event_id"]: [ + _receipt(strudel, timeline.last), + _receipt(greenTea, timeline.last), + ], + timeline[timeline.length - 2]["event_id"]: [ + _receipt(opal, timeline[timeline.length - 2]), + ], + }, + "has_more": false, + }, + ).copyWith(hasFetchedState: true, hasFetchedMembers: true), + for (final room in otherRooms) + _roomId(room.name): _room( + _roomId(room.name), + room.name, + avatar: _avatarOfRoom(room.name), + unread: room.unread, + ), + for (final space in otherSpaces) + _roomId(space): _room( + _roomId(space), + space, + avatar: _avatarOfRoom(space), + ), + }.lock; + + /// The Nexus room's state: who's in it, and their power levels + late final List> nexusState = [ + _event(me, "m.room.power_levels", { + "users": Map.fromEntries( + users.map((user) => .new(user.id, user.powerLevel)), + ), + "users_default": 0, + "events_default": 0, + "state_default": 50, + }, key: ""), + ...users.map( + (user) => _event(user.id, "m.room.member", { + "membership": "join", + "displayname": user.name, + "avatar_url": ?user.avatar, + }, key: user.id), + ), + ]; + + late final List> timeline = [ + _message( + alice, + 35, + "the screenshots in the readme are pretty out of date btw", + ), + _message( + me, + 32, + "Should I:\n" + "1. just take screenshots on a few devices, and redo them whenever the " + "UI changes\n" + "or\n" + "2. overengineer a test that makes them automatically, in a fake room\n" + "I think the answer is 2 :p", + html: + "Should I:" + "
  1. just take screenshots on a few devices, and redo them " + "whenever the UI changes
" + "or" + '
  1. overengineer a test that makes them ' + "automatically, in a fake room
" + "I think the answer is 2 :p", + reactions: {"2️⃣": 3}, + ), + _message(pumpkin, 30, "2, obviously"), + // Linked only in the HTML, so the body has no link to preview + _message( + bot, + 29, + "[Nexus/nexus] Issue opened: #174 Automatic scripts to make screenshots " + "for different pages and viewports by Henry-Hiles", + html: + '[Nexus/nexus] Issue opened: #174 Automatic ' + "scripts to make screenshots for different pages and viewports " + "by Henry-Hiles", + ), + _message( + bot, + 7, + "[Nexus/nexus] Henry-Hiles pushed 1 commit to main: $commitUrl: " + "update screenshots - Henry-Hiles", + html: + "[Nexus/nexus] Henry-Hiles pushed 1 commit to main:
" + '41f5225: update screenshots - Henry-Hiles', + reactions: {"🚀": 3}, + ), + _message( + pumpkin, + 5, + "they're generated now?? let's gooo", + reactions: {"🎉": 2, "❤️": 1}, + ), + ]; + + /// The link preview shown under NexusBot's message + static const urlPreview = { + "og:title": "update screenshots · 41f5225420", + "og:description": + "nexus - A simple and user-friendly Matrix client made with Flutter " + "and a Gomuks backend.", + }; + + int _rowId = 0; + + /// An event in the Nexus room + Map _event( + String sender, + String type, + Map content, { + String? key, + int minutesAgo = 60, + Map reactions = const {}, + }) { + final rowId = ++_rowId; + return { + "rowid": rowId, + "timeline_rowid": rowId, + "room_id": nexusRoom, + "event_id": "\$screenshots-$rowId", + "sender": sender, + "type": type, + "state_key": ?key, + "timestamp": now + .subtract(.new(minutes: minutesAgo)) + .millisecondsSinceEpoch, + "content": content, + "reactions": reactions, + }; + } + + Map _message( + String sender, + int minutesAgo, + String body, { + String? html, + Map reactions = const {}, + }) => _event( + sender, + "m.room.message", + { + "msgtype": sender == bot ? "m.notice" : "m.text", + "body": body, + if (html != null) ...{ + "format": "org.matrix.custom.html", + "formatted_body": html, + }, + }, + minutesAgo: minutesAgo, + reactions: reactions, + ); + + Map _receipt(String userId, Map event) => { + "user_id": userId, + "event_id": event["event_id"], + "room_id": nexusRoom, + "timestamp": event["timestamp"], + }; + + /// A room, with [extra] JSON besides its metadata + Room _room( + String id, + String name, { + String avatar = nexusAvatar, + String? topic, + int unread = 0, + Map? lastEvent, + Map extra = const {}, + }) => .fromJson( + // Round-tripped, so the JSON has the types gomuks' decoded JSON would + jsonDecode( + jsonEncode({ + "meta": { + "room_id": id, + "name": name, + "avatar": avatar, + "topic": ?topic, + "has_member_list": true, + "preview_event_rowid": lastEvent?["rowid"] ?? 0, + "sorting_timestamp": + lastEvent?["timestamp"] ?? + now.subtract(const .new(hours: 1)).millisecondsSinceEpoch, + "unread_highlights": 0, + "unread_notifications": 0, + "unread_messages": unread, + }, + ...extra, + }), + ), + ); + + static Map> _stateIndex( + List> state, + ) => state + .groupListsBy((event) => event["type"] as String) + .map( + (type, events) => .new( + type, + Map.fromEntries( + events.map( + (event) => + .new(event["state_key"] as String, event["rowid"] as int), + ), + ), + ), + ); + + static String _avatarOfRoom(String name) => + "mxc://screenshots/${_slug(name)}.webp"; + + static String _slug(String name) => + name.toLowerCase().replaceAll(RegExp("[^a-z]+"), "-"); + + static String _roomId(String name) => "!${_slug(name)}:federated.nexus"; +} diff --git a/integration_test/screenshots/screenshot_fakes.dart b/integration_test/screenshots/screenshot_fakes.dart new file mode 100644 index 0000000..23ef76f --- /dev/null +++ b/integration_test/screenshots/screenshot_fakes.dart @@ -0,0 +1,62 @@ +import "dart:io"; +import "dart:ui" as ui; + +import "package:flutter/rendering.dart"; +import "package:flutter_test/flutter_test.dart"; +import "package:nexus/controllers/client.dart"; + +import "screenshot_data.dart"; + +/// Answers the commands the screenshotted screens send to gomuks, so the +/// screenshots don't need gomuks or a homeserver. +class FakeClientController() extends ClientController { + this : super(null); + + @override + Future build() async => 0; + + @override + Future sendCommand( + String command, [ + Map request = const {}, + ]) async => switch (command) { + "get_url_preview" => ScreenshotData.urlPreview, + "download_media" => {"path": _mediaPath(request["mxc"])}, + "get_related_events" => [], + "mark_read" || "set_typing" => null, + _ => throw UnimplementedError("The screenshots can't answer $command"), + }; + + /// The file for [mxc], from avatars/ beside this file + static String _mediaPath(String mxc) { + final file = File(switch (mxc) { + ScreenshotData.nexusAvatar => "assets/mobile.png", + _ => + "integration_test/screenshots/avatars/" + "${Uri.parse(mxc).pathSegments.last}", + }); + if (!file.existsSync()) throw StateError("No screenshot media for $mxc"); + return file.absolute.path; + } +} + +extension Screenshot on WidgetTester { + /// Saves what the app currently shows to [path], as a PNG. + Future screenshot(String path) async { + // Lets images finish decoding and animations settle + for (var frame = 0; frame < 20; frame++) { + await runAsync(() => .delayed(const .new(milliseconds: 50))); + await pump(const .new(milliseconds: 50)); + } + + final renderView = binding.renderViews.single; + final layer = renderView.debugLayer! as OffsetLayer; + final bytes = await runAsync(() async { + final image = await layer.toImage(Offset.zero & view.physicalSize); + return image.toByteData(format: ui.ImageByteFormat.png); + }); + + await File(path).create(recursive: true); + await File(path).writeAsBytes(bytes!.buffer.asUint8List()); + } +} diff --git a/integration_test/screenshots/screenshots_test.dart b/integration_test/screenshots/screenshots_test.dart new file mode 100644 index 0000000..29ed0bd --- /dev/null +++ b/integration_test/screenshots/screenshots_test.dart @@ -0,0 +1,142 @@ +import "dart:convert"; + +import "package:flutter_test/flutter_test.dart"; +import "package:integration_test/integration_test.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/client_state.dart"; +import "package:nexus/controllers/gomuks_listener.dart"; +import "package:nexus/controllers/init_complete.dart"; +import "package:nexus/controllers/key.dart"; +import "package:nexus/controllers/member_list_opened.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/controllers/settings.dart"; +import "package:nexus/controllers/space_edges.dart"; +import "package:nexus/controllers/top_level_spaces.dart"; +import "package:nexus/main.dart" as nexus; +import "package:nexus/models/account.dart"; +import "package:nexus/widgets/account_scope.dart"; +import "package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart"; +import "package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart"; + +import "../helpers/pump_until.dart"; +import "screenshot_data.dart"; +import "screenshot_fakes.dart"; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + // Where the screenshots are saved, set by `nix run .#screenshots` + const outputDirectory = String.fromEnvironment( + "SCREENSHOTS_DIR", + defaultValue: "build/screenshots", + ); + const accountId = "screenshots"; + + final data = ScreenshotData(.now()); + + setUpAll(() => nexus.isInBackground = false); + + /// Opens Nexus at the Nexus room, as a [size] window at [pixelRatio], + /// pretending to be a phone if [mobile]. + Future open( + WidgetTester tester, { + required ThemeMode theme, + required Size size, + required double pixelRatio, + required bool mobile, + }) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = pixelRatio; + addTearDown(tester.view.reset); + + SharedPreferencesAsyncPlatform.instance = + InMemorySharedPreferencesAsync.withData({ + KeyController.accountsKey: json.encode([ + Account( + id: accountId, + userId: ScreenshotData.me, + displayName: "QuadRadical", + avatar: .parse(ScreenshotData.myAvatar), + ), + ]), + KeyController.activeAccountKey: accountId, + MemberListOpenedController.key: true, + "$accountId/${KeyController.spaceKey}": ScreenshotData.nexusSpace, + "$accountId/${KeyController.roomKey}": ScreenshotData.nexusRoom, + }); + + await tester.pumpWidget( + AccountScope( + initialAccountId: accountId, + retry: (_, _) => null, + overrides: [ + ClientController.provider.overrideWith(FakeClientController.new), + // Never starts gomuks; the state below is what it would sync + GomuksListenerController.provider.overrideWithBuild((_, _) {}), + ClientStateController.provider.overrideWithBuild( + (_, _) => ScreenshotData.clientState, + ), + InitCompleteController.provider.overrideWithBuild((_, _) => true), + RoomsController.provider.overrideWithBuild((_, _) => data.rooms), + TopLevelSpacesController.provider.overrideWithBuild( + (_, _) => ScreenshotData.topLevelSpaces, + ), + SpaceEdgesController.provider.overrideWithBuild( + (_, _) => ScreenshotData.spaceEdges, + ), + SettingsController.provider.overrideWithBuild( + (_, _) => .new( + theme: theme, + useDynamicTheming: false, + linuxMobileMode: mobile, + ), + ), + ], + child: nexus.App(), + ), + ); + + await tester.pumpUntil(find.text("they're generated now?? let's gooo")); + + // Focused on desktop, which would show a cursor + FocusManager.instance.primaryFocus?.unfocus(); + } + + for (final theme in [ThemeMode.dark, ThemeMode.light]) { + testWidgets("desktop, ${theme.name}", (tester) async { + await open( + tester, + theme: theme, + size: const .new(1920, 1080), + pixelRatio: 1, + mobile: false, + ); + + await tester.pumpUntil(find.text("Strudel")); + + await tester.screenshot("$outputDirectory/desktop-${theme.name}.png"); + }); + + testWidgets("phone, ${theme.name}", (tester) async { + await open( + tester, + theme: theme, + size: const .new(1080, 2340), + pixelRatio: 3, + mobile: true, + ); + + await tester.screenshot("$outputDirectory/phone-chat-${theme.name}.png"); + + await tester.tap( + find.byTooltip( + const DefaultMaterialLocalizations().openAppDrawerTooltip, + ), + ); + await tester.pumpUntil(find.text("Off-topic")); + + await tester.screenshot("$outputDirectory/phone-rooms-${theme.name}.png"); + }); + } +} diff --git a/integration_test/threads_test.dart b/integration_test/threads_test.dart new file mode 100644 index 0000000..8105f1b --- /dev/null +++ b/integration_test/threads_test.dart @@ -0,0 +1,258 @@ +import "package:flutter_test/flutter_test.dart"; +import "package:integration_test/integration_test.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/widgets/composer/composer.dart"; +import "package:nexus/widgets/room_chat/room_chat.dart"; +import "package:nexus/widgets/threads/thread_drawer.dart"; +import "package:nexus/widgets/threads/thread_summary.dart"; +import "package:nexus/widgets/threads/threads_drawer.dart"; + +import "helpers/matrix_user.dart"; +import "helpers/test_app.dart"; +import "helpers/pump_until.dart"; +import "helpers/threads.dart"; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + final app = TestApp("alice", "alicepass"); + setUpAll(app.setUp); + final run = DateTime.now().millisecondsSinceEpoch; + late MatrixUser bob; + + setUpAll(() async => bob = await MatrixUser.login("bob", "bobpass")); + + /// Opens [roomName], waiting for the thread from [rootBody] in its timeline. + Future openRoom( + WidgetTester tester, + String roomName, + String rootBody, + ) async { + await app.openRoom(tester, roomName); + await tester.pumpUntil( + find.message(rootBody).inside(RoomChat).hitTestable(), + ); + } + + /// Opens the thread from the room's summary, waiting for [reply] in it. + Future openThread(WidgetTester tester, String reply) async { + await tester.tapWhenShown(find.byType(ThreadSummary)); + await tester.pumpUntil(find.message(reply).inside(ThreadDrawer)); + } + + group("a thread", () { + final roomName = "Threads $run"; + final rootBody = "Thread root $run"; + const firstReply = "First reply"; + const secondReply = "Second reply"; + + late String roomId; + late String rootId; + + setUpAll(() async { + roomId = await bob.createRoom(roomName); + // Joined before Nexus logs in, so the room is there once it does + await app.join(bob, roomId); + + rootId = (await bob.sendThread( + roomId, + rootBody, + .new([firstReply, secondReply]), + )).rootId; + }); + + Future replyCount() async => + (await bob.threadReplies(roomId, rootId)).length; + + testWidgets("logs in with OAuth and sets up encryption", (tester) async { + await app.open(tester); + + await app.selectRoom(tester, roomName); + }); + + testWidgets("summarises the thread under its root", (tester) async { + await openRoom(tester, roomName, rootBody); + + await tester.expectReplyCount(ThreadSummary, 2); + expect(find.message(secondReply).inside(ThreadSummary), findsWidgets); + // Replies are in the thread, not the room's timeline + expect(find.message(firstReply), findsNothing); + }); + + testWidgets("lists the thread in the threads drawer", (tester) async { + await openRoom(tester, roomName, rootBody); + await tester.tapWhenShown(find.byTooltip("Open threads")); + + await tester.pumpUntil(find.message(rootBody).inside(ThreadsDrawer)); + await tester.expectReplyCount(ThreadsDrawer, 2); + expect(find.text("Last active:").inside(ThreadsDrawer), findsOneWidget); + }); + + testWidgets("opens the thread from the threads drawer", (tester) async { + await openRoom(tester, roomName, rootBody); + await tester.tapWhenShown(find.byTooltip("Open threads")); + await tester.tapWhenShown( + find.message(rootBody).inside(ThreadsDrawer).inkWell, + ); + + await tester.pumpUntil(find.message(secondReply).inside(ThreadDrawer)); + }); + + testWidgets("shows the root and its replies, oldest first", (tester) async { + await openRoom(tester, roomName, rootBody); + await openThread(tester, secondReply); + + final root = find.message(rootBody).inside(ThreadDrawer).first; + final first = find.message(firstReply).inside(ThreadDrawer).first; + final second = find.message(secondReply).inside(ThreadDrawer).first; + expect(root, findsOneWidget); + expect(first, findsOneWidget); + expect( + tester.getTopLeft(root).dy, + lessThan(tester.getTopLeft(first).dy), + reason: "The root should be above the replies", + ); + expect( + tester.getTopLeft(first).dy, + lessThan(tester.getTopLeft(second).dy), + reason: "Older replies should be above newer ones", + ); + }); + + testWidgets("sends replies to the thread", (tester) async { + final body = "Reply from Nexus $run"; + final before = await replyCount(); + await openRoom(tester, roomName, rootBody); + await openThread(tester, secondReply); + + final composer = find + .widgetWithText(TextField, "Your message here...") + .inside(ThreadDrawer); + await tester.pumpUntil(composer); + await tester.enterText(composer, body); + await tester.tapWhenShown( + find.byTooltip("Send message").inside(ThreadDrawer), + ); + await tester.pumpUntil(find.message(body).inside(ThreadDrawer)); + + // It's in the thread for other clients too + final replies = await bob.threadRepliesIncluding(roomId, rootId, body); + expect(replies.last, body); + + // Shown as the latest reply once the summary has caught up + await tester.pumpUntil(find.message(body).inside(ThreadSummary)); + await tester.expectReplyCount(ThreadSummary, before + 1); + expect( + find.text(body).inside(Composer), + findsNothing, + reason: "The composer should be cleared once sent", + ); + }); + + testWidgets("shows replies from others as they arrive", (tester) async { + final body = "Live reply $run"; + await openRoom(tester, roomName, rootBody); + await openThread(tester, secondReply); + + final before = await replyCount(); + await bob.send(roomId, body, threadRoot: rootId); + + await tester.pumpUntil(find.message(body).inside(ThreadDrawer)); + await tester.pumpUntil(find.message(body).inside(ThreadSummary)); + await tester.expectReplyCount(ThreadSummary, before + 1); + }); + }); + + group("redactions", () { + final roomName = "Redactions $run"; + final rootBody = "Redaction root $run"; + const keptReply = "Kept reply"; + const redactedReply = "Redacted reply"; + + late String roomId; + late String rootId; + late String redactedId; + + setUpAll(() async { + roomId = await bob.createRoom(roomName); + await app.join(bob, roomId); + + final thread = await bob.sendThread( + roomId, + rootBody, + .new([keptReply, redactedReply]), + ); + rootId = thread.rootId; + redactedId = thread.replyIds.last; + }); + + testWidgets("drops a redacted reply from its thread", (tester) async { + await openRoom(tester, roomName, rootBody); + await tester.expectReplyCount(ThreadSummary, 2); + + await bob.redact(roomId, redactedId); + + // The reply before it becomes the latest + await tester.pumpUntil(find.message(keptReply).inside(ThreadSummary)); + await tester.expectReplyCount(ThreadSummary, 1); + + await openThread(tester, keptReply); + expect(find.message(redactedReply).inside(ThreadDrawer), findsNothing); + }); + + testWidgets("still opens the thread of a redacted root", (tester) async { + await bob.redact(roomId, rootId); + await app.openRoom(tester, roomName); + await tester.tapWhenShown(find.byTooltip("Open threads")); + + // The root's preview is redacted, so the card is found by its count + await tester.tapWhenShown( + find.text("1 reply").inside(ThreadsDrawer).inkWell, + ); + + final root = find.text("Redacted event").inside(ThreadDrawer); + final reply = find.message(keptReply).inside(ThreadDrawer); + await tester.pumpUntil(root); + await tester.pumpUntil(reply); + expect( + tester.getTopLeft(root.first).dy, + lessThan(tester.getTopLeft(reply.first).dy), + reason: "The redacted root should still be above the replies", + ); + }); + }); + + group("edits", () { + final roomName = "Edits $run"; + final rootBody = "Edit root $run"; + const originalReply = "Reply before editing"; + const editedReply = "Reply after editing"; + + late String roomId; + late String replyId; + + setUpAll(() async { + roomId = await bob.createRoom(roomName); + await app.join(bob, roomId); + + final thread = await bob.sendThread( + roomId, + rootBody, + .new([originalReply]), + ); + replyId = thread.replyIds.single; + }); + + testWidgets("shows an edited reply's new text", (tester) async { + await openRoom(tester, roomName, rootBody); + await tester.pumpUntil(find.message(originalReply).inside(ThreadSummary)); + + await bob.edit(roomId, replyId, editedReply); + + await tester.pumpUntil(find.message(editedReply).inside(ThreadSummary)); + await openThread(tester, editedReply); + expect(find.message(originalReply).inside(ThreadDrawer), findsNothing); + expect(find.text("(edited)").inside(ThreadDrawer), findsOneWidget); + }); + }); +} diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig index ec97fc6..592ceee 100644 --- a/ios/Flutter/Debug.xcconfig +++ b/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig index c4855bf..592ceee 100644 --- a/ios/Flutter/Release.xcconfig +++ b/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/ios/Podfile b/ios/Podfile deleted file mode 100644 index 620e46e..0000000 --- a/ios/Podfile +++ /dev/null @@ -1,43 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '13.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/ios/Podfile.lock b/ios/Podfile.lock deleted file mode 100644 index b29d5cb..0000000 --- a/ios/Podfile.lock +++ /dev/null @@ -1,28 +0,0 @@ -PODS: - - Flutter (1.0.0) - - media_kit_libs_ios_video (1.0.4): - - Flutter - - media_kit_video (0.0.1): - - Flutter - -DEPENDENCIES: - - Flutter (from `Flutter`) - - media_kit_libs_ios_video (from `.symlinks/plugins/media_kit_libs_ios_video/ios`) - - media_kit_video (from `.symlinks/plugins/media_kit_video/ios`) - -EXTERNAL SOURCES: - Flutter: - :path: Flutter - media_kit_libs_ios_video: - :path: ".symlinks/plugins/media_kit_libs_ios_video/ios" - media_kit_video: - :path: ".symlinks/plugins/media_kit_video/ios" - -SPEC CHECKSUMS: - Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467 - media_kit_libs_ios_video: 5a18affdb97d1f5d466dc79988b13eff6c5e2854 - media_kit_video: 1746e198cb697d1ffb734b1d05ec429d1fcd1474 - -PODFILE CHECKSUM: 3c63482e143d1b91d2d2560aee9fb04ecc74ac7e - -COCOAPODS: 1.17.0 diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 065d08b..1612bb0 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -8,13 +8,11 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; - 2ADFEE6C745FFB2100CC9AFD /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8156A45F510382D558AED93A /* Pods_RunnerTests.framework */; }; 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; - 88D55A5F1C7625122EBEE29D /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 82F9A3759658343C81A0EA4C /* Pods_Runner.framework */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; @@ -46,19 +44,14 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 22DE4310DAFBE211CDF700B1 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 363A89F6FA09BCCBDED440CE /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 63516CF65A79A5DDDE64B0D1 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 8156A45F510382D558AED93A /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 82F9A3759658343C81A0EA4C /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -66,9 +59,6 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - AEB96D8976BD46D6860C7041 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - B8B599FDB72E4713FB7B5A44 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; - FE5E4162842555A83F8A7FD7 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -76,7 +66,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 2ADFEE6C745FFB2100CC9AFD /* Pods_RunnerTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -85,27 +74,12 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 88D55A5F1C7625122EBEE29D /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 1CFFAE23B502BCCEB2B191A3 /* Pods */ = { - isa = PBXGroup; - children = ( - AEB96D8976BD46D6860C7041 /* Pods-Runner.debug.xcconfig */, - 363A89F6FA09BCCBDED440CE /* Pods-Runner.release.xcconfig */, - 22DE4310DAFBE211CDF700B1 /* Pods-Runner.profile.xcconfig */, - B8B599FDB72E4713FB7B5A44 /* Pods-RunnerTests.debug.xcconfig */, - FE5E4162842555A83F8A7FD7 /* Pods-RunnerTests.release.xcconfig */, - 63516CF65A79A5DDDE64B0D1 /* Pods-RunnerTests.profile.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; 331C8082294A63A400263BE5 /* RunnerTests */ = { isa = PBXGroup; children = ( @@ -114,15 +88,6 @@ path = RunnerTests; sourceTree = ""; }; - 594EB1F65336CF9C7958F6FA /* Frameworks */ = { - isa = PBXGroup; - children = ( - 82F9A3759658343C81A0EA4C /* Pods_Runner.framework */, - 8156A45F510382D558AED93A /* Pods_RunnerTests.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( @@ -142,8 +107,6 @@ 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, 331C8082294A63A400263BE5 /* RunnerTests */, - 1CFFAE23B502BCCEB2B191A3 /* Pods */, - 594EB1F65336CF9C7958F6FA /* Frameworks */, ); sourceTree = ""; }; @@ -179,7 +142,6 @@ isa = PBXNativeTarget; buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - EE82EC529EB6C0F1FA480659 /* [CP] Check Pods Manifest.lock */, 331C807D294A63A400263BE5 /* Sources */, 331C807F294A63A400263BE5 /* Resources */, 8C0A36760DA8B873D8F6DDCE /* Frameworks */, @@ -198,14 +160,12 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 0830C6758DA3ECA81FB12386 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - 1D165FDFB9D0D939B041966D /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -283,45 +243,6 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 0830C6758DA3ECA81FB12386 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 1D165FDFB9D0D939B041966D /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -353,28 +274,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - EE82EC529EB6C0F1FA480659 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -502,7 +401,6 @@ }; 331C8088294A63A400263BE5 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = B8B599FDB72E4713FB7B5A44 /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; @@ -520,7 +418,6 @@ }; 331C8089294A63A400263BE5 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = FE5E4162842555A83F8A7FD7 /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; @@ -536,7 +433,6 @@ }; 331C808A294A63A400263BE5 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 63516CF65A79A5DDDE64B0D1 /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata index 21a3cc1..1d526a1 100644 --- a/ios/Runner.xcworkspace/contents.xcworkspacedata +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -4,7 +4,4 @@ - - diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 7680b42..7deed9e 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -28,6 +28,7 @@ CFBundleURLSchemes nexus.federated.nexus + matrix @@ -75,5 +76,7 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight + NSLocationWhenInUseUsageDescription + Nexus uses your location only when you choose to share it in a message. diff --git a/lib/controllers/account_data.dart b/lib/controllers/account_data.dart index c595565..62997b5 100644 --- a/lib/controllers/account_data.dart +++ b/lib/controllers/account_data.dart @@ -1,21 +1,161 @@ +import "dart:async"; import "dart:convert"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter/foundation.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/client.dart"; import "package:nexus/models/account_data.dart"; +import "package:nexus/models/push_rules.dart"; +import "package:nexus/models/requests/update_push_rule.dart"; +import "package:nexus/models/room_notification_level.dart"; +import "package:nexus/models/sync_data.dart"; class AccountDataController extends Notifier { @override AccountData build() => .new(); void update(IMap> newAccountData) => - state = .fromJson({ - ...json.decode(json.encode(state.toJson())), - ...newAccountData - .map((key, value) => MapEntry(key, value["content"])) - .unlock, + state = newAccountData.entries.fold(state, (data, entry) { + try { + return .fromJson({ + ...json.decode(json.encode(data.toJson())), + entry.key: entry.value["content"], + }); + } catch (error) { + debugPrint("Ignoring invalid ${entry.key} account data: $error"); + return data; + } }); + void handleSync(SyncData sync) { + if (sync.clearState) state = .new(); + update(sync.accountData); + } + + Future setEnabledImagePacks(ImagePackRooms packs) { + ISet<(String, String)> keysOf(ImagePackRooms rooms) => rooms.rooms.entries + .expand((entry) => entry.value.keys.map((key) => (entry.key, key))) + .toISet(); + final keys = keysOf(packs); + final client = ref.read(ClientController.provider.notifier); + + return _sendAndWait( + () => .wait([ + if (state.imagePackRooms != null) + client.setAccountData( + .new(type: AccountData.imagePackRoomsKey, content: packs), + ), + client.setAccountData( + .new(type: AccountData.legacyImagePackRoomsKey, content: packs), + ), + ]), + (data) { + final current = keysOf(data.enabledImagePacks); + return current.length == keys.length && current.containsAll(keys); + }, + ); + } + + Future setIgnored(String userId, {required bool ignored}) => + _sendAndWait( + () => ref + .read(ClientController.provider.notifier) + .setAccountData( + .new( + type: AccountData.ignoredUserListKey, + content: state.ignoredUserList.withUser( + userId, + ignored: ignored, + ), + ), + ), + (data) => data.ignoredUserList.contains(userId) == ignored, + ); + + /// Saves [rule] of [kind], creating it if it's new, or otherwise changing only + /// its actions and whether it's enabled. + Future savePushRule(PushRuleKind kind, PushRule rule) { + UpdatePushRuleRequest request(UpdatePushRuleAction action) => + .new(kind: kind, ruleId: rule.ruleId, action: action); + + return _updatePushRules( + .new(switch (state.pushRules.global.find(kind, rule.ruleId)) { + null => [request(.put).copyWith(newContent: rule)], + final previous => [ + if (previous.actions != rule.actions) + request(.putActions).copyWith(actions: rule.actions), + if (previous.enabled != rule.enabled) + request(rule.enabled ? .enable : .disable), + ], + }), + (rules) => rules.find(kind, rule.ruleId) == rule, + ); + } + + Future deletePushRule(PushRuleKind kind, String ruleId) => + _updatePushRules( + .new([.new(kind: kind, ruleId: ruleId, action: .delete)]), + (rules) => rules.find(kind, ruleId) == null, + ); + + /// Replaces the push rules for the room with [roomId] with those [level] + /// needs, deleting them first so disabled ones don't stay disabled. + Future setRoomNotificationLevel( + String roomId, + RoomNotificationLevel level, + ) async { + final rules = state.pushRules.global; + if (RoomNotificationLevel.of(rules, roomId) == level) return; + + return _updatePushRules( + .new([ + ...[PushRuleKind.override, PushRuleKind.room] + .where((kind) => rules.find(kind, roomId) != null) + .map((kind) => .new(kind: kind, ruleId: roomId, action: .delete)), + if (level.ruleFor(roomId) case (:final kind, :final rule)) + .new(kind: kind, ruleId: roomId, action: .put, newContent: rule), + ]), + (rules) => RoomNotificationLevel.of(rules, roomId) == level, + ); + } + + /// Sends [requests] in order, then waits until [arrived] is true for the + /// synced push rules. + Future _updatePushRules( + IList requests, + bool Function(PushRuleset rules) arrived, + ) => _sendAndWait( + () => .forEach( + requests, + ref.read(ClientController.provider.notifier).updatePushRule, + ), + (data) => arrived(data.pushRules.global), + ); + + /// Runs [send], then waits until [arrived] is true for the synced data. + Future _sendAndWait( + Future Function() send, + bool Function(AccountData data) arrived, + ) async { + final completer = Completer(); + final removeListener = listenSelf((_, data) { + if (arrived(data) && !completer.isCompleted) completer.complete(); + }); + + try { + await send(); + if (!arrived(state)) { + await completer.future.timeout( + const .new(seconds: 10), + onTimeout: () {}, + ); + } + } finally { + removeListener(); + } + } + static final provider = NotifierProvider( AccountDataController.new, ); diff --git a/lib/controllers/accounts.dart b/lib/controllers/accounts.dart new file mode 100644 index 0000000..0e93f9a --- /dev/null +++ b/lib/controllers/accounts.dart @@ -0,0 +1,60 @@ +import "dart:convert"; + +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/key.dart"; +import "package:nexus/models/account.dart"; + +class AccountsController extends AsyncNotifier> { + @override + Future> build() async { + final stored = await ref.watch( + KeyController.provider(KeyController.accountsKey).future, + ); + final accounts = IList( + (json.decode(stored ?? "[]") as List).map( + (account) => .fromJson(account), + ), + ); + + // Installs from before account switching are logged into the legacy slot + return accounts.isEmpty + ? .new([const .new(id: Account.legacyId)]) + : accounts; + } + + Future _set(IList accounts) async { + state = .data(accounts); + await ref + .read(KeyController.provider(KeyController.accountsKey).notifier) + .set(json.encode(accounts.map((account) => account.toJson()).toList())); + } + + Future> get _current async { + await future; + return state.requireValue; + } + + Future save(Account account) async { + final accounts = await _current; + final index = accounts.indexWhere((existing) => existing.id == account.id); + + await _set( + index == -1 ? accounts.add(account) : accounts.replace(index, account), + ); + } + + Future reset(String id) async { + final accounts = await _current; + final index = accounts.indexWhere((account) => account.id == id); + if (index != -1) await _set(accounts.replace(index, .new(id: id))); + } + + Future remove(String id) async => + _set((await _current).removeWhere((account) => account.id == id)); + + static final provider = + AsyncNotifierProvider>( + AccountsController.new, + ); +} diff --git a/lib/controllers/active_account.dart b/lib/controllers/active_account.dart new file mode 100644 index 0000000..d61e6b2 --- /dev/null +++ b/lib/controllers/active_account.dart @@ -0,0 +1,53 @@ +import "package:collection/collection.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/accounts.dart"; +import "package:nexus/controllers/key.dart"; +import "package:nexus/controllers/notification_request.dart"; +import "package:nexus/models/account.dart"; +import "package:shared_preferences/shared_preferences.dart"; + +typedef AccountSwitch = ({String accountId, int? notificationRowId}); + +class ActiveAccountController( + final String accountId, + final void Function(AccountSwitch next) restart, +) extends Notifier { + @override + String build() => accountId; + + static Future stored() async => + await SharedPreferencesAsync().getString( + KeyController.activeAccountKey, + ) ?? + Account.legacyId; + + /// Restarts the app as [accountId], then opens [notificationRowId] if given. + Future switchTo(String accountId, {int? notificationRowId}) async { + if (accountId == state) { + if (notificationRowId != null) { + ref + .read(NotificationRequestController.provider.notifier) + .request(notificationRowId); + } + return; + } + + final accounts = await ref.read(AccountsController.provider.future); + if (!accounts.any((account) => account.id == accountId)) return; + + if (accounts.firstWhereOrNull((account) => account.id == state) + case Account(userId: null)) { + await ref.read(AccountsController.provider.notifier).remove(state); + } + + await ref + .read(KeyController.provider(KeyController.activeAccountKey).notifier) + .set(accountId); + + restart((accountId: accountId, notificationRowId: notificationRowId)); + } + + static final provider = NotifierProvider( + () => throw UnimplementedError("Provided by AccountScope"), + ); +} diff --git a/lib/controllers/all_emoji.dart b/lib/controllers/all_emoji.dart new file mode 100644 index 0000000..5703356 --- /dev/null +++ b/lib/controllers/all_emoji.dart @@ -0,0 +1,25 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:material_emoji_picker/material_emoji_picker.dart"; +import "package:nexus/controllers/image_packs.dart"; +import "package:nexus/helpers/extensions/image_pack_emoji.dart"; + +class AllEmojiController(final String roomId) + extends AsyncNotifier> { + @override + Future> build() async { + final packs = await ref.watch(ImagePacksController.provider(roomId).future); + final unicode = await ref.watch(EmojiController.provider.future); + + return packs + .map((pack) => pack.emojiCategory) + .nonNulls + .toIList() + .addAll(unicode); + } + + static final provider = AsyncNotifierProvider.autoDispose + .family, String>( + AllEmojiController.new, + ); +} diff --git a/lib/controllers/attachment.dart b/lib/controllers/attachment.dart index 2cabbae..c976684 100644 --- a/lib/controllers/attachment.dart +++ b/lib/controllers/attachment.dart @@ -4,9 +4,12 @@ import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/models/content/content.dart"; import "package:nexus/models/content/message.dart"; +import "package:nexus/models/composer_params.dart"; import "package:path/path.dart"; -class AttachmentController(final String roomId) +typedef AttachmentParams = ({ComposerParams composer, int? editingRowId}); + +class AttachmentController(final AttachmentParams params) extends Notifier<(String, MessageContent?)?> { @override Null build() => null; @@ -18,7 +21,10 @@ class AttachmentController(final String roomId) final isEncrypted = ref.read( RoomsController.provider.select( (value) => - value[roomId]?.state[EventType.encryption.type]?.isNotEmpty == true, + value[params.composer.roomId] + ?.state[EventType.encryption.type] + ?.isNotEmpty == + true, ), ); @@ -29,8 +35,12 @@ class AttachmentController(final String roomId) state = (filename, content); } - static final provider = NotifierProvider.family - .autoDispose( - AttachmentController.new, - ); + void set((String, MessageContent?)? attachment) => state = attachment; + + static final provider = + NotifierProvider.family< + AttachmentController, + (String, MessageContent?)?, + AttachmentParams + >(AttachmentController.new); } diff --git a/lib/controllers/author.dart b/lib/controllers/author.dart index f9c9167..0b783f0 100644 --- a/lib/controllers/author.dart +++ b/lib/controllers/author.dart @@ -2,27 +2,30 @@ import "dart:async"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/user.dart"; +import "package:nexus/models/configs/author.dart"; import "package:nexus/models/content/membership.dart"; -import "package:nexus/models/event.dart"; -class AuthorController(final Event event) +class AuthorController(final AuthorConfig config) extends AsyncNotifier { @override Future build() async { final member = await ref.watch( - UserController.provider(.new(roomId: event.roomId, userId: event.sender)) - .future, + UserController.provider( + .new(roomId: config.roomId, userId: config.userId), + ).future, ); return .new( status: member.status, - avatarUrl: event.pmp?.avatarUrl ?? member.avatarUrl, - displayName: event.pmp?.displayName ?? member.displayName, + avatarUrl: config.avatarUrl ?? member.avatarUrl, + displayName: config.displayName ?? member.displayName, ); } static final provider = - AsyncNotifierProvider.family( - AuthorController.new, - ); + AsyncNotifierProvider.family< + AuthorController, + MembershipContent, + AuthorConfig + >(AuthorController.new); } diff --git a/lib/controllers/banned_warning_dismissed.dart b/lib/controllers/banned_warning_dismissed.dart new file mode 100644 index 0000000..b080d38 --- /dev/null +++ b/lib/controllers/banned_warning_dismissed.dart @@ -0,0 +1,20 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/shared_prefs.dart"; + +class BannedWarningDismissedController extends AsyncNotifier { + static const String key = "bannedWarningDismissed"; + + @override + Future build() async => + await ref.watch(SharedPrefsController.provider).getBool(key) ?? false; + + Future set(bool value) async { + state = .data(value); + await ref.read(SharedPrefsController.provider).setBool(key, value); + } + + static final provider = + AsyncNotifierProvider( + BannedWarningDismissedController.new, + ); +} diff --git a/lib/controllers/bot_argument_suggestions.dart b/lib/controllers/bot_argument_suggestions.dart new file mode 100644 index 0000000..04c2152 --- /dev/null +++ b/lib/controllers/bot_argument_suggestions.dart @@ -0,0 +1,131 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/bot_command_draft.dart"; +import "package:nexus/controllers/members_by_status.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/controllers/via.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/helpers/extensions/weighted_search.dart"; +import "package:nexus/models/bot_argument_suggestion.dart"; +import "package:nexus/models/bot_command_draft.dart"; +import "package:nexus/models/composer_params.dart"; +import "package:nexus/models/content/bot_command_description.dart"; +import "package:nexus/models/content/membership.dart"; +import "package:nexus/models/event.dart"; +import "package:nexus/models/room.dart"; + +class BotArgumentSuggestionsController(final ComposerParams composer) + extends Notifier> { + @override + IList build() { + final draft = ref.watch(BotCommandDraftController.provider(composer)); + final (parameter, text) = switch (draft) { + BotCommandDraft(focusedParameter: final parameter?, :final texts) => ( + parameter, + texts[parameter.key] ?? "", + ), + _ => (null, ""), + }; + if (parameter == null) return const .empty(); + + final schema = parameter.schema; + final parts = schema is ArraySchema + ? text.split(BotParameterSchema.separator) + : [text]; + final query = parts.last.trim().toLowerCase(); + final picked = parts.take(parts.length - 1).toISet(); + + final members = schema.allows(.userId) + ? ref + .watch( + MembersByStatusController.provider( + .new(roomId: composer.roomId, status: .join), + ), + ) + .value ?? + const .empty() + : const ISet.empty(); + final rooms = schema.allows(.roomId) + ? ref.watch(RoomsController.provider).values + : const []; + + return { + ...schema.literals.map((literal) => "$literal"), + if (schema.allows(.boolean)) ...["True", "False"], + } + .map((value) => BotArgumentSuggestion(title: value, text: value)) + .followedBy( + members + .map( + (member) => switch (member) { + Event( + stateKey: final userId?, + content: MembershipContent( + :final displayName, + :final avatarUrl, + ), + ) => + BotArgumentSuggestion( + title: displayName ?? userId.localpart, + subtitle: userId, + avatar: avatarUrl, + text: userId, + ), + _ => null, + }, + ) + .nonNulls, + ) + .followedBy( + rooms + .map( + (room) => switch (room.metadata) { + final metadata? => BotArgumentSuggestion( + title: + metadata.name ?? metadata.canonicalAlias ?? metadata.id, + subtitle: metadata.canonicalAlias ?? metadata.id, + avatar: metadata.avatar, + text: metadata.id, + room: room, + ), + null => null, + }, + ) + .nonNulls, + ) + .where((suggestion) => !picked.contains(suggestion.text)) + .search( + query, + (suggestion) => [(suggestion.title, 2), (suggestion.subtitle, 1)], + ) + .take(8) + .toIList(); + } + + void pick(BotArgumentSuggestion suggestion) => ref + .read(BotCommandDraftController.provider(composer).notifier) + .pick( + suggestion, + via: switch (suggestion.room) { + final room? => ref.read(ViaController.provider(room)), + null => const .empty(), + }, + ); + + bool pickTop() { + final draft = ref.read(BotCommandDraftController.provider(composer)); + if (state.firstOrNull case final suggestion? + when draft != null && !draft.arguments.containsKey(draft.focused)) { + pick(suggestion); + return true; + } + return false; + } + + static final provider = NotifierProvider.autoDispose + .family< + BotArgumentSuggestionsController, + IList, + ComposerParams + >(BotArgumentSuggestionsController.new); +} diff --git a/lib/controllers/bot_command_draft.dart b/lib/controllers/bot_command_draft.dart new file mode 100644 index 0000000..44ee9f5 --- /dev/null +++ b/lib/controllers/bot_command_draft.dart @@ -0,0 +1,108 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/models/bot_argument_suggestion.dart"; +import "package:nexus/models/bot_command.dart"; +import "package:nexus/models/bot_command_draft.dart"; +import "package:nexus/models/composer_params.dart"; +import "package:nexus/models/content/bot_command_description.dart"; + +class BotCommandDraftController(final ComposerParams composer) + extends Notifier { + @override + BotCommandDraft? build() => null; + + void start(BotCommand command, {String text = ""}) { + state = BotCommandDraft( + command: command, + composer: composer, + texts: .fromEntries( + command.description.parameters + .where((parameter) => !parameter.optional) + .map( + (parameter) => switch (parameter.schema) { + LiteralSchema(:final value) => MapEntry( + parameter.key, + "$value", + ), + _ => null, + }, + ) + .nonNulls, + ), + ); + focusNext(); + if (state?.focused case final key? when text.isNotEmpty) setText(key, text); + } + + void setText(String key, String text) { + if (state case final draft?) { + state = draft.copyWith(texts: draft.texts.add(key, text)); + } + } + + void focus(String key) => state = state?.copyWith(focused: key); + + void focusNext() { + if (state case final draft?) { + state = draft.copyWith( + focused: draft.missing.firstOrNull?.key ?? draft.focused, + ); + } + } + + void addOption(String key) { + if (state case final draft?) { + state = draft.copyWith(options: draft.options.add(key), focused: key); + } + } + + void removeOption(String key) { + if (state case final draft?) { + state = draft.copyWith( + options: draft.options.remove(key), + texts: draft.texts.remove(key), + // Focus moves back a parameter if none are missing, so it isn't lost + focused: draft.focused == key + ? draft.missing.firstOrNull?.key ?? + draft.shown + .takeWhile((parameter) => parameter.key != key) + .lastOrNull + ?.key + : draft.focused, + ); + } + } + + void pick(BotArgumentSuggestion suggestion, {required ISet via}) { + if (state case BotCommandDraft( + focusedParameter: final parameter?, + :final texts, + :final vias, + )) { + final text = texts[parameter.key] ?? ""; + final isArray = parameter.schema is ArraySchema; + state = state?.copyWith( + texts: texts.add( + parameter.key, + isArray + ? "${text.substring(0, text.lastIndexOf(BotParameterSchema.separator) + 1)}${suggestion.text}, " + : suggestion.text, + ), + vias: via.isEmpty ? vias : vias.add(suggestion.text, via.toIList()), + ); + if (!isArray) focusNext(); + } + } + + void set(BotCommandDraft? draft) => state = draft; + + void clear() => state = null; + + static final provider = + NotifierProvider.family< + BotCommandDraftController, + BotCommandDraft?, + ComposerParams + >(BotCommandDraftController.new); +} diff --git a/lib/controllers/bot_commands.dart b/lib/controllers/bot_commands.dart new file mode 100644 index 0000000..49dc414 --- /dev/null +++ b/lib/controllers/bot_commands.dart @@ -0,0 +1,77 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/gomuks_commands.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/models/bot_command.dart"; +import "package:nexus/models/content/bot_command_description.dart"; +import "package:nexus/models/content/content.dart"; +import "package:nexus/models/content/membership.dart"; +import "package:nexus/models/event.dart"; + +class BotCommandsController(final String roomId) + extends AsyncNotifier> { + @override + Future> build() async { + final gomuksCommands = await ref.watch( + GomuksCommandsController.provider.future, + ); + + final botCommands = ref.watch( + RoomsController.provider.select((rooms) { + final room = rooms[roomId]; + if (room == null) return const IList.empty(); + + Content? membership(String userId) => + switch (room.state[EventType.membership.type]?[userId]) { + final rowId? => room.events[rowId]?.content, + null => null, + }; + + return (room.state[EventType.botCommandDescription.type]?.values ?? + const []) + .map( + (rowId) => switch (room.events[rowId]) { + Event( + redactedBy: null, + :final sender, + content: final BotCommandDescriptionContent description, + ) + when description.isValid && + !BotCommand.builtIn.contains( + description.command.split(" ").first, + ) => + switch (membership(sender)) { + MembershipContent( + status: .join, + :final displayName, + :final avatarUrl, + ) => + BotCommand( + sender: sender, + botName: displayName ?? sender.localpart, + botAvatar: avatarUrl, + description: description, + ), + _ => null, + }, + _ => null, + }, + ) + .nonNulls + .toIList(); + }), + ); + + return gomuksCommands + .addAll(botCommands) + .sortedBy((command) => command.description.command) + .toIList(); + } + + static final provider = AsyncNotifierProvider.autoDispose + .family, String>( + BotCommandsController.new, + ); +} diff --git a/lib/controllers/capabilities.dart b/lib/controllers/capabilities.dart new file mode 100644 index 0000000..3b7a76f --- /dev/null +++ b/lib/controllers/capabilities.dart @@ -0,0 +1,14 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/models/capabilities.dart"; + +class CapabilitiesController extends AsyncNotifier { + @override + Future build() => + ref.read(ClientController.provider.notifier).getCapabilities(); + + static final provider = + AsyncNotifierProvider( + CapabilitiesController.new, + ); +} diff --git a/lib/controllers/client.dart b/lib/controllers/client.dart index 569138f..3a1ac6c 100644 --- a/lib/controllers/client.dart +++ b/lib/controllers/client.dart @@ -1,15 +1,21 @@ import "dart:async"; import "dart:ffi"; import "dart:io"; -import "dart:isolate"; -import "dart:math"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:ffi/ffi.dart"; import "package:flutter/cupertino.dart"; import "package:intl/intl.dart"; +import "package:nexus/controllers/accounts.dart"; +import "package:nexus/controllers/active_account.dart"; +import "package:nexus/controllers/client_state.dart"; import "package:nexus/controllers/settings.dart"; import "package:nexus/helpers/extensions/gomuks_buffer.dart"; +import "package:nexus/helpers/extensions/event_id_is_fake.dart"; +import "package:nexus/helpers/extensions/thread_events.dart"; +import "package:nexus/main.dart"; +import "package:nexus/models/content/bot_command_description.dart"; +import "package:nexus/models/account.dart"; import "package:nexus/models/capabilities.dart"; import "package:nexus/models/content/message.dart"; import "package:nexus/models/event.dart"; @@ -29,7 +35,10 @@ import "package:nexus/models/requests/get_event_context.dart"; import "package:nexus/models/requests/get_mentions.dart"; import "package:nexus/models/requests/get_related_events.dart"; import "package:nexus/models/requests/get_room_state.dart"; +import "package:nexus/models/requests/get_specific_room_state.dart"; import "package:nexus/models/requests/get_space_hierarchy.dart"; +import "package:nexus/models/requests/get_room_directory.dart"; +import "package:nexus/models/requests/get_threads.dart"; import "package:nexus/models/requests/join_room.dart"; import "package:nexus/models/profile_response.dart"; import "package:nexus/models/push_notification.dart"; @@ -48,54 +57,48 @@ import "package:nexus/models/requests/send_message.dart"; import "package:nexus/models/requests/set_account_data.dart"; import "package:nexus/models/requests/set_membership.dart"; import "package:nexus/models/requests/set_state.dart"; +import "package:nexus/models/requests/update_push_rule.dart"; import "package:nexus/models/requests/upload_media.dart"; import "package:nexus/models/room.dart"; +import "package:nexus/models/room_directory.dart"; import "package:nexus/models/room_summary.dart"; import "package:nexus/models/space_hierarchy.dart"; import "package:nexus/models/spec_versions_response.dart"; import "package:nexus/src/third_party/gomuks.g.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:path/path.dart"; import "package:path_provider/path_provider.dart"; -class ClientController extends AsyncNotifier { +class ClientController(final String? accountId) extends AsyncNotifier { @override Future build() async { - debugPrint("Setting Gomuks env..."); - if (Platform.isAndroid || Platform.isIOS) { - final env = { - "GOMUKS_ROOT": (await getApplicationSupportDirectory()).path, - "GOMUKS_CACHE_HOME": (await getApplicationCacheDirectory()).path, - }; - for (final MapEntry(:key, :value) in env.entries) { - final keyPtr = key.toNativeUtf8().cast(); - final valuePtr = value.toNativeUtf8().cast(); - try { - GomuksSetEnv(keyPtr, valuePtr); - } finally { - calloc - ..free(keyPtr) - ..free(valuePtr); - } + final String account = + accountId ?? ref.watch(ActiveAccountController.provider); + if (accountId == null && !isInBackground) await _deleteRemovedAccounts(); + + final environment = await _environment(account); + + debugPrint("Setting Gomuks env for $account..."); + using((arena) { + for (final MapEntry(:key, :value) in environment.entries) { + GomuksSetEnv( + key.toNativeUtf8(allocator: arena).cast(), + value.toNativeUtf8(allocator: arena).cast(), + ); } - } + }, malloc); debugPrint("Initializing Gomuks..."); - final handle = await Isolate.run(() { - final bufferPointer = GomuksConfig( - matrix: .new( - initialDeviceDisplayName: - "Nexus on ${toBeginningOfSentenceCase(Platform.operatingSystem)}", - ), - ).toJson().toGomuksBufferPtr(); - - try { - return GomuksInit(bufferPointer.ref); - } finally { - calloc - ..free(bufferPointer.ref.base) - ..free(bufferPointer); - } - }); + final config = GomuksConfig( + matrix: .new( + initialDeviceDisplayName: + "Nexus on ${toBeginningOfSentenceCase(Platform.operatingSystem)}", + ), + ).toJson(); + final handle = using( + (arena) => GomuksInit(config.toGomuksBufferPtr(arena).ref), + malloc, + ); if (!ref.mounted) { GomuksDestroy(handle); @@ -104,9 +107,60 @@ class ClientController extends AsyncNotifier { ref.onDispose(() => GomuksDestroy(handle)); + if (accountId != null) { + await _callGomuksMethod(handle, {}, GomuksHandlePushAsync); + } + return handle; } + static Future<({Directory data, Directory cache})> + _accountsDirectories() async => ( + data: Directory( + join((await getApplicationSupportDirectory()).path, "accounts"), + ), + cache: Directory( + join((await getApplicationCacheDirectory()).path, "accounts"), + ), + ); + + static Future> _environment(String accountId) async { + if (accountId == Account.legacyId) { + // Keep the directories gomuks used before account switching existed + final isMobile = Platform.isAndroid || Platform.isIOS; + return .new({ + "GOMUKS_ROOT": isMobile + ? (await getApplicationSupportDirectory()).path + : Platform.environment["GOMUKS_ROOT"] ?? "", + "GOMUKS_CACHE_HOME": isMobile + ? (await getApplicationCacheDirectory()).path + : Platform.environment["GOMUKS_CACHE_HOME"] ?? "", + }); + } + + final (:data, :cache) = await _accountsDirectories(); + return .new({ + "GOMUKS_ROOT": join(data.path, accountId), + "GOMUKS_CACHE_HOME": join(cache.path, accountId), + }); + } + + // Can't be done on removal, since the old container still has them open + Future _deleteRemovedAccounts() async { + final ids = (await ref.read(AccountsController.provider.future)) + .map((account) => account.id) + .toISet(); + + final (:data, :cache) = await _accountsDirectories(); + final removed = await Stream.fromIterable([data, cache]) + .where((directory) => directory.existsSync()) + .asyncExpand((directory) => directory.list()) + .where((entry) => !ids.contains(basename(entry.path))) + .toList(); + + await Future.wait(removed.map((entry) => entry.delete(recursive: true))); + } + /// Calls gomuks with [data] as JSON, returning its decoded response. Future callGomuksMethod( Map data, @@ -116,8 +170,18 @@ class ClientController extends AsyncNotifier { Pointer> callback, ) call, - ) async { - final handle = await future; + ) async => _callGomuksMethod(await future, data, call); + + static Future _callGomuksMethod( + int handle, + Map data, + void Function( + int handle, + GomuksOwnedBuffer data, + Pointer> callback, + ) + call, + ) { final buffer = data.toGomuksOwnedBuffer(); final completer = Completer(); @@ -157,66 +221,68 @@ class ClientController extends AsyncNotifier { : .fromJson(response["notification"]); } - Future _sendCommand( + /// Sends [command] to gomuks, returning its decoded response. Overridable so + /// that tests can answer commands without gomuks. + @protected + Future sendCommand( String command, [ Map data = const {}, ]) => callGomuksMethod(data, (handle, data, callback) { - final commandPointer = command.toNativeUtf8().cast(); - try { - GomuksSubmitCommandAsync(handle, commandPointer, data, callback); - } finally { - // gomuks copies the command name before returning - calloc.free(commandPointer); - } + // gomuks copies the command name before returning + using( + (arena) => GomuksSubmitCommandAsync( + handle, + command.toNativeUtf8(allocator: arena).cast(), + data, + callback, + ), + malloc, + ); }); Future redactEvent(RedactEventRequest report) => - _sendCommand("redact_event", report.toJson()); + sendCommand("redact_event", report.toJson()); - Future sendMessage(SendMessageRequest request) async => - Event.fromJson(await _sendCommand("send_message", request.toJson())); + /// Null for gomuks' own commands that don't reply. + Future sendMessage(SendMessageRequest request) async => + switch (await sendCommand("send_message", request.toJson())) { + final Map json => .fromJson(json), + _ => null, + }; - Future sendEvent(SendEventRequest request) async { - final json = request.toJson(); - final content = request.content.toJson(); + /// The MSC4391 definitions of gomuks' own commands. + Future> getCommandDefinitions() async => + switch (await sendCommand("get_command_definitions")) { + final List definitions => .new( + definitions.whereType>().map( + BotCommandDescriptionContent.fromJson, + ), + ), + _ => const .empty(), + }; - return .fromJson( - await _sendCommand("send_event", { - ...json, - "content": { - ...content, - "m.relates_to": { - ...((content["m.relates_to"] as Map?) ?? {}), - "event_id": request.relatesTo, - "rel_type": request.relationType, - }, - }, - }), - ); - } + Future sendEvent(SendEventRequest request) async => + Event.fromJson(await sendCommand("send_event", request.toJson())); Future setState(SetStateRequest request) async => - await _sendCommand("set_state", request.toJson()); + await sendCommand("set_state", request.toJson()); - Future verify(String recoveryKey) async { - try { - await _sendCommand("verify", {"recovery_key": recoveryKey}); - return null; - } catch (error) { - return error.toString(); - } - } + Future pauseSync() => sendCommand("pause_sync"); + Future resumeSync() => sendCommand("resume_sync"); + + Future verify(String recoveryKey) => + sendCommand("verify", {"recovery_key": recoveryKey}); Future generateRecoveryKey(String passphrase) async => .fromJson( - await _sendCommand("generate_recovery_key", {"passphrase": passphrase}), + await sendCommand("generate_recovery_key", {"passphrase": passphrase}), ); Future resetEncryption(RecoveryKey key) => - _sendCommand("reset_encryption", key.toJson()); + sendCommand("reset_encryption", key.toJson()); Future getCrossSigningResetUrl(Uri homeserver) async { const action = "org.matrix.cross_signing_reset"; - final oauth = (await _sendCommand("get_login_flows", { + final oauth = (await sendCommand("get_login_flows", { "homeserver_url": homeserver.toString(), }))["oauth"]; @@ -234,28 +300,33 @@ class ClientController extends AsyncNotifier { } Future joinRoom(JoinRoomRequest request) async => - (await _sendCommand("join_room", request.toJson()))["room_id"]; + (await sendCommand("join_room", request.toJson()))["room_id"]; Future knockRoom(JoinRoomRequest request) async => - (await _sendCommand("knock_room", request.toJson()))["room_id"]; + (await sendCommand("knock_room", request.toJson()))["room_id"]; Future createRoom(CreateRoomRequest request) async => - (await _sendCommand("create_room", request.toJson()))["room_id"]; + (await sendCommand("create_room", request.toJson()))["room_id"]; Future getSpaceHierarchy( GetSpaceHierarchyRequest request, ) async => - .fromJson(await _sendCommand("get_space_hierarchy", request.toJson())); + .fromJson(await sendCommand("get_space_hierarchy", request.toJson())); + + Future getRoomDirectory( + GetRoomDirectoryRequest request, + ) async => + .fromJson(await sendCommand("get_room_directory", request.toJson())); Future getRoomSummary(JoinRoomRequest request) async => - .fromJson(await _sendCommand("get_room_summary", request.toJson())); + .fromJson(await sendCommand("get_room_summary", request.toJson())); Future leaveRoom(String roomId) => - _sendCommand("leave_room", {"room_id": roomId}); + sendCommand("leave_room", {"room_id": roomId}); Future> getRoomState(GetRoomStateRequest request) async { Future getState(GetRoomStateRequest request) async => - (await _sendCommand("get_room_state", request.toJson())) as List?; + (await sendCommand("get_room_state", request.toJson())) as List?; final response = await getState(request); return .new( @@ -265,49 +336,61 @@ class ClientController extends AsyncNotifier { ); } + Future> getSpecificRoomState( + GetSpecificRoomStateRequest request, + ) async => .new( + ((await sendCommand("get_specific_room_state", request.toJson())) + as List? ?? + []) + .map((event) => .fromJson(event)), + ); + Future?> getRelatedEvents( GetRelatedEventsRequest request, ) async { final response = - (await _sendCommand("get_related_events", request.toJson())) as List?; + (await sendCommand("get_related_events", request.toJson())) as List?; return .new(response?.map((event) => .fromJson(event))); } Future getMentions(GetMentionsRequest request) async => - .fromJson(await _sendCommand("get_mentions", request.toJson())); + .fromJson(await sendCommand("get_mentions", request.toJson())); Future getEvent(GetEventRequest request) async { - final json = await _sendCommand("get_event", request.toJson()); + final json = await sendCommand("get_event", request.toJson()); return json == null ? null : .fromJson(json); } Future getUrlPreview(Uri url) async => - .fromJson(await _sendCommand("get_url_preview", {"url": url.toString()})); + .fromJson(await sendCommand("get_url_preview", {"url": url.toString()})); Future paginate(PaginateRequest request) async => - .fromJson(await _sendCommand("paginate", request.toJson())); + .fromJson(await sendCommand("paginate", request.toJson())); + + Future getThreads(GetThreadsRequest request) async => + .fromJson(await sendCommand("get_threads", request.toJson())); Future paginateManual(PaginateManualRequest request) async => - .fromJson(await _sendCommand("paginate_manual", request.toJson())); + .fromJson(await sendCommand("paginate_manual", request.toJson())); Future searchLocal(SearchRequest request) async => - .fromJson(await _sendCommand("search_local", request.toJson())); + .fromJson(await sendCommand("search_local", request.toJson())); Future searchServer(SearchRequest request) async => - .fromJson(await _sendCommand("search_server", request.toJson())); + .fromJson(await sendCommand("search_server", request.toJson())); Future getEventContext(GetEventContextRequest request) async => - .fromJson(await _sendCommand("get_event_context", request.toJson())); + .fromJson(await sendCommand("get_event_context", request.toJson())); Future getProfile(String userId) async { try { - return .fromJson(await _sendCommand("get_profile", {"user_id": userId})); + return .fromJson(await sendCommand("get_profile", {"user_id": userId})); } catch (_) { return .new(profile: .new(id: userId)); } } - Future setProfileField(String field, Object? value) => _sendCommand( + Future setProfileField(String field, Object? value) => sendCommand( "set_profile_field", { "field": field, @@ -317,40 +400,63 @@ class ClientController extends AsyncNotifier { ); Future reportEvent(ReportRequest request) => - _sendCommand("report_event", request.toJson()); + sendCommand("report_event", request.toJson()); Future setMembership(SetMembershipRequest request) => - _sendCommand("set_membership", request.toJson()); + sendCommand("set_membership", request.toJson()); Future setAccountData(SetAccountDataRequest request) => - _sendCommand("set_account_data", request.toJson()); + sendCommand("set_account_data", request.toJson()); + + Future updatePushRule(UpdatePushRuleRequest request) => + sendCommand("update_push_rule", request.toJson()); Future registerPusher(RegisterPusherRequest request) => - _sendCommand("register_homeserver_push", request.toJson()); + sendCommand("register_homeserver_push", request.toJson()); Future deregisterPusher(DeregisterPusherRequest request) => - _sendCommand("register_homeserver_push", { + sendCommand("register_homeserver_push", { ...request.toJson(), "kind": null, }); Future uploadMedia(UploadMediaRequest request) async => - .fromJson(await _sendCommand("upload_media", request.toJson())); + .fromJson(await sendCommand("upload_media", request.toJson())); - Future downloadMedia(DownloadMediaRequest request) async => - .new((await _sendCommand("download_media", request.toJson()))["path"]); + Future downloadMedia(DownloadMediaRequest request) async { + if (accountId == null && + ref.read(ClientStateController.provider)?.isLoggedIn != true) { + throw StateError("Can't download media while logged out"); + } - Future logout() => _sendCommand("logout"); + return .new( + (await sendCommand("download_media", request.toJson()))["path"], + ); + } - Future setTyping(String roomId, Duration timeout) => _sendCommand( + Future logout() => sendCommand("logout"); + + Future setTyping(String roomId, Duration timeout) => sendCommand( "set_typing", {"room_id": roomId, "timeout": timeout.inMilliseconds}, ); - Future markRead(Room room) async { - if (room.timeline.isEmpty || room.metadata == null) return; - final eventRowId = room.timeline[room.timeline.keys.reduce(max)]; - final event = eventRowId == null ? null : room.events[eventRowId]; + Future markRead(Room room, {String? threadRoot}) async { + if (room.metadata == null) return; + final event = switch (threadRoot) { + final threadRoot? => [ + ?room.latestThreadEvent(threadRoot), + ...room.threadEvents(threadRoot).reversed, + ], + null => + room.timeline.entries + .toIList() + .sort((a, b) => b.key.compareTo(a.key)) + .map((entry) => entry.value) + .nonNulls + .map((rowId) => room.events[rowId]) + .nonNulls, + }.where((event) => !event.eventId.isFake).firstOrNull; if (event == null) return; @@ -359,49 +465,72 @@ class ClientController extends AsyncNotifier { ref.read(SettingsController.provider).value?.readReceipts == .showAndSend; - await _sendCommand("mark_read", { + await sendCommand("mark_read", { "room_id": room.metadata!.id, "receipt_type": sendPublic ? "m.read" : "m.read.private", "event_id": event.eventId, + "thread_id": ?threadRoot, }); } Future registerClient(OAuthRegisterClientRequest request) async => - (await _sendCommand( + (await sendCommand( "oauth_register_client", request.toJson(), ))["client_id"]; Future getAuthUrl(OAuthGetAuthUrl request) async => .fromJson( - await _sendCommand("oauth_get_authorization_url", request.toJson()), + await sendCommand("oauth_get_authorization_url", request.toJson()), ); Future exchangeToken(OAuthExchangeTokenRequest request) async => - await _sendCommand("oauth_exchange_token", request.toJson()); + await sendCommand("oauth_exchange_token", request.toJson()); Future> getMutualRooms(String userId) async => IList( - ((await _sendCommand("get_mutual_rooms", {"user_id": userId}))["joined"] + ((await sendCommand("get_mutual_rooms", {"user_id": userId}))["joined"] as List?) ?.cast(), ); Future> getLocalAliases(String roomId) async => IList( - ((await _sendCommand("get_local_aliases", {"room_id": roomId}))["aliases"] + ((await sendCommand("get_local_aliases", {"room_id": roomId}))["aliases"] as List?) ?.cast(), ); Future createAlias(String roomId, String alias) => - _sendCommand("create_alias", {"room_id": roomId, "alias": alias}); + sendCommand("create_alias", {"room_id": roomId, "alias": alias}); Future deleteAlias(String alias) => - _sendCommand("delete_alias", {"alias": alias}); + sendCommand("delete_alias", {"alias": alias}); + + Future getRoomPublished(String roomId) async => + (await sendCommand("get_room_visibility", { + "room_id": roomId, + }))["visibility"] == + "public"; + + Future setRoomPublished(String roomId, bool published) => sendCommand( + "publish_room", + {"room_id": roomId, "visibility": published ? "public" : "private"}, + ); + + Future upgradeRoom( + String roomId, + String version, { + ISet additionalCreators = const .empty(), + }) async => (await sendCommand("upgrade_room", { + "room_id": roomId, + "new_version": version, + if (additionalCreators.isNotEmpty) + "additional_creators": additionalCreators.toList(), + }))["replacement_room"]; /// The room [alias] points to, or null if it doesn't exist. Future resolveAlias(String alias) async { try { - return (await _sendCommand("resolve_alias", {"alias": alias}))["room_id"]; + return (await sendCommand("resolve_alias", {"alias": alias}))["room_id"]; } on GomuksException catch (error) { if (error.statusCode == 404) return null; rethrow; @@ -409,14 +538,14 @@ class ClientController extends AsyncNotifier { } Future getSpecVersions() async => - .fromJson(await _sendCommand("get_versions")); + .fromJson(await sendCommand("get_versions")); Future getCapabilities() async => - .fromJson((await _sendCommand("get_capabilities"))["capabilities"]); + .fromJson((await sendCommand("get_capabilities"))["capabilities"]); Future discoverHomeserver(Uri homeserver) async { try { - final response = await _sendCommand("discover_homeserver", { + final response = await sendCommand("discover_homeserver", { "user_id": "@fake-user:${homeserver.authority}", }); return Uri.parse(response["m.homeserver"]?["base_url"]); @@ -426,6 +555,12 @@ class ClientController extends AsyncNotifier { } static final provider = AsyncNotifierProvider( - ClientController.new, + () => ClientController(null), ); + + /// The instance for an account other than the active one. + static final forAccount = + AsyncNotifierProvider.family( + ClientController.new, + ); } diff --git a/lib/controllers/clock.dart b/lib/controllers/clock.dart new file mode 100644 index 0000000..f9fe690 --- /dev/null +++ b/lib/controllers/clock.dart @@ -0,0 +1,20 @@ +import "dart:async"; + +import "package:flutter_riverpod/flutter_riverpod.dart"; + +class ClockController extends Notifier { + @override + DateTime build() { + final timer = Timer.periodic( + const .new(seconds: 30), + (_) => state = .now(), + ); + ref.onDispose(timer.cancel); + return .now(); + } + + static final provider = + NotifierProvider.autoDispose( + ClockController.new, + ); +} diff --git a/lib/controllers/composer_draft.dart b/lib/controllers/composer_draft.dart new file mode 100644 index 0000000..25ed273 --- /dev/null +++ b/lib/controllers/composer_draft.dart @@ -0,0 +1,97 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/attachment.dart"; +import "package:nexus/controllers/bot_command_draft.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/get_filename.dart"; +import "package:nexus/helpers/extensions/is_media.dart"; +import "package:nexus/helpers/extensions/with_latest_edit.dart"; +import "package:nexus/models/composer_draft.dart"; +import "package:nexus/models/composer_params.dart"; +import "package:nexus/models/content/message.dart"; +import "package:nexus/models/relation_type.dart"; +import "package:nexus/models/text_command.dart"; + +class ComposerDraftController(final ComposerParams composer) + extends Notifier { + @override + ComposerDraft build() => const .new(); + + BotCommandDraftController get _botCommand => + ref.read(BotCommandDraftController.provider(composer).notifier); + + void update(ComposerDraft Function(ComposerDraft draft) update) => + state = update(state); + + void relate(int rowId, RelationType type) { + if (type == .reply) { + _restoreBeforeEdit(); + state = state.copyWith(relatedEvent: rowId, relationType: .reply); + return; + } + + // Keeps the changes made so far + if (state.isEditing && state.relatedEvent == rowId) return; + + final event = ref + .read(RoomsController.provider)[composer.roomId] + ?.withLatestEdit(rowId); + final content = event?.content; + // Edit sources start with text commands, like "/me " + final (:commands, :text) = TextCommand.parse( + event?.localContent?.editSource ?? + switch (content) { + TextMessageContent(:final body) || + ImageMessageContent(:final body) || + VideoMessageContent(:final body) || + AudioMessageContent(:final body) || + FileMessageContent(:final body) => body, + _ => "", + }, + ); + + state = ComposerDraft( + text: text, + textCommands: commands, + relatedEvent: rowId, + relationType: .edit, + beforeEdit: + state.beforeEdit ?? + ( + draft: state, + botCommand: ref.read(BotCommandDraftController.provider(composer)), + ), + ); + ref + .read( + AttachmentController.provider(( + composer: composer, + editingRowId: rowId, + )).notifier, + ) + .set( + content is MessageContent && content.isMedia + ? (content.filename ?? content.body ?? "Attachment", content) + : null, + ); + _botCommand.clear(); + } + + void dismiss() { + if (state.isEditing) return _restoreBeforeEdit(); + state = state.copyWith(relatedEvent: null); + } + + void _restoreBeforeEdit() { + if (state.beforeEdit case (:final draft, :final botCommand)) { + state = draft; + _botCommand.set(botCommand); + } + } + + static final provider = + NotifierProvider.family< + ComposerDraftController, + ComposerDraft, + ComposerParams + >(ComposerDraftController.new); +} diff --git a/lib/controllers/emoji_shortcodes.dart b/lib/controllers/emoji_shortcodes.dart new file mode 100644 index 0000000..a24ebb1 --- /dev/null +++ b/lib/controllers/emoji_shortcodes.dart @@ -0,0 +1,31 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:material_emoji_picker/material_emoji_picker.dart"; + +/// Maps each unicode emoji, without variation selectors, to its shortcode. +class EmojiShortcodesController extends Notifier> { + static final _variationSelectors = RegExp("[\uFE0E\uFE0F]"); + + static String normalize(String emoji) => + emoji.replaceAll(_variationSelectors, ""); + + @override + IMap build() => .fromEntries( + ref + .watch(EmojiController.provider) + .requireValue + .map((category) => category.emojis) + .flattened + .where((emoji) => emoji.aliases.isNotEmpty) + .map( + (emoji) => + MapEntry(normalize(emoji.value), ":${emoji.aliases.first}:"), + ), + ); + + static final provider = + NotifierProvider>( + EmojiShortcodesController.new, + ); +} diff --git a/lib/controllers/enabled_image_packs.dart b/lib/controllers/enabled_image_packs.dart new file mode 100644 index 0000000..c16799c --- /dev/null +++ b/lib/controllers/enabled_image_packs.dart @@ -0,0 +1,69 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/account_data.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/models/content/content.dart"; +import "package:nexus/models/requests/get_specific_room_state.dart"; + +/// The image packs the user has enabled everywhere, as room IDs to their +/// packs' state keys, once the packs' state has been loaded. +class EnabledImagePacksController + extends AsyncNotifier>> { + @override + Future>> build() async { + final enabledPacks = ref.watch( + AccountDataController.provider.select( + (data) => data.enabledImagePacks.rooms.map( + (roomId, packs) => .new(roomId, packs.keys.toISet()), + ), + ), + ); + + const packTypes = [.imagePack, .legacyImagePack]; + // Rooms we aren't in can't be fetched, and fetched rooms have every pack. + final missingKeys = ref.watch( + RoomsController.provider.select( + (rooms) => enabledPacks.entries + .where((entry) => !(rooms[entry.key]?.hasFetchedState ?? true)) + .expand( + (entry) => entry.value + .where( + (stateKey) => packTypes.every( + (type) => + rooms[entry.key]?.state[type.type]?[stateKey] == null, + ), + ) + .expand( + (stateKey) => packTypes.map( + (type) => RoomStateKey( + roomId: entry.key, + type: type.type, + stateKey: stateKey, + ), + ), + ), + ) + .toIList(), + ), + ); + + if (missingKeys.isNotEmpty) { + ref + .read(RoomsController.provider.notifier) + .addSpecificState( + await ref + .read(ClientController.provider.notifier) + .getSpecificRoomState(.new(keys: missingKeys)), + ); + } + + return enabledPacks; + } + + static final provider = + AsyncNotifierProvider.autoDispose< + EnabledImagePacksController, + IMap> + >(EnabledImagePacksController.new); +} diff --git a/lib/controllers/event.dart b/lib/controllers/event.dart index a41d6b6..fc1657f 100644 --- a/lib/controllers/event.dart +++ b/lib/controllers/event.dart @@ -1,22 +1,20 @@ -import "package:collection/collection.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/rooms.dart"; -import "package:nexus/models/event.dart"; import "package:nexus/models/requests/get_event.dart"; +/// The row ID of an event, fetching it if it isn't stored yet. class EventController(final GetEventRequest request) - extends AsyncNotifier { + extends AsyncNotifier { @override - Future build() async { - final room = ref.watch( - RoomsController.provider.select((value) => value[request.roomId]), - ); - final event = room?.events.values.firstWhereOrNull( - (event) => event.eventId == request.eventId, + Future build() async { + final rowId = ref.watch( + RoomsController.provider.select( + (rooms) => rooms[request.roomId]?.eventIds[request.eventId], + ), ); - if (event != null) return event; + if (rowId != null) return rowId; final link = ref.keepAlive(); final fetchedEvent = await ref @@ -41,11 +39,9 @@ class EventController(final GetEventRequest request) ); } - return fetchedEvent; + return fetchedEvent?.rowId; } static final provider = AsyncNotifierProvider.family - .autoDispose( - EventController.new, - ); + .autoDispose(EventController.new); } diff --git a/lib/controllers/gomuks_commands.dart b/lib/controllers/gomuks_commands.dart new file mode 100644 index 0000000..b4276eb --- /dev/null +++ b/lib/controllers/gomuks_commands.dart @@ -0,0 +1,44 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/models/bot_command.dart"; + +class GomuksCommandsController extends AsyncNotifier> { + static const unsupported = ISetConst({ + // Needs gomuks web + "devtools", + "upgraderoom", + + // Needs attachment stuff + "myroomavatar", + "globalavatar", + "roomavatar", + + // Already in Nexus' UI with a better UX + "poll", + }); + + @override + Future> build() async => + (await ref + .read(ClientController.provider.notifier) + .getCommandDefinitions()) + .where( + (description) => + description.isValid && + !unsupported.contains(description.command), + ) + .map( + (description) => BotCommand( + sender: BotCommand.gomuksSender, + botName: "gomuks", + description: description, + ), + ) + .toIList(); + + static final provider = + AsyncNotifierProvider>( + GomuksCommandsController.new, + ); +} diff --git a/lib/controllers/gomuks_listener.dart b/lib/controllers/gomuks_listener.dart index a97599b..3100253 100644 --- a/lib/controllers/gomuks_listener.dart +++ b/lib/controllers/gomuks_listener.dart @@ -3,9 +3,11 @@ import "dart:ffi"; import "dart:io"; import "dart:isolate"; -import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:collection/collection.dart"; import "package:flutter/foundation.dart"; import "package:nexus/controllers/account_data.dart"; +import "package:nexus/controllers/accounts.dart"; +import "package:nexus/controllers/active_account.dart"; import "package:nexus/controllers/app_paused.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; @@ -19,9 +21,7 @@ import "package:nexus/controllers/typing.dart"; import "package:nexus/helpers/extensions/gomuks_buffer.dart"; import "package:nexus/main.dart"; import "package:ffi/ffi.dart"; -import "package:nexus/models/event.dart"; -import "package:nexus/models/events_decrypted.dart"; -import "package:nexus/models/sync_data.dart"; +import "package:nexus/models/gomuks_event.dart"; import "package:nexus/src/third_party/gomuks.g.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; @@ -39,100 +39,43 @@ class GomuksListenerController extends AsyncNotifier { int requestId, GomuksOwnedBuffer data, ) { + final type = command.cast().toDartString(); try { - final muksEventType = command.cast().toDartString(); - debugPrint("Handling $muksEventType..."); - final decodedMuksEvent = data.toJsonAndFree(); - - switch (muksEventType) { - case "client_state": - ref - .read(ClientStateController.provider.notifier) - .set(.fromJson(decodedMuksEvent)); - case "sync_status": - ref - .read(SyncStatusController.provider.notifier) - .set(.fromJson(decodedMuksEvent)); - case "init_complete": + debugPrint("Handling $type..."); + switch (GomuksEvent.parse(type, data.toJsonAndFree())) { + case ClientStateEvent(:final state): + ref.read(ClientStateController.provider.notifier).set(state); + case SyncStatusEvent(:final status): + ref.read(SyncStatusController.provider.notifier).set(status); + case InitCompleteEvent(): ref.read(InitCompleteController.provider.notifier).complete(); - case "send_complete": - final event = Event.fromJson(decodedMuksEvent["event"]); + case SendCompleteEvent(:final event): + ref.read(RoomsController.provider.notifier).storeEvents([ + event, + ]); + case TypingEvent(:final typing): + ref.read(TypingController.provider.notifier).set(typing); + case EventsDecryptedEvent(:final decrypted): ref .read(RoomsController.provider.notifier) - .update( - .new({ - event.roomId: .new(events: .new({event.rowId: event})), - }), - ); - case "typing": + .handleDecrypted(decrypted); + case SyncCompleteEvent(:final sync): + ref.read(RoomsController.provider.notifier).handleSync(sync); ref - .read(TypingController.provider.notifier) - .set(.fromJson(decodedMuksEvent)); - case "events_decrypted": - final decrypted = EventsDecrypted.fromJson(decodedMuksEvent); - final metadata = ref - .read(RoomsController.provider)[decrypted.roomId] - ?.metadata; - + .read(AccountDataController.provider.notifier) + .handleSync(sync); + ref.read(InvitesController.provider.notifier).handleSync(sync); + ref.read(TypingController.provider.notifier).handleSync(sync); ref - .read(RoomsController.provider.notifier) - .update( - .new({ - decrypted.roomId: .new( - events: decrypted.events, - metadata: metadata?.copyWith( - previewEventRowID: - decrypted.previewEventRowID ?? - metadata.previewEventRowID, - sortingTimestamp: - decrypted.sortingTimestamp ?? - metadata.sortingTimestamp, - ), - ), - }), - ); - case "sync_complete": - final syncData = SyncData.fromJson(decodedMuksEvent); - final roomProvider = RoomsController.provider; - final accountDataProvider = AccountDataController.provider; - final invitesProvider = InvitesController.provider; - - if (syncData.clearState) { - ref.invalidate(roomProvider); - ref.invalidate(accountDataProvider); - ref.invalidate(invitesProvider); - ref.invalidate(TypingController.provider); - } - + .read(TopLevelSpacesController.provider.notifier) + .handleSync(sync); ref - .read(roomProvider.notifier) - .update(syncData.rooms, syncData.leftRooms); - ref - .read(accountDataProvider.notifier) - .update(syncData.accountData); - ref - .read(invitesProvider.notifier) - .update( - syncData.invitedRooms, - joinedRooms: syncData.rooms.keys.toISet(), - leftRooms: syncData.leftRooms, - ); - - if (syncData.topLevelSpaces case final topLevelSpaces?) { - ref - .read(TopLevelSpacesController.provider.notifier) - .set(topLevelSpaces); - } - - if (syncData.spaceEdges case final spaceEdges?) { - ref - .read(SpaceEdgesController.provider.notifier) - .set(spaceEdges); - } - default: - debugPrint("Unhandled event: $muksEventType"); + .read(SpaceEdgesController.provider.notifier) + .handleSync(sync); + case UnknownGomuksEvent(): + debugPrint("Unhandled event: $type"); } - debugPrint("Finished handling $muksEventType..."); + debugPrint("Finished handling $type..."); } catch (error, stackTrace) { if (kDebugMode) { debugPrintStack(stackTrace: stackTrace, label: error.toString()); @@ -152,15 +95,55 @@ class GomuksListenerController extends AsyncNotifier { if (!ref.mounted) return; + // Cached so the account switcher and push routing have them while the + // account isn't active + ref.listen( + ClientStateController.provider.select( + (state) => (state?.isInitialized, state?.userId, state?.deviceId), + ), + (_, ids) => Future(() async { + final id = ref.read(ActiveAccountController.provider); + final accounts = ref.read(AccountsController.provider.notifier); + + switch (ids) { + // Logged out, so it shouldn't show as an account anymore + case (true, null, _): + await accounts.reset(id); + case (_, final userId?, final deviceId): + final previous = (await ref.read( + AccountsController.provider.future, + )).firstWhereOrNull((account) => account.id == id); + final profile = + (await ref + .read(ClientController.provider.notifier) + .getProfile(userId)) + .profile; + + // Fetching the profile fails while offline, so keep what was cached + await accounts.save( + .new( + id: id, + userId: userId, + deviceId: deviceId, + displayName: profile.displayName ?? previous?.displayName, + avatar: profile.avatarUrl ?? previous?.avatar, + ), + ); + } + }).catchError(showError), + fireImmediately: true, + ); + if (Platform.isAndroid || Platform.isIOS) { // Mobile OSes block network access for backgrounded apps, so pause // syncing instead of letting it fail. ref.listen(AppPausedController.provider, (_, paused) { + final client = ref.read(ClientController.provider.notifier); if (paused) { - GomuksPauseSync(handle); + client.pauseSync().onError(showError); } else { ref.invalidate(TypingController.provider); - GomuksResumeSync(handle); + client.resumeSync().onError(showError); } }, fireImmediately: true); } diff --git a/lib/controllers/image_pack_sources.dart b/lib/controllers/image_pack_sources.dart new file mode 100644 index 0000000..61e4a2e --- /dev/null +++ b/lib/controllers/image_pack_sources.dart @@ -0,0 +1,75 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/enabled_image_packs.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/controllers/space_edges.dart"; + +typedef ImagePackSource = ({String roomId, String? stateKey}); + +class ImagePackSourcesController(final String roomId) + extends AsyncNotifier> { + @override + Future> build() async { + final enabledPacksFuture = ref.watch( + EnabledImagePacksController.provider.future, + ); + final spaceEdges = ref.watch(SpaceEdgesController.provider); + final directParents = ref.watch( + RoomsController.provider.select( + (rooms) => + rooms[roomId]?.state["m.space.parent"]?.keys.toISet() ?? + const .empty(), + ), + ); + + Iterable parentsOf(String childId) => spaceEdges.entries + .where((entry) => entry.value.any((edge) => edge.childId == childId)) + .map((entry) => entry.key) + .followedBy(childId == roomId ? directParents : const []); + + ISet withAncestors(ISet spaces, String childId) => + parentsOf(childId).fold( + spaces, + (spaces, parentId) => spaces.contains(parentId) + ? spaces + : withAncestors(spaces.add(parentId), parentId), + ); + + final rooms = ref.read(RoomsController.provider); + final spaces = withAncestors( + const .empty(), + roomId, + ).remove(roomId).where(rooms.containsKey).toIList(); + + final client = ref.read(ClientController.provider.notifier); + final roomsNotifier = ref.read(RoomsController.provider.notifier); + + await Future.wait( + spaces + .where((spaceId) => !rooms[spaceId]!.hasFetchedState) + .map( + (spaceId) async => roomsNotifier.addState( + spaceId, + await client.getRoomState(.new(roomId: spaceId)), + ), + ), + ); + final enabledPacks = await enabledPacksFuture; + + return .new([ + (roomId: roomId, stateKey: null), + ...spaces.map((spaceId) => (roomId: spaceId, stateKey: null)), + ...enabledPacks.entries.expand( + (entry) => entry.value.map( + (stateKey) => (roomId: entry.key, stateKey: stateKey), + ), + ), + ]); + } + + static final provider = AsyncNotifierProvider.autoDispose + .family, String>( + ImagePackSourcesController.new, + ); +} diff --git a/lib/controllers/image_packs.dart b/lib/controllers/image_packs.dart new file mode 100644 index 0000000..9248211 --- /dev/null +++ b/lib/controllers/image_packs.dart @@ -0,0 +1,43 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/image_pack_sources.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/room_image_packs.dart"; +import "package:nexus/models/image_pack.dart"; + +class ImagePacksController(final String roomId) + extends AsyncNotifier> { + @override + Future> build() async { + final sources = await ref.watch( + ImagePackSourcesController.provider(roomId).future, + ); + + final packs = ref.watch( + RoomsController.provider.select( + (rooms) => sources.expand((source) { + final packs = + rooms[source.roomId]?.imagePacks(source.roomId) ?? const .empty(); + + return switch (source.stateKey) { + final stateKey? => [?packs[stateKey]], + null => packs.values, + }; + }).toIList(), + ), + ); + + return .new( + packs + .whereNoDuplicates(by: (pack) => pack.id) + .where( + (pack) => pack.emoticons.isNotEmpty || pack.stickers.isNotEmpty, + ), + ); + } + + static final provider = AsyncNotifierProvider.autoDispose + .family, String>( + ImagePacksController.new, + ); +} diff --git a/lib/controllers/invites.dart b/lib/controllers/invites.dart index 3effbf9..42821ac 100644 --- a/lib/controllers/invites.dart +++ b/lib/controllers/invites.dart @@ -1,5 +1,6 @@ import "package:collection/collection.dart"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/experimental/mutation.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; @@ -16,6 +17,7 @@ import "package:nexus/models/content/name.dart"; import "package:nexus/models/content/topic.dart"; import "package:nexus/models/invited_room.dart"; import "package:nexus/models/room_summary.dart"; +import "package:nexus/models/sync_data.dart"; /// Pending invites, newest first. class InvitesController extends Notifier> { @@ -102,6 +104,15 @@ class InvitesController extends Notifier> { .removeWhere((invite) => removed.contains(invite.roomId)); } + void handleSync(SyncData sync) { + if (sync.clearState) state = .new(); + update( + sync.invitedRooms, + joinedRooms: sync.rooms.keys.toISet(), + leftRooms: sync.leftRooms, + ); + } + void remove(String roomId) => state = state.removeWhere((invite) => invite.roomId == roomId); @@ -115,6 +126,10 @@ class InvitesController extends Notifier> { Future declineAll() => Future.wait(state.map((invite) => decline(invite.roomId))); + /// Accepting or declining an invite, keyed by its room ID + static final respondMutation = Mutation(); + static final declineAllMutation = Mutation(); + static final provider = NotifierProvider>( InvitesController.new, diff --git a/lib/controllers/key.dart b/lib/controllers/key.dart index 33c76da..d0ea054 100644 --- a/lib/controllers/key.dart +++ b/lib/controllers/key.dart @@ -1,23 +1,38 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/active_account.dart"; import "package:nexus/controllers/shared_prefs.dart"; +import "package:nexus/models/account.dart"; class KeyController(final String key) extends AsyncNotifier { static const String spaceKey = "space"; static const String roomKey = "room"; static const String pushKeyKey = "pushKey"; + static const String accountsKey = "accounts"; + static const String activeAccountKey = "activeAccount"; + + static const ISet _perAccountKeys = ISetConst({spaceKey, roomKey}); + + String get _prefsKey { + final account = ref.read(ActiveAccountController.provider); + + return _perAccountKeys.contains(key) && account != Account.legacyId + ? "$account/$key" + : key; + } @override Future build() => - ref.watch(SharedPrefsController.provider).getString(key); + ref.watch(SharedPrefsController.provider).getString(_prefsKey); Future set(String? value) async { final prefs = ref.read(SharedPrefsController.provider); state = .data(value); if (value == null) { - await prefs.remove(key); + await prefs.remove(_prefsKey); } else { - await prefs.setString(key, value); + await prefs.setString(_prefsKey, value); } } diff --git a/lib/controllers/link_request.dart b/lib/controllers/link_request.dart new file mode 100644 index 0000000..0d7e7c2 --- /dev/null +++ b/lib/controllers/link_request.dart @@ -0,0 +1,21 @@ +import "package:app_links/app_links.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/helpers/extensions/get_link_info.dart"; + +class LinkRequestController extends Notifier { + @override + LinkInfo? build() { + final subscription = AppLinks().uriLinkStream.listen((uri) { + if (uri.toString().linkInfo case final linkInfo?) state = linkInfo; + }); + ref.onDispose(subscription.cancel); + + return null; + } + + void consume() => state = null; + + static final provider = NotifierProvider( + LinkRequestController.new, + ); +} diff --git a/lib/controllers/notification.dart b/lib/controllers/notification.dart index 47ecdf0..e8a5dff 100644 --- a/lib/controllers/notification.dart +++ b/lib/controllers/notification.dart @@ -4,12 +4,12 @@ import "dart:io"; import "package:flutter/services.dart"; import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/active_account.dart"; import "package:nexus/controllers/portal.dart"; import "package:nexus/controllers/sidebar_page.dart"; import "package:nexus/main.dart"; import "package:flutter_local_notifications/flutter_local_notifications.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:nexus/controllers/notification_request.dart"; import "package:nexus/models/push_notification.dart"; import "package:xdg_desktop_portal/xdg_desktop_portal.dart"; @@ -41,17 +41,7 @@ class NotificationController macOS: darwin, ), onDidReceiveNotificationResponse: (details) { - if (details.payload == null) return; - - if (int.tryParse(details.payload!) case final rowId?) { - navigatorKey.currentState?.popUntil((route) => route.isFirst); - ref - .read(SidebarPageController.provider.notifier) - .set(.notifications); - ref - .read(NotificationRequestController.provider.notifier) - .request(rowId); - } + if (details.payload case final payload?) _open(payload); }, ); } @@ -64,21 +54,36 @@ class NotificationController return; } - if (int.tryParse(call.arguments) case int rowId) { - navigatorKey.currentState?.popUntil((route) => route.isFirst); - ref.read(SidebarPageController.provider.notifier).set(.notifications); - ref - .read(NotificationRequestController.provider.notifier) - .request(rowId); - } + if (call.arguments case final String payload) _open(payload); }); - - ref.onDispose(() => notificationChannel.setMethodCallHandler(null)); } return notifications; } + static String payloadFor(String accountId, int rowId) => "$accountId:$rowId"; + + void _open(String payload) { + final (accountId, rowId) = switch (payload.split(":")) { + [final accountId, final rowId] => (accountId, int.tryParse(rowId)), + // From before notifications were per account + [final rowId] => (null, int.tryParse(rowId)), + _ => (null, null), + }; + if (rowId == null) return; + + navigatorKey.currentState?.popUntil((route) => route.isFirst); + ref.read(SidebarPageController.provider.notifier).set(.notifications); + + ref + .read(ActiveAccountController.provider.notifier) + .switchTo( + accountId ?? ref.read(ActiveAccountController.provider), + notificationRowId: rowId, + ) + .onError(showError); + } + Future requestPermissions() async { if (Platform.isLinux) { return true; @@ -149,10 +154,12 @@ class NotificationController } /// Passing [message] shows it as a chat message in the conversation for - /// [threadId], naming the sender in group chats. + /// [threadId], naming the sender in group chats. [subtitle] is shown on + /// platforms that support it. Future send({ required int id, required String title, + String? subtitle, required String body, String? payload, String? threadId, @@ -169,7 +176,7 @@ class NotificationController if (Platform.isLinux) { final portal = await ref.read(PortalController.provider.future); - const escape = HtmlEscape(HtmlEscapeMode.element); + const escape = HtmlEscape(.element); await portal.notification.addNotification( id.toString(), @@ -208,6 +215,7 @@ class NotificationController : null; final darwin = DarwinNotificationDetails( + subtitle: subtitle, presentSound: sound, threadIdentifier: threadId, ); @@ -222,6 +230,7 @@ class NotificationController ? .new( "general", "General", + subText: subtitle, silent: !sound, when: timestamp?.millisecondsSinceEpoch, largeIcon: icon == null @@ -232,6 +241,7 @@ class NotificationController : .new( "messages", "Messages", + subText: subtitle, silent: !sound, when: timestamp?.millisecondsSinceEpoch, category: .message, diff --git a/lib/controllers/pinned_events.dart b/lib/controllers/pinned_events.dart index d0d7bb5..16456fc 100644 --- a/lib/controllers/pinned_events.dart +++ b/lib/controllers/pinned_events.dart @@ -13,7 +13,7 @@ class PinnedEventsController(final String roomId) pinIds.map( (eventId) => ref.watch( EventController.provider(.new(eventId: eventId, roomId: roomId)) - .selectAsync((data) => data?.rowId), + .future, ), ), )).nonNulls.toIList(); diff --git a/lib/controllers/poll_votes.dart b/lib/controllers/poll_votes.dart new file mode 100644 index 0000000..c881a0c --- /dev/null +++ b/lib/controllers/poll_votes.dart @@ -0,0 +1,132 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/room_power_levels.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/event_id_is_fake.dart"; +import "package:nexus/models/configs/event.dart"; +import "package:nexus/models/content/content.dart"; +import "package:nexus/models/content/encrypted.dart"; +import "package:nexus/models/content/poll_end.dart"; +import "package:nexus/models/content/poll_response.dart"; +import "package:nexus/models/content/poll_start.dart"; +import "package:nexus/models/event.dart"; +import "package:nexus/models/poll_votes.dart"; + +class PollVotesController(final EventConfig config) + extends AsyncNotifier { + @override + Future build() async { + // Only what's needed, so e.g. reactions don't cause refetches + final (poll, localRelated) = ref.watch( + RoomsController.provider.select((rooms) { + final room = rooms[config.roomId]; + final event = room?.events[config.eventRowId]; + if (room == null || event == null) { + return (null, const IList.empty()); + } + + final edited = event.lastEditRowId == 0 + ? null + : room.events[event.lastEditRowId]; + + return ( + ( + eventId: event.eventId, + sender: event.sender, + // Edits can change the answers + content: (edited ?? event).content, + ), + (room.relations[event.eventId] ?? const ISet.empty()) + .map((rowId) => room.events[rowId]) + .nonNulls + .where((related) => related.relationType == "m.reference") + .toIList(), + ); + }), + ); + final powerLevels = ref.watch( + RoomPowerLevelsController.provider(config.roomId), + ); + + if (poll == null) return const PollVotes(); + final PollStart(:answers, :selectionLimit) = switch (poll.content) { + PollStartContent(:final poll) => poll, + _ => const PollStart(), + }; + + final fetched = await ref + .read(ClientController.provider.notifier) + .getRelatedEvents( + .new( + roomId: config.roomId, + eventId: poll.eventId, + relationType: "m.reference", + ), + ); + + final related = + IMap.fromIterable( + (fetched ?? const IList.empty()).addAll(localRelated), + keyMapper: (event) => event.rowId, + valueMapper: (event) => event, + ).values + // gomuks' database has unsent local echoes too + .where((event) => event.redactedBy == null && !event.eventId.isFake) + .toIList(); + + final end = related + .where( + (event) => + event.content is PollEndContent && + powerLevels.canEndPoll(event.sender, pollSender: poll.sender), + ) + .sortedBy((event) => event.timestamp) + .firstOrNull; + final endedAt = end?.timestamp; + + bool beforeEnd(Event event) => + endedAt == null || !event.timestamp.isAfter(endedAt); + + final answerIds = answers.map((answer) => answer.id).toISet(); + + return .new( + endEventId: end?.eventId, + undecryptable: related + .where( + (event) => event.content is EncryptedContent && beforeEnd(event), + ) + .length, + // Each user's latest response before the end counts, even if invalid + votes: related + .where( + (event) => + event.type == EventType.pollResponse.type && beforeEnd(event), + ) + .toIList() + .sort((a, b) => a.timestamp.compareTo(b.timestamp)) + .fold(const .empty(), (votes, event) { + // Truncated before removing duplicates, as MSC3381 specifies + final picked = switch (event.content) { + PollResponseContent(:final answers) => + answers.take(selectionLimit).toISet(), + _ => null, + }; + + return votes.add( + event.sender, + // Spoiled responses count as no answers + picked != null && picked.every(answerIds.contains) + ? picked.toIList() + : const .empty(), + ); + }), + ); + } + + static final provider = AsyncNotifierProvider.family + .autoDispose( + PollVotesController.new, + ); +} diff --git a/lib/controllers/reactions.dart b/lib/controllers/reactions.dart index b3584c8..662661c 100644 --- a/lib/controllers/reactions.dart +++ b/lib/controllers/reactions.dart @@ -1,14 +1,18 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/emoji_shortcodes.dart"; import "package:nexus/controllers/rooms.dart"; -import "package:nexus/models/configs/reactions.dart"; +import "package:nexus/models/configs/event.dart"; import "package:nexus/models/content/reaction.dart"; +import "package:nexus/models/reaction_group.dart"; -class ReactionsController(final ReactionsConfig config) - extends AsyncNotifier>> { +class ReactionsController(final EventConfig config) + extends AsyncNotifier> { @override - Future>> build() async { + Future> build() async { + final unicodeShortcodes = ref.watch(EmojiShortcodesController.provider); + final eventInfo = ref.watch( RoomsController.provider.select((value) { final event = value[config.roomId]?.events[config.eventRowId]; @@ -30,12 +34,25 @@ class ReactionsController(final ReactionsConfig config) return reactionEvents ?.where((event) => event.redactedBy == null) - .fold>>(.new(), (acc, event) { - if (event.content case ReactionContent(:final key?)) { + .fold>(.new(), (acc, event) { + if (event.content case ReactionContent( + :final key?, + :final shortcode, + )) { return acc.update( key, - (list) => list.add(event.sender), - ifAbsent: () => .new([event.sender]), + (group) => group.copyWith( + senders: group.senders.add(event.sender), + shortcode: group.shortcode ?? shortcode, + ), + ifAbsent: () => .new( + senders: .new([event.sender]), + shortcode: + shortcode ?? + unicodeShortcodes[EmojiShortcodesController.normalize( + key, + )], + ), ); } @@ -47,7 +64,7 @@ class ReactionsController(final ReactionsConfig config) static final provider = AsyncNotifierProvider.family< ReactionsController, - IMap>, - ReactionsConfig + IMap, + EventConfig >(ReactionsController.new); } diff --git a/lib/controllers/read_receipts.dart b/lib/controllers/read_receipts.dart index 15f76aa..4dba46c 100644 --- a/lib/controllers/read_receipts.dart +++ b/lib/controllers/read_receipts.dart @@ -32,7 +32,12 @@ class ReadReceiptsController(final ChatParams chat) final room = ref.watch( RoomsController.provider.select( (rooms) => switch (rooms[chat.roomId]) { - final room? => (events: room.events, receipts: room.receipts), + final room? => ( + events: room.events, + eventIds: room.eventIds, + receipts: room.receipts, + timeline: room.timeline, + ), null => null, }, ), @@ -50,15 +55,48 @@ class ReadReceiptsController(final ChatParams chat) .toIList(); final messageIndexes = messages.map((entry) => entry.$1).toList(); + final positions = IMap.fromEntries( + room.timeline.entries + .map( + (entry) => switch (entry.value) { + final rowId? => MapEntry(rowId, entry.key), + null => null, + }, + ) + .nonNulls, + ); + final placed = events.indexed + .map( + (entry) => switch (positions[entry.$2.rowId]) { + final position? => (index: entry.$1, position: position), + null => null, + }, + ) + .nonNulls + .toList(); + final placedPositions = placed.map((entry) => entry.position).toList(); + + int? indexOf(String eventId) { + if (indexes[eventId] case final index?) return index; + + final position = switch (room.eventIds[eventId]) { + final rowId? => positions[rowId], + null => null, + }; + if (position == null) return null; + + final before = lowerBound(placedPositions, position + 1) - 1; + return before < 0 ? null : placed[before].index; + } + return room.receipts.values.flattened .where( (receipt) => receipt.userId != userId && - // Receipts in threads are for the thread, not the timeline - receipt.thread == "main", + receipt.thread == (chat.threadRoot ?? "main"), ) .map( - (receipt) => switch (indexes[receipt.eventId]) { + (receipt) => switch (indexOf(receipt.eventId)) { final index? => ( receipt: receipt, message: lowerBound(messageIndexes, index + 1) - 1, diff --git a/lib/controllers/recent_emoji.dart b/lib/controllers/recent_emoji.dart index 8dd3e59..a091afb 100644 --- a/lib/controllers/recent_emoji.dart +++ b/lib/controllers/recent_emoji.dart @@ -23,7 +23,13 @@ class RecentEmojiController extends Notifier> { ), ); - return .new(recents.where((recent) => emoji.contains(recent.emoji))); + return .new( + recents.where( + (recent) => + // Is unicode or custom emote + emoji.contains(recent.emoji) || recent.emoji.startsWith("mxc://"), + ), + ); } Future add(String emoji) => ref diff --git a/lib/controllers/room_chat.dart b/lib/controllers/room_chat.dart index b8b688d..2a53a0d 100644 --- a/lib/controllers/room_chat.dart +++ b/lib/controllers/room_chat.dart @@ -7,18 +7,37 @@ import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:fluttertagger/fluttertagger.dart"; import "package:nexus/controllers/attachment.dart"; import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/event.dart"; import "package:nexus/controllers/rooms.dart"; +import "package:nexus/controllers/thread_replies.dart"; +import "package:nexus/helpers/extensions/is_media.dart"; +import "package:nexus/helpers/extensions/send_failed.dart"; +import "package:nexus/helpers/extensions/thread_events.dart"; +import "package:nexus/models/bot_command_draft.dart"; +import "package:nexus/models/composer_params.dart"; +import "package:nexus/models/content/bot_command.dart"; import "package:nexus/models/content/content.dart"; +import "package:nexus/models/content/image_pack.dart"; +import "package:nexus/models/content/poll_end.dart"; +import "package:nexus/models/content/poll_response.dart"; +import "package:nexus/models/content/poll_start.dart"; import "package:nexus/models/content/reaction.dart"; +import "package:nexus/models/content/sticker.dart"; import "package:nexus/models/direction.dart"; import "package:nexus/models/event.dart"; +import "package:nexus/models/paginate_manual.dart"; import "package:nexus/models/requests/redact_event.dart"; import "package:nexus/models/relation_type.dart"; +import "package:nexus/models/content/message.dart"; import "package:nexus/models/requests/send_message.dart"; import "package:nexus/models/room.dart"; import "package:nexus/models/room_chat.dart"; -typedef ChatParams = ({String roomId, int? contextualEvent}); +typedef ChatParams = ({ + String roomId, + int? contextualEvent, + String? threadRoot, +}); class RoomChatController(final ChatParams info) extends AsyncNotifier { @@ -37,52 +56,173 @@ class RoomChatController(final ChatParams info) ref.read(RoomsController.provider.notifier).addState(info.roomId, state); } - final timeline = room.timeline - .toEntryIList(compare: (a, b) => (a?.key ?? 0).compareTo(b?.key ?? 0)) - .map((e) => e.value) - .toIList() - .addAll(room.clientSticky) - .nonNulls - .toIList(); - if (info.contextualEvent == null || - timeline.contains(info.contextualEvent)) { - ref.watch( - RoomsController.provider.select( - (rooms) => - (rooms[info.roomId]?.timeline, rooms[info.roomId]?.clientSticky), - ), + if (info.threadRoot case final threadRoot? + when info.contextualEvent == null) { + final nextBatch = await ref.watch( + ThreadRepliesController.provider(( + roomId: info.roomId, + threadRoot: threadRoot, + )).future, ); return .new( - timeline: timeline, - hasMoreBackward: room.hasMore, + timeline: ref.watch(RoomsController.provider.select(threadTimeline)), + hasMoreBackward: nextBatch != null, hasMoreForward: false, ); - } else { - final context = await client.getEventContext( - .new( - roomId: info.roomId, - eventId: room.events[info.contextualEvent!]!.eventId, - ), - ); + } - // `before` is in reverse chronological order - final events = context.before.reversed + if (info.threadRoot == null) { + final timeline = room.timeline + .toEntryIList(compare: (a, b) => (a?.key ?? 0).compareTo(b?.key ?? 0)) + .map((e) => e.value) .toIList() - .add(context.event) - .addAll(context.after); + .addAll(room.clientSticky) + .nonNulls + // Threads are shown from their root instead + .where((rowId) => room.events[rowId]?.threadRoot == null) + .toIList(); + + if (info.contextualEvent == null || + timeline.contains(info.contextualEvent)) { + ref.watch( + RoomsController.provider.select( + (rooms) => ( + rooms[info.roomId]?.timeline, + rooms[info.roomId]?.clientSticky, + ), + ), + ); + + return .new( + timeline: timeline, + hasMoreBackward: room.hasMore, + hasMoreForward: false, + ); + } + } + + final context = await client.getEventContext( + .new( + roomId: info.roomId, + eventId: room.events[info.contextualEvent!]!.eventId, + ), + ); + + final contextEvents = context.before.reversed + .toIList() + .add(context.event) + .addAll(context.after); + ref + .read(RoomsController.provider.notifier) + .storeEvents(contextEvents.addAll(context.relatedEvents)); + + if (info.threadRoot case final threadRoot?) { + final (older, newer) = await ( + client.paginateManual( + .new( + roomId: info.roomId, + threadRoot: threadRoot, + since: context.start, + direction: .backward, + ), + ), + client.paginateManual( + .new( + roomId: info.roomId, + threadRoot: threadRoot, + since: context.end, + direction: .forward, + ), + ), + ).wait; + final rootRowId = await threadRootBefore(older); ref .read(RoomsController.provider.notifier) - .storeEvents(events.addAll(context.relatedEvents)); + .storeEvents( + older.events + .addAll(older.relatedEvents) + .addAll(newer.events) + .addAll(newer.relatedEvents), + ); + return .new( - timeline: .new(events.map((element) => element.rowId)), - hasMoreBackward: true, - hasMoreForward: true, - historicalData: .new(start: context.start, end: context.end), + timeline: .new([?rootRowId]) + .addAll( + // Paginating backwards gives the newest first + older.events.reversed + .addAll( + contextEvents.where( + (event) => event.threadRoot == threadRoot, + ), + ) + .addAll(newer.events) + .map((event) => event.rowId), + ) + .removeDuplicates(), + hasMoreBackward: older.nextBatch != null, + hasMoreForward: newer.nextBatch != null, + historicalData: .new( + start: older.nextBatch ?? "", + end: newer.nextBatch ?? "", + ), ); } + + return .new( + timeline: .new( + contextEvents + .where((event) => event.threadRoot == null) + .map((event) => event.rowId), + ), + hasMoreBackward: true, + hasMoreForward: true, + historicalData: .new(start: context.start, end: context.end), + ); } + /// The thread's root, which comes before all of its events, if paginating + /// backwards to [older] reached the start of the thread. + Future threadRootBefore(PaginateManual older) async => + switch (info.threadRoot) { + final threadRoot? when older.nextBatch == null => await ref.read( + EventController.provider( + .new(roomId: info.roomId, eventId: threadRoot), + ).future, + ), + _ => null, + }; + + /// The thread's root, then its events, if this is a thread's chat. + IList threadTimeline(IMap rooms) => + switch ((rooms[info.roomId], info.threadRoot)) { + (final room?, final threadRoot?) => .new([ + ?room.eventIds[threadRoot], + ...room.threadEvents(threadRoot).map((event) => event.rowId), + ]), + _ => const .empty(), + }; + + Relation? replyRelation(Event? replied) => + switch (info.threadRoot ?? replied?.threadRoot) { + null => + replied == null + ? null + : .new(eventId: replied.eventId, relationType: .reply), + final threadRoot => .new( + eventId: + replied?.eventId ?? + ref + .read(RoomsController.provider)[info.roomId] + ?.latestThreadEvent(threadRoot) + ?.eventId ?? + threadRoot, + relationType: .reply, + threadRoot: threadRoot, + isFallingBack: replied == null, + ), + }; + Future deleteMessage(Event event, {String? reason}) => ref .read(ClientController.provider.notifier) .redactEvent( @@ -123,97 +263,132 @@ class RoomChatController(final ChatParams info) return; } + if ((info.threadRoot, chat) case (final threadRoot?, final chat?) + when chat.historicalData == null) { + return ref + .read( + ThreadRepliesController.provider(( + roomId: info.roomId, + threadRoot: threadRoot, + )).notifier, + ) + .loadOlder(); + } + state = .loading(); final client = ref.read(ClientController.provider.notifier); - if (chat?.historicalData == null) { - final timelineKeys = ref - .read(RoomsController.provider.select((value) => value[info.roomId])) - ?.timeline - .keys; - final response = await client.paginate( - .new( - roomId: info.roomId, - maxTimelineId: timelineKeys?.isNotEmpty == true - ? timelineKeys?.reduce(min) - : null, - ), - ); + try { + if (chat?.historicalData == null) { + final timelineKeys = ref + .read( + RoomsController.provider.select((value) => value[info.roomId]), + ) + ?.timeline + .keys; + final response = await client.paginate( + .new( + roomId: info.roomId, + maxTimelineId: timelineKeys?.isNotEmpty == true + ? timelineKeys?.reduce(min) + : null, + ), + ); + if (!ref.mounted) return; - if (response.events.isEmpty) { - state = .data(chat); - } + if (response.events.isEmpty) { + state = .data(chat); + } - ref - .read(RoomsController.provider.notifier) - .update( - IMap({ - info.roomId: Room( - events: IMap.fromIterable( - response.events.addAll(response.relatedEvents), - keyMapper: (event) => event.rowId, - valueMapper: (event) => event, - ), - hasMore: response.hasMore, - receipts: response.receipts, - timeline: IMap.fromIterable( - response.events, - keyMapper: (event) => event.timelineRowId, - valueMapper: (event) => event.rowId, + ref + .read(RoomsController.provider.notifier) + .update( + .new({ + info.roomId: .new( + // ignore: unused_result - I am using it you donkey + events: .fromIterable( + response.events.addAll(response.relatedEvents), + keyMapper: (event) => event.rowId, + valueMapper: (event) => event, + ), + hasMore: response.hasMore, + receipts: response.receipts, + // ignore: unused_result - I am using it you donkey + timeline: .fromIterable( + response.events, + keyMapper: (event) => event.timelineRowId, + valueMapper: (event) => event.rowId, + ), ), + }), + ); + } else { + final paginationResponse = await client.paginateManual( + .new( + roomId: info.roomId, + threadRoot: info.threadRoot, + direction: direction, + since: direction == .forward + ? chat!.historicalData!.end + : chat!.historicalData!.start, + ), + ); + if (!ref.mounted) return; + + ref + .read(RoomsController.provider.notifier) + .storeEvents( + paginationResponse.events.addAll( + paginationResponse.relatedEvents, ), - }), - ); - } else { - final paginationResponse = await client.paginateManual( - .new( - roomId: info.roomId, - direction: direction, - since: direction == .forward - ? chat!.historicalData!.end - : chat!.historicalData!.start, - ), - ); + ); - ref - .read(RoomsController.provider.notifier) - .storeEvents( - paginationResponse.events.addAll(paginationResponse.relatedEvents), - ); - - final eventRowIds = - (direction == .forward + final rootRowId = direction == .backward + ? await threadRootBefore(paginationResponse) + : null; + if (!ref.mounted) return; + final eventRowIds = [ + ?rootRowId, + ...(direction == .forward ? paginationResponse.events : paginationResponse.events.reversed) - .map((element) => element.rowId) - .toIList(); + .where((event) => event.threadRoot == info.threadRoot) + .map((element) => element.rowId), + ].lock; - state = .data( - .new( - timeline: direction == .forward - ? chat.timeline.addAll(eventRowIds) - : eventRowIds.addAll(chat.timeline), - hasMoreForward: - direction == .forward && paginationResponse.nextBatch == null - ? false - : chat.hasMoreForward, - hasMoreBackward: - direction == .backward && paginationResponse.nextBatch == null - ? false - : chat.hasMoreBackward, - historicalData: chat.historicalData?.copyWith( - start: - (direction == .backward - ? paginationResponse.nextBatch - : null) ?? - chat.historicalData!.start, - end: - (direction == .forward ? paginationResponse.nextBatch : null) ?? - chat.historicalData!.end, + state = .data( + .new( + timeline: direction == .forward + ? chat.timeline.addAll(eventRowIds) + : eventRowIds.addAll(chat.timeline), + hasMoreForward: + direction == .forward && paginationResponse.nextBatch == null + ? false + : chat.hasMoreForward, + hasMoreBackward: + direction == .backward && paginationResponse.nextBatch == null + ? false + : chat.hasMoreBackward, + historicalData: chat.historicalData?.copyWith( + start: + (direction == .backward + ? paginationResponse.nextBatch + : null) ?? + chat.historicalData!.start, + end: + (direction == .forward + ? paginationResponse.nextBatch + : null) ?? + chat.historicalData!.end, + ), ), - ), - ); + ); + } + } catch (_) { + if (!ref.mounted) return; + state = .data(chat); + rethrow; } } @@ -224,34 +399,42 @@ class RoomChatController(final ChatParams info) required RelationType relationType, int? relatedEventRowId, }) async { - Content? baseContent; + final events = ref.read(RoomsController.provider)[info.roomId]?.events; final relatedEvent = relatedEventRowId == null ? null - : ref.read( - RoomsController.provider.select( - (rooms) => rooms[info.roomId]?.events[relatedEventRowId], - ), - ); + : events?[relatedEventRowId]; - if (relationType == .edit && relatedEventRowId != null) { - baseContent = relatedEvent?.content; - } else { - final provider = AttachmentController.provider(info.roomId); - baseContent = ref.read(provider)?.$2; - ref.invalidate(provider); - } + final ComposerParams composer = ( + roomId: info.roomId, + threadRoot: info.threadRoot, + ); + final attachmentProvider = AttachmentController.provider(( + composer: composer, + editingRowId: relationType == .edit ? relatedEventRowId : null, + )); + final attachment = ref.read(attachmentProvider)?.$2; + ref.invalidate(attachmentProvider); - var taggedMessage = text; + // Edits of media use the attachment, which starts as the current media + final latestContent = relatedEvent == null + ? null + : (events?[relatedEvent.lastEditRowId] ?? relatedEvent).content; + final baseContent = + attachment ?? + (relationType == .edit && latestContent?.isMedia == false + ? latestContent + : null); - for (final tag in tags) { - final escaped = RegExp.escape(tag.id); - final pattern = RegExp(r"@+(" + escaped + r")(#[^#]*#)?"); - - taggedMessage = taggedMessage.replaceAllMapped( - pattern, + // Replaces each formatted tag, like ":id#name#", with its ID + final taggedMessage = tags.fold( + text, + (message, tag) => message.replaceAllMapped( + RegExp( + "${RegExp.escape(tag.triggerCharacter)}(${RegExp.escape(tag.id)})(#[^#]*#)?", + ), (match) => match.group(1)!, - ); - } + ), + ); final client = ref.read(ClientController.provider.notifier); final event = await client.sendMessage( @@ -266,22 +449,29 @@ class RoomChatController(final ChatParams info) room: taggedMessage.contains("@room"), ), text: taggedMessage, - relation: relatedEvent == null - ? null - : .new(eventId: relatedEvent.eventId, relationType: relationType), + relation: relationType == .edit && relatedEvent != null + ? .new(eventId: relatedEvent.eventId, relationType: .edit) + : replyRelation(relatedEvent), ), ); - ref - .read(RoomsController.provider.notifier) - .update( - .new({ - info.roomId: .new( - events: .new({event.rowId: event}), - clientSticky: .new({event.rowId}), - ), - }), - ); + addSent(event); + } + + /// Shows [event], which was just sent, until it comes down sync. + void addSent(Event? event) { + if (event case final event?) { + ref + .read(RoomsController.provider.notifier) + .update( + .new({ + info.roomId: .new( + events: .new({event.rowId: event}), + clientSticky: .new({event.rowId}), + ), + }), + ); + } } Future removeReaction( @@ -315,14 +505,24 @@ class RoomChatController(final ChatParams info) } } - Future sendReaction(String reaction, Event event) async { + /// Reacts to [event] with [reaction], which is an mxc URL for custom emoji, + /// with their [shortcode]. + Future sendReaction( + String reaction, + Event event, { + String? shortcode, + }) async { final client = ref.read(ClientController.provider.notifier); await client.sendEvent( .new( roomId: info.roomId, type: EventType.reaction.type, - content: ReactionContent(key: reaction), + // Wrapped in colons, like other clients send it + content: ReactionContent( + key: reaction, + shortcode: shortcode == null ? null : ":$shortcode:", + ), synchronous: true, disableEncryption: true, relatesTo: event.eventId, @@ -331,6 +531,143 @@ class RoomChatController(final ChatParams info) ); } + /// Sends [content], as a reply to [repliedEventRowId] if set. + Future sendWithReply( + EventType type, + Content content, { + bool shouldMention = true, + int? repliedEventRowId, + }) async { + final repliedEvent = repliedEventRowId == null + ? null + : ref.read( + RoomsController.provider.select( + (rooms) => rooms[info.roomId]?.events[repliedEventRowId], + ), + ); + + final event = await ref + .read(ClientController.provider.notifier) + .sendEvent( + .new( + roomId: info.roomId, + type: type.type, + content: content, + mentions: Mentions( + userIds: [ + if (shouldMention && repliedEvent != null) repliedEvent.sender, + ].toIList(), + ), + reply: replyRelation(repliedEvent), + ), + ); + + addSent(event); + } + + /// Sends [image] as a sticker, as a reply to [repliedEventRowId] if set. + Future sendSticker( + String shortcode, + PackImage image, { + bool shouldMention = true, + int? repliedEventRowId, + }) => sendWithReply( + .sticker, + StickerContent( + body: image.body ?? shortcode, + info: image.info ?? const .new(), + url: image.url, + ), + shouldMention: shouldMention, + repliedEventRowId: repliedEventRowId, + ); + + Future sendPoll( + PollStart poll, { + bool shouldMention = true, + int? repliedEventRowId, + }) => sendWithReply( + .pollStart, + PollStartContent(poll: poll), + shouldMention: shouldMention, + repliedEventRowId: repliedEventRowId, + ); + + Future sendLocation( + LocationMessageContent location, { + bool shouldMention = true, + int? repliedEventRowId, + }) => sendWithReply( + .message, + location, + shouldMention: shouldMention, + repliedEventRowId: repliedEventRowId, + ); + + Future sendBotCommand( + BotCommandDraft draft, { + int? repliedEventRowId, + }) async { + final repliedEvent = repliedEventRowId == null + ? null + : ref + .read(RoomsController.provider)[info.roomId] + ?.events[repliedEventRowId]; + + final event = await ref + .read(ClientController.provider.notifier) + .sendMessage( + .new( + roomId: info.roomId, + text: "", + baseContent: BotCommandMessageContent( + body: draft.body, + command: draft.input, + ), + mentions: .new(userIds: [draft.command.sender].lock), + relation: replyRelation(repliedEvent), + ), + ); + + addSent(event); + } + + /// Completes once the event has come down sync. + Future sendPollReference( + Event poll, + EventType type, + Content content, + ) async { + // The end event lands in the timeline and rebuilds this, so no ref after awaiting + final rooms = ref.read(RoomsController.provider.notifier); + final event = await ref + .read(ClientController.provider.notifier) + .sendEvent( + .new( + roomId: info.roomId, + type: type.type, + content: content, + relatesTo: poll.eventId, + relationType: "m.reference", + synchronous: true, + ), + ); + + if (event.sendFailed) throw Exception(event.sendError); + + await rooms.awaitEvent(info.roomId, event.eventId); + } + + /// An empty [answers] removes the vote. + Future votePoll(Event poll, IList answers) => sendPollReference( + poll, + .pollResponse, + PollResponseContent(answers: answers), + ); + + Future endPoll(Event poll) => + sendPollReference(poll, .pollEnd, const PollEndContent()); + static final provider = AsyncNotifierProvider.family .autoDispose( RoomChatController.new, diff --git a/lib/controllers/room_directory.dart b/lib/controllers/room_directory.dart new file mode 100644 index 0000000..8d6e498 --- /dev/null +++ b/lib/controllers/room_directory.dart @@ -0,0 +1,39 @@ +import "package:flutter_riverpod/experimental/mutation.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/models/room_directory.dart"; + +/// The public room directory of a server, or of the user's own if null. +class RoomDirectoryController(final String? server) + extends AsyncNotifier { + @override + Future build() => ref + .read(ClientController.provider.notifier) + .getRoomDirectory(.new(server: server)); + + Future loadMore() async { + final current = await future; + if (current.nextBatch == null) return; + + final next = await ref + .read(ClientController.provider.notifier) + .getRoomDirectory(.new(server: server, since: current.nextBatch)); + + if (!ref.mounted) return; + + state = AsyncData( + current.copyWith( + rooms: current.rooms.addAll(next.rooms), + nextBatch: next.nextBatch, + ), + ); + } + + /// Loading the next page of a directory, keyed by its server + static final loadMoreMutation = Mutation(); + + static final provider = AsyncNotifierProvider.family + .autoDispose( + RoomDirectoryController.new, + ); +} diff --git a/lib/controllers/room_image_packs.dart b/lib/controllers/room_image_packs.dart new file mode 100644 index 0000000..318d388 --- /dev/null +++ b/lib/controllers/room_image_packs.dart @@ -0,0 +1,37 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/room_image_packs.dart"; +import "package:nexus/models/image_pack.dart"; + +/// The image packs in [roomId]'s own state by state key, loading its state if +/// it hasn't been yet. +class RoomImagePacksController(final String roomId) + extends AsyncNotifier> { + @override + Future> build() async { + if (ref.read(RoomsController.provider)[roomId] case final room? + when !room.hasFetchedState) { + ref + .read(RoomsController.provider.notifier) + .addState( + roomId, + await ref + .read(ClientController.provider.notifier) + .getRoomState(.new(roomId: roomId)), + ); + } + + return ref.watch( + RoomsController.provider.select( + (rooms) => rooms[roomId]?.imagePacks(roomId) ?? const .empty(), + ), + ); + } + + static final provider = AsyncNotifierProvider.autoDispose + .family, String>( + RoomImagePacksController.new, + ); +} diff --git a/lib/controllers/room_power_levels.dart b/lib/controllers/room_power_levels.dart index e33c436..7001eec 100644 --- a/lib/controllers/room_power_levels.dart +++ b/lib/controllers/room_power_levels.dart @@ -1,6 +1,7 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/room_version_at_least.dart"; import "package:nexus/models/content/content.dart"; import "package:nexus/models/content/create.dart"; import "package:nexus/models/content/power_levels.dart"; @@ -26,8 +27,7 @@ class RoomPowerLevelsController(final String roomId) _ => null, }; // Creators only outrank everyone from room version 12, earlier ones just have a power level - final creatorsPrivileged = - (int.tryParse(create?.roomVersion ?? "") ?? 0) >= 12; + final creatorsPrivileged = (create?.roomVersion).versionAtLeast(12); return .new( content: switch (stateEvent(.powerLevels)?.content) { diff --git a/lib/controllers/room_published.dart b/lib/controllers/room_published.dart new file mode 100644 index 0000000..b560575 --- /dev/null +++ b/lib/controllers/room_published.dart @@ -0,0 +1,21 @@ +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:nexus/controllers/client.dart"; + +/// Whether a room is published to the user's server's room directory. +class RoomPublishedController(final String roomId) extends AsyncNotifier { + @override + Future build() => + ref.read(ClientController.provider.notifier).getRoomPublished(roomId); + + Future set(bool published) async { + await ref + .read(ClientController.provider.notifier) + .setRoomPublished(roomId, published); + ref.invalidateSelf(); + } + + static final provider = AsyncNotifierProvider.family + .autoDispose( + RoomPublishedController.new, + ); +} diff --git a/lib/controllers/room_settings_sections.dart b/lib/controllers/room_settings_sections.dart index 583f0f9..bababee 100644 --- a/lib/controllers/room_settings_sections.dart +++ b/lib/controllers/room_settings_sections.dart @@ -2,15 +2,19 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/controllers/local_aliases.dart"; import "package:nexus/controllers/power_level.dart"; import "package:nexus/controllers/power_levels_saving.dart"; +import "package:nexus/controllers/room_image_packs.dart"; import "package:nexus/controllers/room_power_levels.dart"; +import "package:nexus/controllers/room_published.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/space_edges.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; +import "package:nexus/helpers/extensions/join_rule_name.dart"; +import "package:nexus/helpers/extensions/room_version_at_least.dart"; import "package:nexus/helpers/file_dialog_helper.dart"; import "package:nexus/helpers/hooks/saving.dart"; import "package:nexus/main.dart"; @@ -20,25 +24,31 @@ import "package:nexus/models/content/content.dart"; import "package:nexus/models/content/create.dart"; import "package:nexus/models/content/encryption.dart"; import "package:nexus/models/content/history_visibility.dart"; +import "package:nexus/models/content/image_pack.dart"; import "package:nexus/models/content/join_rules.dart"; import "package:nexus/models/content/membership.dart"; import "package:nexus/models/content/message.dart"; import "package:nexus/models/content/name.dart"; import "package:nexus/models/content/power_levels.dart"; +import "package:nexus/models/content/tombstone.dart"; import "package:nexus/models/content/topic.dart"; import "package:nexus/models/join_rule.dart"; +import "package:nexus/models/power_level_permission.dart"; import "package:nexus/models/setting.dart"; import "package:nexus/models/settings_category.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; -import "package:nexus/widgets/divider_text.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/common/divider_text.dart"; +import "package:nexus/widgets/avatars/image_pack_avatar.dart"; import "package:nexus/widgets/settings/add_users_power_level_sheet.dart"; import "package:nexus/widgets/settings/aliases_sheet.dart"; import "package:nexus/widgets/settings/allowed_rooms_sheet.dart"; import "package:nexus/widgets/settings/dialog_list_tile.dart"; +import "package:nexus/widgets/settings/image_pack_sheet.dart"; import "package:nexus/widgets/settings/local_aliases_sheet.dart"; import "package:nexus/widgets/settings/power_level_entry_sheet.dart"; import "package:nexus/widgets/settings/power_level_tile.dart"; import "package:nexus/widgets/settings/text_setting_tile.dart"; +import "package:nexus/widgets/settings/upgrade_room_sheet.dart"; class RoomSettingsSectionsController(final String roomId) extends AsyncNotifier>> { @@ -89,6 +99,7 @@ class RoomSettingsSectionsController(final String roomId) final canSetJoinRules = canSet(.joinRules); final canSetHistoryVisibility = canSet(.historyVisibility); final canSetAliases = canSet(.canonicalAlias); + final canCreatePacks = canSet(.imagePack); final canSetPowerLevels = canSet(.powerLevels) && !ref.watch(PowerLevelsSavingController.provider(roomId)); @@ -114,18 +125,18 @@ class RoomSettingsSectionsController(final String roomId) ?canonicalAlias.alias, ]).toISet(); - final roomVersion = switch (stateContent(.create)) { - CreateContent(:final roomVersion) => int.tryParse(roomVersion), + final versionName = switch (stateContent(.create)) { + CreateContent(:final roomVersion) => roomVersion, _ => null, }; - bool versionAtLeast(int version) => - roomVersion == null || roomVersion >= version; + final canUpgrade = + canSet(.tombstone) && stateContent(.tombstone) is! TombstoneContent; final joinRuleOptions = [ JoinRule.public, JoinRule.invite, - if (versionAtLeast(7)) JoinRule.knock, - if (versionAtLeast(8)) JoinRule.restricted, - if (versionAtLeast(10)) JoinRule.knockRestricted, + if (versionName.versionAtLeast(7)) JoinRule.knock, + if (versionName.versionAtLeast(8)) JoinRule.restricted, + if (versionName.versionAtLeast(10)) JoinRule.knockRestricted, ]; bool isRestricted(JoinRule rule) => rule == .restricted || rule == .knockRestricted; @@ -156,20 +167,81 @@ class RoomSettingsSectionsController(final String roomId) ClientStateController.provider.select((state) => state?.userId), ); final ownLevel = userId == null ? 0.0 : roomPowerLevels.levelOf(userId); - // Encrypted rooms send messages as m.room.encrypted, so that's what limits them - final messageType = stateContent(.encryption) is EncryptionContent - ? EventType.encrypted - : EventType.message; + final encrypted = stateContent(.encryption) is EncryptionContent; + final shownEvents = PowerLevelEvent.shownIn(encrypted: encrypted); - Future setState(EventType type, Content content) async { + Future setState( + EventType type, + Content content, { + String stateKey = "", + }) async { final eventId = await client.setState( - .new(roomId: roomId, type: type.type, stateKey: "", content: content), + .new( + roomId: roomId, + type: type.type, + stateKey: stateKey, + content: content, + ), ); if (eventId case final eventId?) { - await roomsController.awaitState(roomId, type.type, eventId); + await roomsController.awaitState( + roomId, + type.type, + eventId, + stateKey: stateKey, + ); } } + final imagePacks = + ref.watch(RoomImagePacksController.provider(roomId)).value ?? + const .empty(); + + // Pack sheets can stay open while the state changes, so these read it when + // called, rather than using the state from building + IMap> currentState() => + ref.read(RoomsController.provider)[roomId]?.state ?? const .empty(); + + // Whether the legacy type still has a pack at [stateKey], to clear it + bool hasLegacyPack(String stateKey) => + switch (currentState()[EventType.legacyImagePack.type]?[stateKey]) { + final rowId? => switch (contentOf(rowId)) { + final ImagePackContent content => content.hasContent, + _ => false, + }, + null => false, + }; + final canSetLegacyPacks = canSet(.legacyImagePack); + + /// Saves the pack at [stateKey] as the stable type, migrating it by + /// clearing its legacy event if it has one. + Future setPack(String stateKey, Content content) async { + await setState(.imagePack, content, stateKey: stateKey); + if (hasLegacyPack(stateKey)) { + await setState(.legacyImagePack, const .new(), stateKey: stateKey); + } + } + + /// A state key for a new pack named [name]. It's one no pack has ever + /// had, even deleted ones, as users may still have those enabled. + String newPackKey(String name) { + final state = currentState(); + final usedKeys = [ + EventType.imagePack, + EventType.legacyImagePack, + ].expand((type) => state[type.type]?.keys ?? []).toISet(); + final slug = name + .toLowerCase() + .replaceAll(RegExp(r"[^\p{L}\p{N}_-]+", unicode: true), "_") + .replaceAll(RegExp(r"^_+|_+$"), ""); + final base = slug.isEmpty ? "pack" : slug; + + return Iterable.generate( + usedKeys.length + 1, + (index) => index == 0 ? base : "${base}_${index + 1}", + ).firstWhere((key) => !usedKeys.contains(key)); + } + Future setAliases( String? canonical, ISet alternatives, @@ -218,12 +290,10 @@ class RoomSettingsSectionsController(final String roomId) .run(() => setState(.powerLevels, content).onError(showError)); // Event types with their own level that don't have a setting of their own - final listedEvents = [ - messageType, - EventType.sticker, - EventType.reaction, - EventType.pinnedEvents, - ].map((type) => type.type).toISet(); + final listedEvents = shownEvents + .addAll(PowerLevelGroup.values.expand((group) => group.events)) + .map((event) => event.type.type) + .toISet(); final otherEvents = powerLevels.events.entries .where((entry) => !listedEvents.contains(entry.key)) .toIList() @@ -288,20 +358,94 @@ class RoomSettingsSectionsController(final String roomId) ), ); - /// A setting for the level needed to send [type], which otherwise needs [fallback]. - Setting eventSetting( - EventType type, { - required String title, - required String description, - required IconData icon, - required int fallback, - }) => powerLevelSetting( - title: title, - description: description, - icon: icon, - value: powerLevels.events[type.type] ?? fallback, - update: (level) => powerLevels.copyWith( - events: powerLevels.events.add(type.type, level), + Setting permissionSetting(PowerLevelPermission permission) => + powerLevelSetting( + title: permission.title, + description: permission.description, + icon: permission.icon, + value: permission.levelIn(powerLevels), + update: (level) => permission.withLevel(powerLevels, level), + ); + + /// A setting for the level needed to send [event], which otherwise needs [fallback]. + Setting eventSetting(PowerLevelEvent event, {required int fallback}) => + powerLevelSetting( + title: event.title, + description: event.description, + icon: event.icon, + value: powerLevels.events[event.type.type] ?? fallback, + update: (level) => powerLevels.copyWith( + events: powerLevels.events.add(event.type.type, level), + ), + ); + + Widget tileOf(Setting setting) => + setting.builder(setting.title, setting.description, setting.icon); + + /// A setting for all of [group]'s levels at once, which expands to set each. + Setting groupSetting(PowerLevelGroup group) => .new( + title: group.title, + description: group.description, + icon: group.icon, + builder: (title, description, icon) => HookBuilder( + builder: (context) { + final expanded = useState(false); + + return Column( + mainAxisSize: .min, + children: [ + PowerLevelTile( + leading: Icon(icon), + title: title, + description: description, + value: group.levelIn(powerLevels), + ownLevel: ownLevel, + // Changing it would change levels above the user's own + onChanged: + canSetPowerLevels && + group.highestIn(powerLevels) <= ownLevel + ? (level) => + setPowerLevels(group.withLevel(powerLevels, level)) + : null, + trailing: IconButton( + tooltip: expanded.value ? "Collapse" : "Set each", + icon: AnimatedRotation( + turns: expanded.value ? 0.5 : 0, + duration: Durations.medium2, + child: Icon(Icons.expand_more), + ), + onPressed: () => expanded.value = !expanded.value, + ), + ), + AnimatedSize( + duration: Durations.medium2, + curve: Curves.easeInOut, + alignment: .topCenter, + child: expanded.value + ? Padding( + padding: .only(left: 16), + child: Column( + mainAxisSize: .min, + children: [ + ...group.permissions + .map(permissionSetting) + .map(tileOf), + ...group.events + .map( + (event) => eventSetting( + event, + fallback: powerLevels.stateDefault, + ), + ) + .map(tileOf), + ], + ), + ) + : const SizedBox(width: .infinity), + ), + ], + ); + }, ), ); @@ -415,6 +559,84 @@ class RoomSettingsSectionsController(final String roomId) : null, ), ), + .new( + title: "Publish to Room Directory", + description: "List the room in your homeserver's directory.", + icon: Icons.travel_explore, + builder: (title, description, icon) => HookConsumer( + builder: (context, ref, _) { + final saving = Saving.use(); + final published = ref.watch( + RoomPublishedController.provider(roomId), + ); + + return SwitchListTile( + secondary: Icon(icon), + title: Text(title), + subtitle: Text(description), + value: published.value ?? false, + onChanged: + canSetAliases && published.hasValue && !saving.active + ? (value) => saving.run( + () => ref + .read( + RoomPublishedController.provider(roomId) + .notifier, + ) + .set(value) + .onError(showError), + ) + : null, + ); + }, + ), + ), + .new( + title: "Room Version", + description: "The rules the room follows, set when it's created.", + icon: Icons.upgrade, + builder: (title, description, icon) => HookBuilder( + builder: (context) { + final saving = Saving.use(); + + return ListTile( + leading: Icon(icon), + title: Text(title), + subtitle: Text( + versionName == null + ? description + : "Version $versionName", + ), + trailing: TextButton( + onPressed: + canUpgrade && versionName != null && !saving.active + ? () => context.showAdaptiveSheet( + (_) => UpgradeRoomSheet( + roomId: roomId, + currentVersion: versionName, + creators: roomPowerLevels.creators.remove( + userId ?? "", + ), + userId: userId, + onSave: (version, creators) => saving.run( + () => client + .upgradeRoom( + roomId, + version, + additionalCreators: creators, + ) + .then((_) {}) + .onError(showError), + ), + ), + ) + : null, + child: Text("Upgrade"), + ), + ); + }, + ), + ), ]), ), .new( @@ -431,14 +653,7 @@ class RoomSettingsSectionsController(final String roomId) subtitle: Text(description), value: joinRules.joinRule, options: joinRuleOptions, - getName: (rule) => switch (rule) { - .public => "Public", - .invite => "Invite only", - .knock => "Knock", - .restricted => "Restricted", - .knockRestricted => "Restricted or knock", - .private => "Private", - }, + getName: (rule) => rule.displayName, onChanged: canSetJoinRules ? (rule) => setState( .joinRules, @@ -598,6 +813,7 @@ class RoomSettingsSectionsController(final String roomId) .invited => "After invite", .joined => "After join", .worldReadable => "Anyone", + .unknown => "Unknown", }, onChanged: canSetHistoryVisibility ? (visibility) => setState( @@ -615,13 +831,7 @@ class RoomSettingsSectionsController(final String roomId) title: "Permissions", icon: Icons.admin_panel_settings, settings: .new([ - powerLevelSetting( - title: "Default Power Level", - description: "The power level of users who aren't given one.", - icon: Icons.person, - value: powerLevels.usersDefault, - update: (level) => powerLevels.copyWith(usersDefault: level), - ), + permissionSetting(.usersDefault), header("Users", "Power levels of specific users.", Icons.group), ...users.map((entry) { final member = memberOf(entry.key); @@ -682,87 +892,31 @@ class RoomSettingsSectionsController(final String roomId) ), ), ), + header( + "Groups", + "Power levels set together, which can each be set on their own.", + Icons.workspaces, + ), + ...PowerLevelGroup.values.map(groupSetting), header( "Regular Events", "Power levels needed to send messages and other timeline events.", Icons.chat, ), - eventSetting( - messageType, - title: "Send Messages", - description: "The power level needed to send messages.", - icon: Icons.message, - fallback: powerLevels.eventsDefault, - ), - eventSetting( - .sticker, - title: "Send Stickers", - description: "The power level needed to send stickers.", - icon: Icons.sticky_note_2, - fallback: powerLevels.eventsDefault, - ), - eventSetting( - .reaction, - title: "Send Reactions", - description: "The power level needed to react to messages.", - icon: Icons.add_reaction, - fallback: powerLevels.eventsDefault, - ), - powerLevelSetting( - title: "Default for Events", - description: - "The power level needed to send events without their own.", - icon: Icons.more_horiz, - value: powerLevels.eventsDefault, - update: (level) => powerLevels.copyWith(eventsDefault: level), - ), + ...shownEvents + .where((event) => event != .pinnedEvents) + .map( + (event) => + eventSetting(event, fallback: powerLevels.eventsDefault), + ), + permissionSetting(.eventsDefault), header( "State Events", - "Power levels needed to manage members and change the room's state.", + "Power levels needed to change the room's state.", Icons.settings, ), - eventSetting( - .pinnedEvents, - title: "Pin Messages", - description: "The power level needed to pin messages.", - icon: Icons.push_pin, - fallback: powerLevels.stateDefault, - ), - powerLevelSetting( - title: "Invite Users", - description: "The power level needed to invite users.", - icon: Icons.person_add, - value: powerLevels.invite, - update: (level) => powerLevels.copyWith(invite: level), - ), - powerLevelSetting( - title: "Kick Users", - description: "The power level needed to kick users.", - icon: Icons.sports_martial_arts, - value: powerLevels.kick, - update: (level) => powerLevels.copyWith(kick: level), - ), - powerLevelSetting( - title: "Ban Users", - description: "The power level needed to ban and unban users.", - icon: Icons.gavel, - value: powerLevels.ban, - update: (level) => powerLevels.copyWith(ban: level), - ), - powerLevelSetting( - title: "Delete Others' Messages", - description: "The power level needed to remove others' messages.", - icon: Icons.delete, - value: powerLevels.redact, - update: (level) => powerLevels.copyWith(redact: level), - ), - powerLevelSetting( - title: "Default for State Events", - description: "The power level needed to send state events without their own.", - icon: Icons.tune, - value: powerLevels.stateDefault, - update: (level) => powerLevels.copyWith(stateDefault: level), - ), + permissionSetting(.invite), + permissionSetting(.stateDefault), header( "Other Events", "Power levels for specific event types.", @@ -813,6 +967,90 @@ class RoomSettingsSectionsController(final String roomId) ), ]), ), + .new( + title: "Image Packs", + icon: Icons.emoji_emotions, + settings: .new([ + ...imagePacks.entries.map((entry) { + final stateKey = entry.key; + final pack = entry.value; + final canEdit = + canCreatePacks && + (canSetLegacyPacks || !hasLegacyPack(stateKey)); + + return Setting( + title: pack.name, + description: pack.imageCountLabel, + icon: Icons.emoji_emotions, + builder: (title, description, _) => HookBuilder( + key: ValueKey(stateKey), + builder: (context) { + final saving = Saving.use(); + + return ListTile( + enabled: !saving.active, + leading: ImagePackAvatar(pack.icon), + title: Text(title), + subtitle: Text(description), + onTap: () => context.showAdaptiveSheet( + (_) => ImagePackSheet( + title: canEdit ? "Edit Image Pack" : title, + content: pack.content, + onSave: canEdit + ? (content) => saving.run( + () => setPack( + stateKey, + content, + ).onError(showError), + ) + : null, + onDeleted: canEdit + ? () => saving.run( + () => setPack( + stateKey, + const .new(), + ).onError(showError), + ) + : null, + ), + ), + ); + }, + ), + ); + }), + .new( + title: "Create Pack", + description: "Add a pack of emoticons and stickers to the room.", + icon: Icons.add, + builder: (title, description, icon) => HookBuilder( + builder: (context) { + final saving = Saving.use(); + + return ListTile( + enabled: canCreatePacks && !saving.active, + leading: Icon(icon), + title: Text(title), + subtitle: Text(description), + onTap: () => context.showAdaptiveSheet( + (_) => ImagePackSheet( + title: "Create Pack", + content: const .new(), + onSave: (content) => saving.run( + () => setState( + .imagePack, + content, + stateKey: newPackKey(content.pack!.displayName!), + ).onError(showError), + ), + ), + ), + ); + }, + ), + ), + ]), + ), ]), }); } diff --git a/lib/controllers/rooms.dart b/lib/controllers/rooms.dart index 5370bcf..66ffa3b 100644 --- a/lib/controllers/rooms.dart +++ b/lib/controllers/rooms.dart @@ -4,36 +4,44 @@ import "package:collection/collection.dart"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/models/event.dart"; +import "package:nexus/models/events_decrypted.dart"; import "package:nexus/models/read_receipt.dart"; import "package:nexus/models/room.dart"; +import "package:nexus/models/sync_data.dart"; class RoomsController extends Notifier> { @override IMap build() => .new(); - void addState( - String roomId, - IList state, { - bool isMembers = false, - }) => update( - .new({ - roomId: Room( - events: .fromEntries(state.map((event) => .new(event.rowId, event))), - hasFetchedState: true, - hasFetchedMembers: isMembers, - state: .new( - state - .groupListsBy((event) => event.type) - .map( - (type, group) => .new( - type, - .fromEntries(group.map((e) => .new(e.stateKey!, e.rowId))), - ), - ), - ), - ), - }), - .new(), + void addState(String roomId, IList state, {bool isMembers = false}) => + update( + .new({ + roomId: stateRoom(state) + .copyWith(hasFetchedState: true, hasFetchedMembers: isMembers), + }), + .new(), + ); + + void addSpecificState(Iterable state) => update( + .new( + state + .groupListsBy((event) => event.roomId) + .map((roomId, roomState) => .new(roomId, stateRoom(roomState))), + ), + ); + + static Room stateRoom(Iterable state) => Room( + events: .fromEntries(state.map((event) => .new(event.rowId, event))), + state: .new( + state + .groupListsBy((event) => event.type) + .map( + (type, group) => .new( + type, + .fromEntries(group.map((e) => .new(e.stateKey!, e.rowId))), + ), + ), + ), ); static IMap> mergeReceipts( @@ -76,6 +84,58 @@ class RoomsController extends Notifier> { ), ); + void handleSync(SyncData sync) { + if (sync.clearState) state = .new(); + update(sync.rooms, sync.leftRooms); + } + + void handleDecrypted(EventsDecrypted decrypted) { + final metadata = state[decrypted.roomId]?.metadata; + + update( + .new({ + decrypted.roomId: .new( + events: decrypted.events, + metadata: metadata?.copyWith( + previewEventRowID: + decrypted.previewEventRowID ?? metadata.previewEventRowID, + sortingTimestamp: + decrypted.sortingTimestamp ?? metadata.sortingTimestamp, + ), + ), + }), + ); + } + + static IMap> addRelations( + IMap> relations, + Iterable events, + ) => events.fold( + relations, + (acc, event) => switch (event.relatesTo) { + final relatesTo? => acc.update( + relatesTo, + (rowIds) => rowIds.add(event.rowId), + ifAbsent: () => .new([event.rowId]), + ), + null => acc, + }, + ); + + /// IDs replace previous ones for the same row, e.g. once a local echo is sent. + static IMap addEventIds( + IMap eventIds, + IMap existing, + Iterable events, + ) => events.fold(eventIds, (acc, event) { + final previousId = existing[event.rowId]?.eventId; + + return (previousId != null && previousId != event.eventId + ? acc.remove(previousId) + : acc) + .add(event.eventId, event.rowId); + }); + void update( IMap rooms, [ ISet leftRooms = const .empty(), @@ -103,6 +163,15 @@ class RoomsController extends Notifier> { events: incoming.events.isEmpty ? existing.events : existing.events.addAll(incoming.events), + relations: addRelations( + existing.relations, + incoming.events.values, + ), + eventIds: addEventIds( + existing.eventIds, + existing.events, + incoming.events.values, + ), state: incoming.state.entries.fold( existing.state, (previousValue, event) => previousValue.add( @@ -123,6 +192,12 @@ class RoomsController extends Notifier> { ) ?? incoming.copyWith( receipts: mergeReceipts(const .empty(), incoming.receipts), + relations: addRelations(const .empty(), incoming.events.values), + eventIds: addEventIds( + const .empty(), + const .empty(), + incoming.events.values, + ), ), ); }); @@ -138,12 +213,19 @@ class RoomsController extends Notifier> { String type, String eventId, { String stateKey = "", - }) { - bool arrived(IMap rooms) => - switch (rooms[roomId]?.state[type]?[stateKey]) { - final rowId? => rooms[roomId]?.events[rowId]?.eventId == eventId, - null => false, - }; + }) => awaitRooms( + (rooms) => switch (rooms[roomId]?.state[type]?[stateKey]) { + final rowId? => rooms[roomId]?.events[rowId]?.eventId == eventId, + null => false, + }, + ); + + /// Waits for a sent event to come down sync, giving up after a while. + Future awaitEvent(String roomId, String eventId) => awaitRooms( + (rooms) => rooms[roomId]?.eventIds.containsKey(eventId) ?? false, + ); + + Future awaitRooms(bool Function(IMap rooms) arrived) { if (arrived(state)) return .value(); final completer = Completer(); diff --git a/lib/controllers/selected_room.dart b/lib/controllers/selected_room.dart index f59232c..075fcdd 100644 --- a/lib/controllers/selected_room.dart +++ b/lib/controllers/selected_room.dart @@ -17,7 +17,9 @@ class SelectedRoomController extends Notifier { (space) => space?.allChildRooms .map((room) => room.metadata?.id) .nonNulls - .toIList(), + .toIList() + // Real spaces have a timeline of their own + .addAll([?space.room?.metadata?.id]), ), ); if (roomIds == null) return roomId; diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index 2cd804c..999fea6 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -6,28 +6,44 @@ import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; import "package:intl/intl.dart"; import "package:m3e_buttons/m3e_buttons.dart"; +import "package:multi_state_switch/multi_state_switch.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/account_data.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; -import "package:nexus/controllers/init_complete.dart"; +import "package:nexus/controllers/enabled_image_packs.dart"; import "package:nexus/controllers/notification.dart"; +import "package:nexus/controllers/profile.dart"; +import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/settings.dart"; import "package:nexus/controllers/unified_push.dart"; import "package:nexus/controllers/spec_versions.dart"; import "package:nexus/controllers/unified_push_allowed.dart"; import "package:nexus/controllers/unified_push_distributors.dart"; import "package:nexus/helpers/extensions/distributor_name.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/helpers/extensions/room_image_packs.dart"; +import "package:nexus/helpers/hooks/saving.dart"; import "package:nexus/models/account_data.dart"; import "package:nexus/models/client_state.dart"; +import "package:nexus/models/image_pack.dart"; +import "package:nexus/models/name_color.dart"; +import "package:nexus/models/push_rule_switch.dart"; import "package:nexus/models/room_order.dart"; +import "package:nexus/models/setting.dart"; import "package:nexus/models/settings.dart"; import "package:nexus/models/settings_category.dart"; import "package:nexus/models/show_and_send.dart"; import "package:nexus/main.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/common/divider_text.dart"; +import "package:nexus/widgets/avatars/image_pack_avatar.dart"; +import "package:nexus/widgets/settings/block_user_field.dart"; import "package:nexus/widgets/settings/dialog_list_tile.dart"; -import "package:nexus/widgets/user_bottom_sheet.dart"; -import "package:nexus/widgets/reset_encryption_sheet.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; +import "package:nexus/widgets/settings/enable_image_packs_sheet.dart"; +import "package:nexus/widgets/settings/keyword_field.dart"; +import "package:nexus/widgets/users/user_bottom_sheet.dart"; +import "package:nexus/widgets/encryption/reset_encryption_sheet.dart"; class SettingsSectionsController extends AsyncNotifier>> { @@ -35,6 +51,33 @@ class SettingsSectionsController Future>> build() async { final settings = await ref.watch(SettingsController.provider.future); + // Loads the enabled packs' state, so they can be shown + ref.watch(EnabledImagePacksController.provider); + final enabledPacks = ref.watch( + AccountDataController.provider.select((data) => data.enabledImagePacks), + ); + final enabledPackInfo = ref.watch( + RoomsController.provider.select( + (rooms) => enabledPacks.rooms.entries.expand((entry) { + final room = rooms[entry.key]; + final packs = room?.imagePacks(entry.key) ?? const .empty(); + + return entry.value.keys.map( + (stateKey) => ( + roomId: entry.key, + stateKey: stateKey, + roomName: room?.metadata?.name ?? entry.key, + pack: packs[stateKey], + ), + ); + }).toIList(), + ), + ); + + Future setEnabledPacks(ImagePackRooms packs) => ref + .read(AccountDataController.provider.notifier) + .setEnabledImagePacks(packs); + /// A tile for a [ShowAndSend] setting, saving the settings from [update]. Widget showAndSendTile( String title, @@ -59,6 +102,72 @@ class SettingsSectionsController .onError(showError), ); + final pushRules = ref.watch( + AccountDataController.provider.select((data) => data.pushRules.global), + ); + final ignoredUsers = ref.watch( + AccountDataController.provider.select( + (data) => data.ignoredUserList.ignoredUsers.keys.toIList().sort(), + ), + ); + final accountData = ref.read(AccountDataController.provider.notifier); + + Setting header(String title, String description, IconData icon) => .new( + title: title, + description: description, + icon: icon, + builder: (title, _, _) => Padding( + padding: .symmetric(horizontal: 16), + child: DividerText(title), + ), + ); + + /// A switch for push rules, which is disabled while [onChanged] saves. A + /// null [value] is shown in the middle, for rules set up some other way. + Setting pushSwitchSetting({ + required String title, + required String description, + required IconData icon, + required bool? value, + required Future Function(bool value) onChanged, + }) => .new( + title: title, + description: description, + icon: icon, + builder: (title, description, icon) => HookBuilder( + builder: (context) { + final saving = Saving.use(); + final position = switch (value) { + false => 0, + null => 1, + true => 2, + }; + void change(bool value) => + saving.run(() => onChanged(value)).onError(showError); + + return ListTile( + enabled: !saving.active, + leading: Icon(icon), + title: Text(title), + subtitle: Text(description), + trailing: MultiStateSwitch( + states: 3, + // As wide as a regular switch, which has 2 states 20 apart + stepWidth: 10, + value: position, + semanticFormatterCallback: (position) => + ["Off", "Custom", "On"][position], + onChanged: saving.active + ? null + : (newPosition) => change(newPosition > position), + ), + // Tapping turns it off only when it's fully on + onTap: () => change(value != true), + ); + }, + ), + ); + return .new({ "General": .new([ .new( @@ -104,6 +213,26 @@ class SettingsSectionsController : null, ), ), + .new( + title: "Name Colors", + description: "Color names by power level, so moderators and admins stand out, or by user, so everyone has their own.", + icon: Icons.format_color_text, + builder: (title, description, icon) => DialogListTile( + icon: Icon(icon), + title: title, + subtitle: Text(description), + value: settings.nameColor, + options: NameColor.values, + getName: (option) => switch (option) { + .powerLevel => "By power level", + .user => "By user", + }, + onChanged: (value) => ref + .read(SettingsController.provider.notifier) + .set(settings.copyWith(nameColor: value)) + .onError(showError), + ), + ), ]), ), .new( @@ -209,6 +338,21 @@ class SettingsSectionsController .onError(showError), ), ), + .new( + title: "Hide Server ACL Events", + description: "Hides server ACL (server ban list) changes from appearing in conversations.", + icon: Icons.dns, + builder: (title, description, icon) => SwitchListTile( + title: Text(title), + subtitle: Text(description), + secondary: Icon(icon), + value: settings.hideServerAclEvents, + onChanged: (value) => ref + .read(SettingsController.provider.notifier) + .set(settings.copyWith(hideServerAclEvents: value)) + .onError(showError), + ), + ), ]), ), .new( @@ -264,12 +408,84 @@ class SettingsSectionsController ), ]), ), + .new( + title: "Image Packs", + icon: Icons.emoji_emotions, + settings: .new([ + ...enabledPackInfo.map( + (info) => Setting( + title: + info.pack?.name ?? + ImagePack.fallbackName(info.roomName, info.stateKey), + description: info.roomName, + icon: Icons.emoji_emotions, + builder: (title, description, _) => HookBuilder( + key: ValueKey((info.roomId, info.stateKey)), + builder: (context) { + final saving = Saving.use(); + + return ListTile( + enabled: !saving.active, + leading: ImagePackAvatar(info.pack?.icon), + title: Text(title), + subtitle: Text(description), + trailing: IconButton( + tooltip: "Remove pack", + icon: Icon(Icons.delete), + onPressed: saving.active + ? null + : () => saving.run( + () => setEnabledPacks( + ref + .read(AccountDataController.provider) + .enabledImagePacks + .withPack( + info.roomId, + info.stateKey, + enabled: false, + ), + ).onError(showError), + ), + ), + ); + }, + ), + ), + ), + .new( + title: "Add Packs", + description: + "Use image packs from any of your rooms in every room.", + icon: Icons.add, + builder: (title, description, icon) => HookBuilder( + builder: (context) { + final saving = Saving.use(); + + return ListTile( + enabled: !saving.active, + leading: Icon(icon), + title: Text(title), + subtitle: Text(description), + onTap: () => context.showAdaptiveSheet( + (_) => EnableImagePacksSheet( + enabled: enabledPacks, + onSave: (packs) => saving.run( + () => setEnabledPacks(packs).onError(showError), + ), + ), + ), + ); + }, + ), + ), + ]), + ), .new( title: "Notifications", icon: Icons.notifications, settings: .new([ .new( - title: "Push notifications", + title: "Push Notifications", description: "Enable push notifications using Web Push, and choose which UnifiedPush distributor to use.", builder: (title, description, icon) => HookConsumer( builder: (context, ref, _) { @@ -366,6 +582,102 @@ class SettingsSectionsController ), icon: Icons.notification_add, ), + if (pushRules.master case final master?) + pushSwitchSetting( + title: "Mute All", + description: "Don't notify for anything, without changing your other rules.", + icon: Icons.notifications_off, + value: master.enabled, + onChanged: (mute) => accountData.savePushRule( + .override, + master.copyWith(enabled: mute), + ), + ), + ...PushRuleSection.values.expand( + (section) => [ + header(section.title, section.description, section.icon), + ...PushRuleSwitch.values + .where( + (option) => + option.section == section && + option.rulesIn(pushRules).isNotEmpty, + ) + .map( + (option) => pushSwitchSetting( + title: option.title, + description: option.description, + icon: option.icon, + value: option.valueIn(pushRules), + onChanged: (value) => Future.wait( + option + .changesIn(pushRules, value) + .map( + (change) => accountData.savePushRule( + change.kind, + change.rule, + ), + ), + ), + ), + ), + ], + ), + header( + "Keywords", + "Messages containing these words, which notify with a highlight and sound.", + Icons.text_fields, + ), + ...pushRules.keywords.map( + (rule) => Setting( + title: rule.pattern ?? rule.ruleId, + description: "Messages containing this keyword.", + icon: Icons.text_fields, + builder: (title, description, icon) => HookBuilder( + key: ValueKey(rule.ruleId), + builder: (context) { + final saving = Saving.use(); + final custom = + !rule.enabled || rule.actions != .highlightWithSound; + + return ListTile( + enabled: !saving.active, + leading: Icon(icon), + title: Text(title), + trailing: IconButton( + tooltip: custom + ? "Set up differently by another client. Press to reset to Nexus defaults." + : "Remove keyword", + icon: Icon(custom ? Icons.warning : Icons.delete), + onPressed: saving.active + ? null + : () => saving + .run( + () => custom + ? accountData.savePushRule( + .content, + rule.copyWith( + enabled: true, + actions: .highlightWithSound, + ), + ) + : accountData.deletePushRule( + .content, + rule.ruleId, + ), + ) + .onError(showError), + ), + ); + }, + ), + ), + ), + .new( + title: "Add Keyword", + description: "Notify for messages containing a word.", + icon: Icons.add, + builder: (_, _, _) => KeywordField(), + ), ]), ), .new( @@ -422,6 +734,59 @@ class SettingsSectionsController ), icon: Icons.person_off, ), + header( + "Blocked Users", + "Users whose messages and invites are hidden. They aren't told they're blocked.", + Icons.block, + ), + ...ignoredUsers.map( + (userId) => Setting( + title: userId, + description: "A blocked user.", + icon: Icons.person, + builder: (title, description, icon) => HookConsumer( + key: ValueKey(userId), + builder: (context, ref, _) { + final saving = Saving.use(); + final profile = ref + .watch(ProfileController.provider(userId)) + .value + ?.profile; + final name = profile?.displayName ?? userId.localpart; + + return ListTile( + enabled: !saving.active, + leading: AvatarOrHash(profile?.avatarUrl, name), + title: Text(name, overflow: .ellipsis), + subtitle: Text(userId, overflow: .ellipsis), + onTap: () => context.showAdaptiveSheet( + (_) => UserBottomSheet(userId), + ), + trailing: IconButton( + tooltip: "Unblock", + icon: Icon(Icons.lock_open), + onPressed: saving.active + ? null + : () => saving + .run( + () => accountData.setIgnored( + userId, + ignored: false, + ), + ) + .onError(showError), + ), + ); + }, + ), + ), + ), + .new( + title: "Block User", + description: "Block a user by their ID.", + icon: Icons.block, + builder: (_, _, _) => BlockUserField(), + ), ]), ), .new( @@ -443,43 +808,6 @@ class SettingsSectionsController ), icon: Icons.key_off, ), - .new( - title: "Log Out", - description: - "Log out of your account, returning you to the login page.", - builder: (title, description, icon) => Builder( - builder: (context) { - final colorScheme = Theme.of(context).colorScheme; - return M3EButton.icon( - onPressed: () async { - final container = ProviderScope.containerOf(context); - - final route = ModalRoute.of(context)!; - Navigator.of(context).popUntil((r) => r.isFirst); - await route.completed; - - await container - .read(UnifiedPushController.provider.notifier) - .deregister() - .onError(showError); - container.invalidate(InitCompleteController.provider); - await container - .read(ClientController.provider.notifier) - .logout() - .onError(showError); - }, - label: Text(title), - icon: Icon(icon), - tooltip: description, - decoration: .styleFrom( - backgroundColor: colorScheme.errorContainer, - foregroundColor: colorScheme.onErrorContainer, - ), - ); - }, - ), - icon: Icons.logout, - ), ]), ), ]), diff --git a/lib/controllers/sidebar_page.dart b/lib/controllers/sidebar_page.dart index 5598691..d80cb44 100644 --- a/lib/controllers/sidebar_page.dart +++ b/lib/controllers/sidebar_page.dart @@ -1,9 +1,14 @@ import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/notification_request.dart"; import "package:nexus/models/sidebar_page.dart"; class SidebarPageController extends Notifier { + // Show the notification that switched accounts, if one did @override - SidebarPage build() => .rooms; + SidebarPage build() => + ref.read(NotificationRequestController.provider) == null + ? .rooms + : .notifications; void set(SidebarPage page) => state = page; diff --git a/lib/controllers/space_edges.dart b/lib/controllers/space_edges.dart index 81347c5..3b239bf 100644 --- a/lib/controllers/space_edges.dart +++ b/lib/controllers/space_edges.dart @@ -1,13 +1,16 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/models/space_edge.dart"; +import "package:nexus/models/sync_data.dart"; class SpaceEdgesController extends Notifier>> { @override IMap> build() => .new(); - void set(IMap> newEdges) => - state = state.addAll(newEdges); + void handleSync(SyncData sync) { + if (sync.clearState) state = .new(); + state = state.addAll(sync.spaceEdges ?? const .empty()); + } static final provider = NotifierProvider>>( diff --git a/lib/controllers/space_hierarchy.dart b/lib/controllers/space_hierarchy.dart index 8a5aa9d..226b091 100644 --- a/lib/controllers/space_hierarchy.dart +++ b/lib/controllers/space_hierarchy.dart @@ -1,3 +1,4 @@ +import "package:flutter_riverpod/experimental/mutation.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/models/space_hierarchy.dart"; @@ -27,6 +28,12 @@ class SpaceHierarchyController(final String spaceId) ); } + /// Adding rooms to a space, keyed by its ID + static final addChildrenMutation = Mutation(); + + /// Removing a room from a space, keyed by (space ID, room ID) + static final removeChildMutation = Mutation(); + static final provider = AsyncNotifierProvider.family .autoDispose( SpaceHierarchyController.new, diff --git a/lib/controllers/spaces.dart b/lib/controllers/spaces.dart index 8af045c..4d6dffe 100644 --- a/lib/controllers/spaces.dart +++ b/lib/controllers/spaces.dart @@ -25,55 +25,50 @@ class SpacesController extends AsyncNotifier> { MapEntry(spaceId, edges.map((edge) => edge.childId).toList()), ); - Set collectDescendants(String startId) { - final visited = {}; - final stack = [startId]; - - while (stack.isNotEmpty) { - final current = stack.removeLast(); - final children = childrenById[current] ?? const []; - - for (final child in children) { - if (visited.add(child)) { - stack.add(child); - } - } - } - - return visited; - } + /// Everything under [spaceId], however deep, skipping any already + /// [visited] so cycles end. + ISet collectDescendants( + String spaceId, [ + ISet visited = const .empty(), + ]) => (childrenById[spaceId] ?? const []).fold( + visited, + (visited, childId) => visited.contains(childId) + ? visited + : collectDescendants(childId, visited.add(childId)), + ); Space buildSpace(String spaceId) { final space = rooms[spaceId]; final directChildrenIds = childrenById[spaceId] ?? const []; - final directRooms = []; - final subSpaces = []; - - for (final childId in directChildrenIds) { - final room = rooms[childId]; - if (room == null) continue; - - if (childrenById.containsKey(childId)) { - final descendants = collectDescendants(childId); - - subSpaces.add( - .new( - room: room, - children: .new(descendants.map((id) => rooms[id]).nonNulls), - ), - ); - } else { - directRooms.add(room); - } - } - return .new( id: spaceId, room: space, title: space?.metadata?.name ?? "Unnamed Space", - children: .new(directRooms), - subSpaces: .new(subSpaces), + children: .new( + directChildrenIds + .where((childId) => !childrenById.containsKey(childId)) + .map((childId) => rooms[childId]) + .nonNulls, + ), + subSpaces: .new( + directChildrenIds + .where(childrenById.containsKey) + .map( + (childId) => switch (rooms[childId]) { + final room? => Subspace( + room: room, + children: .new( + collectDescendants(childId) + .map((id) => rooms[id]) + .nonNulls, + ), + ), + null => null, + }, + ) + .nonNulls, + ), ); } diff --git a/lib/controllers/thread_list.dart b/lib/controllers/thread_list.dart new file mode 100644 index 0000000..847b29e --- /dev/null +++ b/lib/controllers/thread_list.dart @@ -0,0 +1,37 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/rooms.dart"; + +class ThreadListController(final String roomId) extends AsyncNotifier { + @override + Future build() => fetch(null); + + Future fetch(String? since) async { + final threads = await ref + .read(ClientController.provider.notifier) + .getThreads(.new(roomId: roomId, since: since)); + ref + .read(RoomsController.provider.notifier) + .storeEvents(threads.events.addAll(threads.relatedEvents)); + + return threads.nextBatch; + } + + Future loadMore() async { + final since = await future; + if (state.isLoading || since == null) return; + + state = .loading(); + try { + state = .data(await fetch(since)); + } catch (_) { + state = .data(since); + rethrow; + } + } + + static final provider = AsyncNotifierProvider.family + .autoDispose( + ThreadListController.new, + ); +} diff --git a/lib/controllers/thread_replies.dart b/lib/controllers/thread_replies.dart new file mode 100644 index 0000000..b0e4327 --- /dev/null +++ b/lib/controllers/thread_replies.dart @@ -0,0 +1,49 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/rooms.dart"; + +typedef ThreadParams = ({String roomId, String threadRoot}); + +/// Loads a thread's replies from the server, newest first, storing them. Its +/// state is the token for older replies, or null if there are none. +class ThreadRepliesController(final ThreadParams thread) + extends AsyncNotifier { + @override + Future build() => fetch(null); + + Future fetch(String? since) async { + final response = await ref + .read(ClientController.provider.notifier) + .paginateManual( + .new( + roomId: thread.roomId, + threadRoot: thread.threadRoot, + since: since, + direction: .backward, + ), + ); + ref + .read(RoomsController.provider.notifier) + .storeEvents(response.events.addAll(response.relatedEvents)); + + return response.nextBatch; + } + + Future loadOlder() async { + final since = await future; + if (state.isLoading || since == null) return; + + state = .loading(); + try { + state = .data(await fetch(since)); + } catch (_) { + state = .data(since); + rethrow; + } + } + + static final provider = AsyncNotifierProvider.family + .autoDispose( + ThreadRepliesController.new, + ); +} diff --git a/lib/controllers/tombstone.dart b/lib/controllers/tombstone.dart new file mode 100644 index 0000000..92c275b --- /dev/null +++ b/lib/controllers/tombstone.dart @@ -0,0 +1,22 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/models/content/content.dart"; +import "package:nexus/models/event.dart"; + +class TombstoneController(final String roomId) extends Notifier { + @override + Event? build() => ref.watch( + RoomsController.provider.select((rooms) { + final room = rooms[roomId]; + return switch (room?.state[EventType.tombstone.type]?[""]) { + final rowId? => room?.events[rowId], + null => null, + }; + }), + ); + + static final provider = NotifierProvider.family + .autoDispose( + TombstoneController.new, + ); +} diff --git a/lib/controllers/top_level_spaces.dart b/lib/controllers/top_level_spaces.dart index 321e29d..acdacad 100644 --- a/lib/controllers/top_level_spaces.dart +++ b/lib/controllers/top_level_spaces.dart @@ -1,11 +1,12 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/models/sync_data.dart"; class TopLevelSpacesController extends Notifier> { @override IList build() => .new(); - void set(IList newSpaces) => state = newSpaces; + void handleSync(SyncData sync) => state = sync.topLevelSpaces ?? state; static final provider = NotifierProvider>( diff --git a/lib/controllers/typing.dart b/lib/controllers/typing.dart index d1f3d28..b0e3f93 100644 --- a/lib/controllers/typing.dart +++ b/lib/controllers/typing.dart @@ -1,5 +1,6 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/models/sync_data.dart"; import "package:nexus/models/typing.dart"; class TypingController extends Notifier>> { @@ -8,6 +9,10 @@ class TypingController extends Notifier>> { void set(Typing typing) => state = state.add(typing.roomId, typing.userIds); + void handleSync(SyncData sync) { + if (sync.clearState) state = .new(); + } + static final provider = NotifierProvider>>( TypingController.new, diff --git a/lib/controllers/unified_push.dart b/lib/controllers/unified_push.dart index 40c4666..25675e2 100644 --- a/lib/controllers/unified_push.dart +++ b/lib/controllers/unified_push.dart @@ -2,11 +2,16 @@ import "dart:async"; import "dart:convert"; import "dart:io"; +import "package:collection/collection.dart"; import "package:flutter/foundation.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:intl/intl.dart"; +import "package:nexus/controllers/accounts.dart"; +import "package:nexus/controllers/active_account.dart"; +import "package:nexus/controllers/capabilities.dart"; import "package:nexus/controllers/selected_room.dart"; import "package:nexus/controllers/notification.dart"; +import "package:nexus/controllers/client_state.dart"; import "package:nexus/controllers/push_key.dart"; import "package:nexus/main.dart"; import "package:nexus/controllers/client.dart"; @@ -18,6 +23,19 @@ import "package:window_manager/window_manager.dart"; class UnifiedPushController extends AsyncNotifier { Completer? _endpoint; + /// The account [instance] (its device ID) belongs to, or the active one for + /// devices registered before account switching. + Future _accountFor(String instance) async => + (await ref.read(AccountsController.provider.future)) + .firstWhereOrNull((account) => account.deviceId == instance) + ?.id ?? + ref.read(ActiveAccountController.provider); + + ClientController _clientFor(String accountId) => + accountId == ref.read(ActiveAccountController.provider) + ? ref.read(ClientController.provider.notifier) + : ref.read(ClientController.forAccount(accountId).notifier); + @override Future build() async { if (!Platform.isLinux && !Platform.isAndroid) return null; @@ -36,23 +54,21 @@ class UnifiedPushController extends AsyncNotifier { .read(PushKeyController.provider(instance).notifier) .set(pushKey); - await ref - .read(ClientController.provider.notifier) - .registerPusher( - .new( - appDisplayName: "Nexus", - appId: "nexus.federated.nexus", - data: .webPush( - url: .parse(endpoint.url), - auth: endpoint.pubKeySet!.auth, - ), - deviceDisplayName: - "Nexus on ${toBeginningOfSentenceCase(Platform.operatingSystem)}", - kind: .webPush, - lang: "en", - pushKey: pushKey, - ), - ); + await _clientFor(await _accountFor(instance)).registerPusher( + .new( + appDisplayName: "Nexus", + appId: "nexus.federated.nexus", + data: .webPush( + url: .parse(endpoint.url), + auth: endpoint.pubKeySet!.auth, + ), + deviceDisplayName: + "Nexus on ${toBeginningOfSentenceCase(Platform.operatingSystem)}", + kind: .webPush, + lang: "en", + pushKey: pushKey, + ), + ); state = .data(await UnifiedPush.getDistributor()); }); @@ -82,21 +98,26 @@ class UnifiedPushController extends AsyncNotifier { "Failed to decrypt notification. Try toggling off and on UnifiedPush in settings.", ); } - final notification = await ref - .read(ClientController.provider.notifier) - .handlePush(json.decode(String.fromCharCodes(message.content))); + final accountId = await _accountFor(instance); + final client = _clientFor(accountId); + final isActive = + accountId == ref.read(ActiveAccountController.provider); + final notification = await client.handlePush( + json.decode(String.fromCharCodes(message.content)), + ); if (notification == null || (!isInBackground && - (!Platform.isAndroid && - (WindowManager.instance.getCurrent()?.isFocused ?? true)) && + isActive && + (WindowManager.instance.getCurrent()?.isFocused ?? false) && ref.read(SelectedRoomController.provider) == notification.roomId)) { if (isInBackground) exit(0); return; } - final client = ref.read(ClientController.provider.notifier); + final hasOtherAccounts = + (await ref.read(AccountsController.provider.future)).length > 1; final icon = notification.roomAvatar == null ? null @@ -116,17 +137,20 @@ class UnifiedPushController extends AsyncNotifier { await ref .read(NotificationController.provider.notifier) .send( - // Android stacks messages into one conversation per room + // Android stacks messages into one conversation per room (and + // account, since two accounts can share a room) id: - (Platform.isAndroid - ? notification.roomId - : notification.eventId) + "$accountId/${Platform.isAndroid ? notification.roomId : notification.eventId}" .hashCode & 0x7fffffff, - threadId: notification.roomId, + threadId: "$accountId/${notification.roomId}", title: notification.roomName, + subtitle: hasOtherAccounts ? notification.self.id : null, body: notification.text, - payload: notification.eventRowId.toString(), + payload: NotificationController.payloadFor( + accountId, + notification.eventRowId, + ), timestamp: notification.timestamp, icon: icon, sound: notification.sound, @@ -147,14 +171,32 @@ class UnifiedPushController extends AsyncNotifier { if (!registered || isInBackground) return null; - try { - if (await deregisterIfDisabled()) return null; + ref.listen( + ClientStateController.provider.select((state) => state?.isLoggedIn), + (previous, isLoggedIn) => Future(() async { + if (isLoggedIn != true) return; + if (await deregisterIfDisabled()) return; - return await register(); - } catch (error, stackTrace) { - showError(error, stackTrace); - return null; - } + // On startup, only accounts with push on (which have a push key). + // After logging in, push is on by default. + final deviceId = ref.read(ClientStateController.provider)?.deviceId; + if (previous != false && + (deviceId == null || + await ref.read(PushKeyController.provider(deviceId).future) == + null)) { + return; + } + + try { + await register(); + } on UnsupportedError { + // The settings tile explains that the homeserver can't send Web Push + } + }).catchError(showError), + fireImmediately: true, + ); + + return null; } /// Registers with [distributor], or the current/default distributor if none @@ -166,16 +208,17 @@ class UnifiedPushController extends AsyncNotifier { await deregister(); } + // Not loading until logged in, since the app waits for this + final deviceId = await ref + .read(GomuksListenerController.provider.notifier) + .deviceId(); + state = .loading(); try { - final deviceId = await ref - .read(GomuksListenerController.provider.notifier) - .deviceId(); - await Future(() async { - final capabilities = await ref - .read(ClientController.provider.notifier) - .getCapabilities(); + final capabilities = await ref.read( + CapabilitiesController.provider.future, + ); if (capabilities.webpush?.vapid == null) { throw UnsupportedError( @@ -238,10 +281,10 @@ class UnifiedPushController extends AsyncNotifier { final keyProvider = PushKeyController.provider(instance); final key = await ref.read(keyProvider.future); + final accountId = await _accountFor(instance); if (key != null) { - await ref - .read(ClientController.provider.notifier) + await _clientFor(accountId) .deregisterPusher(.new(appId: "nexus.federated.nexus", pushKey: key)); await ref.read(keyProvider.notifier).set(null); } else { @@ -251,7 +294,9 @@ class UnifiedPushController extends AsyncNotifier { } await UnifiedPush.unregister(instance); - state = .data(null); + if (accountId == ref.read(ActiveAccountController.provider)) { + state = .data(null); + } } static final provider = AsyncNotifierProvider( diff --git a/lib/controllers/unified_push_allowed.dart b/lib/controllers/unified_push_allowed.dart index 03ce3b0..6dd1cf7 100644 --- a/lib/controllers/unified_push_allowed.dart +++ b/lib/controllers/unified_push_allowed.dart @@ -1,7 +1,7 @@ import "dart:io"; import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/capabilities.dart"; import "package:nexus/controllers/unified_push_distributors.dart"; class UnifiedPushAllowedController extends AsyncNotifier { @@ -19,9 +19,9 @@ class UnifiedPushAllowedController extends AsyncNotifier { : "Your platform is not currently supported by UnifiedPush"}."; } - final capabilities = await ref - .read(ClientController.provider.notifier) - .getCapabilities(); + final capabilities = await ref.watch( + CapabilitiesController.provider.future, + ); if (capabilities.webpush?.vapid == null) { return "Your homeserver does not support MSC4174 (Web Push), and therefore cannot send notifications to Nexus."; diff --git a/lib/controllers/via.dart b/lib/controllers/via.dart index 39db682..e443572 100644 --- a/lib/controllers/via.dart +++ b/lib/controllers/via.dart @@ -1,60 +1,58 @@ -import "package:collection/collection.dart"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/models/content/content.dart"; import "package:nexus/models/content/membership.dart"; import "package:nexus/models/content/power_levels.dart"; +import "package:nexus/models/event.dart"; import "package:nexus/models/room.dart"; -class ViaController(final Room room) extends Notifier { +class ViaController(final Room room) extends Notifier> { @override - String build() { - final servers = {}; + ISet build() { + final powerLevelUsers = + switch (room.state[EventType.powerLevels.type]?[""]) { + final rowId? => switch (room.events[rowId]?.content) { + PowerLevelsContent(:final users) => users.keys.toIList(), + _ => null, + }, + null => null, + } ?? + .new([]); - void addUserId(String? userId) { - final server = userId?.split(":").lastOrNull; - if (server != null) { - servers.add(server); - } - } + final joinedMembers = + (room.state[EventType.membership.type]?.values ?? const []) + .map( + (rowId) => switch (room.events[rowId]) { + Event( + stateKey: final userId?, + content: MembershipContent(status: .join), + ) => + userId, + _ => null, + }, + ) + .nonNulls + .toIList(); - addUserId(ref.watch(ClientStateController.provider)?.userId); - - final powerLevelsEventId = room.state[EventType.powerLevels.type]?[""]; - final powerLevels = powerLevelsEventId == null - ? null - : room.events[powerLevelsEventId]; - - if (powerLevels?.content case PowerLevelsContent(:final users)) { - for (final userId in users.keys) { - addUserId(userId); - if (servers.length >= 5) break; - } - } - - final members = room.state[EventType.membership.type]?.values.toIList(); - for (var i = 0; servers.length < 5; i++) { - final membershipEventId = members?.getOrNull(i); - final member = membershipEventId == null - ? null - : room.events[membershipEventId]; - - if (member?.content case MembershipContent(:final status)) { - if (status == .join) { - addUserId(member?.stateKey); - } - } - - if (members?.getOrNull(i) == null) break; - } - - return servers.isEmpty - ? "" - : "?${servers.map((server) => "via=$server").join("&")}"; + return [?ref.watch(ClientStateController.provider)?.userId] + .toIList() + .addAll(powerLevelUsers) + .addAll(joinedMembers) + .map((userId) => userId.substring(userId.indexOf(":") + 1)) + .whereNoDuplicates() + .take(5) + .toISet(); } - static final provider = NotifierProvider.family( - ViaController.new, - ); + static final provider = + NotifierProvider.family, Room>( + ViaController.new, + ); +} + +extension ViaQuery on ISet { + /// These servers as a matrix: URI query, or empty if there are none. + String get viaQuery => + isEmpty ? "" : "?${map((server) => "via=$server").join("&")}"; } diff --git a/lib/helpers/current_location_helper.dart b/lib/helpers/current_location_helper.dart new file mode 100644 index 0000000..06f22d8 --- /dev/null +++ b/lib/helpers/current_location_helper.dart @@ -0,0 +1,78 @@ +import "dart:async"; +import "dart:io"; + +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:location/location.dart"; +import "package:latlong2/latlong.dart"; +import "package:nexus/controllers/portal.dart"; +import "package:nexus/models/location_exception.dart"; + +class CurrentLocationHelper(final Ref ref) { + static const _timeLimit = Duration(seconds: 10); + + /// The user's location and its accuracy in meters, or null if [askPermission] + /// is off and they haven't allowed it. + Future<(LatLng, double?)?> get({required bool askPermission}) async { + // location talks to GeoClue directly, which Flatpak's sandbox blocks, so + // Linux uses the location portal, which also asks the user for permission + if (Platform.isLinux) { + // The portal can't say whether it's allowed without asking + if (!askPermission) return null; + + try { + final portal = await ref.read(PortalController.provider.future); + final location = await portal.location + .createSession(accuracy: .exact) + .first + .timeout(_timeLimit); + + return switch ((location.latitude, location.longitude)) { + (final latitude?, final longitude?) => ( + LatLng(latitude, longitude), + location.accuracy, + ), + _ => throw LocationException.failed, + }; + } on TimeoutException { + throw LocationException.timedOut; + } catch (_) { + throw LocationException.failed; + } + } + + final location = Location.instance; + if (!await location.serviceEnabled()) { + if (!askPermission) return null; + throw LocationException.servicesOff; + } + + var permission = await location.hasPermission(); + if (permission == .denied && askPermission) { + permission = await location.requestPermission(); + } + if (permission == .denied || permission == .deniedForever) { + if (!askPermission) return null; + throw LocationException.denied; + } + + LocationData? data; + try { + data = await location.getLocation().timeout(_timeLimit); + } on TimeoutException { + // A fix can take long indoors, but another app may have a recent one + data = await location.getLastKnownLocation().onError( + (_, _) => throw LocationException.failed, + ); + } catch (_) { + throw LocationException.failed; + } + + if (data == null) throw LocationException.timedOut; + + return (LatLng(data.latitude, data.longitude), data.accuracy); + } + + static final provider = Provider( + CurrentLocationHelper.new, + ); +} diff --git a/lib/helpers/extensions/better_when.dart b/lib/helpers/extensions/better_when.dart index e054d02..459d139 100644 --- a/lib/helpers/extensions/better_when.dart +++ b/lib/helpers/extensions/better_when.dart @@ -1,7 +1,7 @@ import "package:flutter/widgets.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:nexus/widgets/error_dialog.dart"; -import "package:nexus/widgets/loading.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/widgets/common/loading.dart"; extension BetterWhen on AsyncValue { Widget betterWhen({ diff --git a/lib/helpers/extensions/build_event_options.dart b/lib/helpers/extensions/build_event_options.dart index 72ca2d2..a6ecc06 100644 --- a/lib/helpers/extensions/build_event_options.dart +++ b/lib/helpers/extensions/build_event_options.dart @@ -1,9 +1,9 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:material_ui/material_ui.dart"; -import "package:nexus/widgets/sheet_layout.dart"; import "package:flutter/services.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/pinned_ids.dart"; import "package:nexus/controllers/power_level.dart"; @@ -12,12 +12,11 @@ import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/room_chat.dart"; import "package:nexus/controllers/via.dart"; import "package:nexus/helpers/extensions/event_id_is_fake.dart"; -import "package:nexus/helpers/extensions/is_desktop.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; import "package:nexus/models/content/message.dart"; import "package:nexus/models/event.dart"; import "package:nexus/models/relation_type.dart"; -import "package:nexus/widgets/emoji_picker.dart"; +import "package:nexus/widgets/emoji/emoji_picker.dart"; +import "package:nexus/widgets/emoji/mxc_emoji.dart"; import "package:nexus/main.dart"; extension BuildEventOptions on Event { @@ -27,6 +26,7 @@ extension BuildEventOptions on Event { required String roomId, required String userId, required void Function(int, RelationType) onRelation, + void Function(String threadRoot)? onStartThread, }) { final theme = Theme.of(context); final danger = theme.colorScheme.error; @@ -35,11 +35,15 @@ extension BuildEventOptions on Event { final notifier = RoomChatController.provider(( roomId: roomId, contextualEvent: null, + threadRoot: null, )).notifier; final isPinned = ref .read(PinnedIdsController.provider(roomId)) .contains(eventId); + final canSend = ref.read( + PowerLevelController.provider(.new(eventType: .message, roomId: roomId)), + ); void showReasonSheet({ required String title, @@ -83,6 +87,18 @@ extension BuildEventOptions on Event { ); } + if (eventId.isFake) { + return [ + PopupMenuItem( + onTap: () => ref.read(notifier).hideClientSticky(rowId), + child: ListTile( + leading: Icon(Icons.delete, color: danger), + title: Text("Hide", style: .new(color: danger)), + ), + ), + ].lock; + } + return .new([ if (ref.read( PowerLevelController.provider( @@ -97,6 +113,8 @@ extension BuildEventOptions on Event { mainAxisAlignment: isDesktop ? .center : .spaceEvenly, children: [ ...{ + // Custom emoji are sent without their shortcode, as only + // their mxc URL is recorded ...ref .read(RecentEmojiController.provider) .map((entry) => entry.emoji), @@ -109,10 +127,15 @@ extension BuildEventOptions on Event { .take(isDesktop ? 3 : 5) .map( (emoji) => IconButton( - icon: Text( - emoji, - style: .new(fontSize: isDesktop ? null : 18), - ), + icon: emoji.startsWith("mxc://") + ? SizedBox.square( + dimension: isDesktop ? 18 : 24, + child: MxcEmoji(Uri.parse(emoji)), + ) + : Text( + emoji, + style: .new(fontSize: isDesktop ? null : 18), + ), onPressed: () async { Navigator.of(context).pop(); await ref @@ -134,12 +157,13 @@ extension BuildEventOptions on Event { context.showAdaptiveSheet( (context) => EmojiPicker( + roomId: roomId, allowFreeText: true, - onSelection: (emoji) { + onSelection: (emoji, {shortcode, description}) { Navigator.of(context).pop(); ref .read(notifier) - .sendReaction(emoji, this) + .sendReaction(emoji, this, shortcode: shortcode) .onError(showError); }, ), @@ -151,11 +175,7 @@ extension BuildEventOptions on Event { ), ), - if (ref.read( - PowerLevelController.provider( - .new(eventType: .message, roomId: roomId), - ), - )) + if (canSend) PopupMenuItem( onTap: () => onRelation(rowId, .reply), child: const ListTile( @@ -164,7 +184,25 @@ extension BuildEventOptions on Event { ), ), - if (content is MessageContent && sender == userId) + if (onStartThread != null && + threadCount == 0 && + canSend && + relatesTo == null) + PopupMenuItem( + onTap: () => onStartThread(eventId), + child: const ListTile( + leading: Icon(Icons.forum), + title: Text("Start Thread"), + ), + ), + + if (sender == userId && + switch (content) { + LocationMessageContent() || + TextMessageContent(botCommand: _?) => false, + MessageContent() => true, + _ => false, + }) PopupMenuItem( onTap: () => onRelation(rowId, .edit), child: const ListTile(leading: Icon(Icons.edit), title: Text("Edit")), @@ -204,7 +242,7 @@ extension BuildEventOptions on Event { ); if (room == null) return; - final vias = ref.read(ViaController.provider(room)); + final vias = ref.read(ViaController.provider(room)).viaQuery; await Clipboard.setData( ClipboardData( @@ -229,11 +267,10 @@ extension BuildEventOptions on Event { ), if (ref.read( - PowerLevelController.provider( - .redaction(targetUser: sender, roomId: roomId), - ), - ) && - !eventId.isFake) + PowerLevelController.provider( + .redaction(targetUser: sender, roomId: roomId), + ), + )) PopupMenuItem( onTap: () => showReasonSheet( title: "Delete Message", @@ -250,15 +287,6 @@ extension BuildEventOptions on Event { ), ), - if (eventId.isFake) - PopupMenuItem( - onTap: () => ref.read(notifier).hideClientSticky(rowId), - child: ListTile( - leading: Icon(Icons.delete, color: danger), - title: Text("Hide", style: .new(color: danger)), - ), - ), - PopupMenuItem( onTap: () => showReasonSheet( title: "Report", diff --git a/lib/helpers/extensions/displayname_color.dart b/lib/helpers/extensions/displayname_color.dart new file mode 100644 index 0000000..eb81d16 --- /dev/null +++ b/lib/helpers/extensions/displayname_color.dart @@ -0,0 +1,38 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/room_power_levels.dart"; +import "package:nexus/controllers/settings.dart"; +import "package:nexus/helpers/extensions/string_to_color.dart"; + +extension DisplaynameColor on WidgetRef { + /// The color of [userId]'s name in [roomId], from their power level + /// (so everyone with the same level shares one) or their user ID, depending + /// on the user's settings. + Color displaynameColor(String roomId, String userId) => switch (watch( + SettingsController.provider.select((settings) => settings.value?.nameColor), + )) { + .user => userId.colorHash, + .powerLevel || null => powerLevelColor( + watch( + RoomPowerLevelsController.provider(roomId) + .select((levels) => levels.levelOf(userId)), + ), + ), + }; + + /// Like [displaynameColor], for when [userId]'s [level] is already known, + /// like a level they're being given. + Color displaynameColorAt(String userId, double level) => switch (watch( + SettingsController.provider.select((settings) => settings.value?.nameColor), + )) { + .user => userId.colorHash, + .powerLevel || null => powerLevelColor(level), + }; + + static Color powerLevelColor(double level) => HSLColor.fromAHSL( + 1, + level.isInfinite ? 30 : (210 + level / 50 * 137.50776) % 360, + 0.7, + 0.5, + ).toColor(); +} diff --git a/lib/helpers/extensions/get_localpart.dart b/lib/helpers/extensions/get_localpart.dart index 71e9808..200d2d0 100644 --- a/lib/helpers/extensions/get_localpart.dart +++ b/lib/helpers/extensions/get_localpart.dart @@ -4,6 +4,12 @@ extension GetLocalpart on String { /// Whether this looks like a valid Matrix user ID, e.g. `@user:example.com`. bool get isValidUserId => RegExp(r"^@[^:\s]+:[^\s]+$").hasMatch(this); + /// Whether this is a valid Matrix server name, e.g. `example.com:8448`. + bool get isValidServerName => RegExp( + r"^(\[[0-9a-f:.]+\]|[a-z0-9.-]{1,255})(:\d{1,5})?$", + caseSensitive: false, + ).hasMatch(this); + String? get serverName { final index = indexOf(":"); return index == -1 ? null : substring(index + 1); diff --git a/lib/helpers/extensions/global_rect.dart b/lib/helpers/extensions/global_rect.dart deleted file mode 100644 index 91c8305..0000000 --- a/lib/helpers/extensions/global_rect.dart +++ /dev/null @@ -1,15 +0,0 @@ -import "package:material_ui/material_ui.dart"; - -extension GlobalRect on BuildContext { - /// Where the widget this context belongs to is on screen, e.g. to open a - /// menu or popover next to it. - Rect get globalRect { - final overlay = Overlay.of(this).context.findRenderObject() as RenderBox; - - return switch (findRenderObject()) { - final RenderBox box => - box.localToGlobal(.zero, ancestor: overlay) & box.size, - _ => Rect.zero, - }; - } -} diff --git a/lib/helpers/extensions/gomuks_buffer.dart b/lib/helpers/extensions/gomuks_buffer.dart index 57425be..14404b4 100644 --- a/lib/helpers/extensions/gomuks_buffer.dart +++ b/lib/helpers/extensions/gomuks_buffer.dart @@ -2,7 +2,6 @@ import "dart:convert"; import "dart:ffi"; import "dart:typed_data"; -import "package:ffi/ffi.dart"; import "package:nexus/src/third_party/gomuks.g.dart"; extension GomuksOwnedBufferToX on GomuksOwnedBuffer { @@ -15,7 +14,10 @@ extension GomuksOwnedBufferToX on GomuksOwnedBuffer { } } - dynamic toJsonAndFree() => jsonDecode(utf8.decode(toBytesAndFree())); + dynamic toJsonAndFree() { + final bytes = toBytesAndFree(); + return bytes.isEmpty ? null : jsonDecode(utf8.decode(bytes)); + } } extension JsonToGomuksBuffer on Map { @@ -26,13 +28,13 @@ extension JsonToGomuksBuffer on Map { return buffer; } - Pointer toGomuksBufferPtr() { + Pointer toGomuksBufferPtr(Allocator allocator) { final bytes = utf8.encode(json.encode(this)); - final dataPtr = calloc(bytes.length); + final dataPtr = allocator(bytes.length); dataPtr.asTypedList(bytes.length).setAll(0, bytes); - return calloc() + return allocator() ..ref.base = dataPtr ..ref.length = bytes.length; } diff --git a/lib/helpers/extensions/image_pack_emoji.dart b/lib/helpers/extensions/image_pack_emoji.dart new file mode 100644 index 0000000..fe480d5 --- /dev/null +++ b/lib/helpers/extensions/image_pack_emoji.dart @@ -0,0 +1,29 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:material_emoji_picker/material_emoji_picker.dart"; +import "package:nexus/models/content/image_pack.dart"; +import "package:nexus/models/image_pack.dart"; +import "package:nexus/widgets/emoji/mxc_emoji.dart"; + +extension ImagePackEmoji on ImagePack { + EmojiCategory? get emojiCategory => _category(emoticons); + EmojiCategory? get stickerCategory => _category(stickers); + + EmojiCategory? _category(IMap images) => images.isEmpty + ? null + : .new( + icon: MxcEmoji(avatar ?? images.values.first.url), + name: name, + emojis: images + .mapTo( + (shortcode, image) => Emoji( + widget: MxcEmoji(image.url, label: shortcode), + value: image.url.toString(), + aliases: .new([shortcode]), + description: image.body ?? shortcode, + tags: const .empty(), + data: image, + ), + ) + .toIList(), + ); +} diff --git a/lib/helpers/extensions/is_desktop.dart b/lib/helpers/extensions/is_desktop.dart deleted file mode 100644 index d4161dd..0000000 --- a/lib/helpers/extensions/is_desktop.dart +++ /dev/null @@ -1,7 +0,0 @@ -import "package:material_ui/material_ui.dart"; - -extension IsDesktop on BuildContext { - /// Whether the window is wide enough for the desktop layout, with the - /// sidebar always visible, menus instead of bottom sheets, etc. - bool get isDesktop => MediaQuery.sizeOf(this).width > 650; -} diff --git a/lib/helpers/extensions/is_media.dart b/lib/helpers/extensions/is_media.dart new file mode 100644 index 0000000..dceea43 --- /dev/null +++ b/lib/helpers/extensions/is_media.dart @@ -0,0 +1,12 @@ +import "package:nexus/models/content/content.dart"; +import "package:nexus/models/content/message.dart"; + +extension IsMedia on Content { + bool get isMedia => switch (this) { + ImageMessageContent() || + VideoMessageContent() || + AudioMessageContent() || + FileMessageContent() => true, + _ => false, + }; +} diff --git a/lib/helpers/extensions/is_shown_as_message.dart b/lib/helpers/extensions/is_shown_as_message.dart index a78810b..6df7d2c 100644 --- a/lib/helpers/extensions/is_shown_as_message.dart +++ b/lib/helpers/extensions/is_shown_as_message.dart @@ -1,15 +1,19 @@ import "package:nexus/models/content/encrypted.dart"; import "package:nexus/models/content/message.dart"; +import "package:nexus/models/content/poll_start.dart"; import "package:nexus/models/content/sticker.dart"; import "package:nexus/models/event.dart"; extension IsShownAsMessage on Event { + /// Whether this is a message, sticker or poll. + bool get hasMessageContent => switch (content) { + MessageContent() || StickerContent() || PollStartContent() => true, + _ => false, + }; + /// Whether this is shown in the timeline as a message, with MessageRenderer. bool get isShownAsMessage => redactedBy == null && relationType != "m.replace" && - switch (content) { - MessageContent() || EncryptedContent() || StickerContent() => true, - _ => false, - }; + (hasMessageContent || content is EncryptedContent); } diff --git a/lib/helpers/extensions/join_room.dart b/lib/helpers/extensions/join_room.dart index df939c1..03140f9 100644 --- a/lib/helpers/extensions/join_room.dart +++ b/lib/helpers/extensions/join_room.dart @@ -17,6 +17,7 @@ extension JoinRoom on BuildContext { }) async { final container = ProviderScope.containerOf(this); final messenger = ScaffoldMessenger.of(this); + final navigator = Navigator.of(this); final roomId = await withProgressSnackbar( "Joining $name...", @@ -31,6 +32,7 @@ extension JoinRoom on BuildContext { action: .new( label: "Open", onPressed: () async { + navigator.popUntil((route) => route.isFirst); await container.focusRoom(roomId); container.read(SidebarPageController.provider.notifier).set(.rooms); }, diff --git a/lib/helpers/extensions/join_rule_name.dart b/lib/helpers/extensions/join_rule_name.dart new file mode 100644 index 0000000..94c6001 --- /dev/null +++ b/lib/helpers/extensions/join_rule_name.dart @@ -0,0 +1,14 @@ +import "package:nexus/models/join_rule.dart"; + +extension JoinRuleName on JoinRule { + /// What the rule is called in the UI, e.g. "Invite only". + String get displayName => switch (this) { + .public => "Public", + .invite => "Invite only", + .knock => "Knock", + .restricted => "Restricted", + .knockRestricted => "Restricted or knock", + .private => "Private", + .unknown => "Unknown", + }; +} diff --git a/lib/helpers/extensions/linkify_html.dart b/lib/helpers/extensions/linkify_html.dart new file mode 100644 index 0000000..f7eec0c --- /dev/null +++ b/lib/helpers/extensions/linkify_html.dart @@ -0,0 +1,45 @@ +import "package:html/dom.dart"; +import "package:html/parser.dart"; +import "package:linkify/linkify.dart"; +import "package:nexus/helpers/matrix_linkifier.dart"; + +extension LinkifyHtml on String { + /// Wraps bare links in this HTML's text in `` tags. + /// + /// Only text nodes are touched, so attribute values are left alone, and + /// text already inside a link or code is skipped. + String get linkifiedHtml { + final fragment = parseFragment(this); + _linkifyNode(fragment); + return fragment.outerHtml; + } +} + +void _linkifyNode(Node node) { + if (node is Element && const {"a", "code", "pre"}.contains(node.localName)) { + return; + } + + for (final child in node.nodes.toList()) { + if (child is! Text) { + _linkifyNode(child); + continue; + } + + final elements = linkifyText(child.data); + if (!elements.any((element) => element is LinkableElement)) continue; + + elements + .map( + (element) => switch (element) { + LinkableElement(:final text, :final url) => + Element.tag("a") + ..attributes["href"] = url + ..append(Text(text)), + _ => Text(element.text), + }, + ) + .forEach((replacement) => node.insertBefore(replacement, child)); + child.remove(); + } +} diff --git a/lib/helpers/extensions/log_out.dart b/lib/helpers/extensions/log_out.dart new file mode 100644 index 0000000..a170857 --- /dev/null +++ b/lib/helpers/extensions/log_out.dart @@ -0,0 +1,55 @@ +import "package:collection/collection.dart"; +import "package:flutter_riverpod/experimental/mutation.dart"; +import "package:nexus/controllers/accounts.dart"; +import "package:nexus/controllers/active_account.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/init_complete.dart"; +import "package:nexus/controllers/unified_push.dart"; +import "package:nexus/main.dart"; + +extension LogOut on MutationTarget { + static final mutation = Mutation(); + + Future logOut(String accountId) => mutation.run(this, (_) async { + final accounts = await container.read(AccountsController.provider.future); + final account = accounts.firstWhereOrNull( + (account) => account.id == accountId, + ); + if (account == null) return; + + final isActive = + accountId == container.read(ActiveAccountController.provider); + final client = isActive + ? container.read(ClientController.provider.notifier) + : container.read(ClientController.forAccount(accountId).notifier); + + if (account.deviceId case final deviceId?) { + await container + .read(UnifiedPushController.provider.notifier) + .deregister(deviceId) + .onError(showError); + } + if (isActive) container.invalidate(InitCompleteController.provider); + await client.logout().onError(showError); + + if (!isActive) { + container.invalidate(ClientController.forAccount(accountId)); + await container + .read(AccountsController.provider.notifier) + .remove(accountId); + return; + } + + final other = accounts.firstWhereOrNull( + (account) => account.id != accountId, + ); + if (other == null) return; + + await container + .read(AccountsController.provider.notifier) + .remove(accountId); + await container + .read(ActiveAccountController.provider.notifier) + .switchTo(other.id); + }); +} diff --git a/lib/helpers/extensions/open_link_info.dart b/lib/helpers/extensions/open_link_info.dart new file mode 100644 index 0000000..60947bb --- /dev/null +++ b/lib/helpers/extensions/open_link_info.dart @@ -0,0 +1,49 @@ +import "package:material_ui/material_ui.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/event.dart"; +import "package:nexus/controllers/room_summary.dart"; +import "package:nexus/helpers/extensions/focus_room.dart"; +import "package:nexus/helpers/extensions/get_link_info.dart"; +import "package:nexus/helpers/extensions/show_user_popover.dart"; +import "package:nexus/models/room_summary.dart"; +import "package:nexus/widgets/rooms/room_summary_sheet.dart"; + +extension OpenLinkInfo on WidgetRef { + Future openLinkInfo( + BuildContext context, + LinkInfo linkInfo, { + String? roomId, + }) async { + final identifier = linkInfo.identifier; + if (identifier.startsWith("@")) { + context.showUserPopover(identifier, roomId: roomId); + return; + } + + final request = RoomSummaryController.provider( + .new(roomIdOrAlias: identifier, via: linkInfo.via), + ); + final summary = await read(request.future) + .onError((_, _) => RoomSummary(roomId: identifier)); + + final eventRowId = linkInfo.eventId == null + ? null + : await read( + EventController.provider( + .new(roomId: summary.roomId, eventId: linkInfo.eventId!), + ).future, + ).onError((_, _) => null); + + if (await focusRoom(summary.roomId, eventRowId) || !context.mounted) return; + + await context.showAdaptiveSheet( + (context) => Consumer( + builder: (context, ref, _) => RoomSummarySheet( + ref.watch(request).whenOrNull(data: (data) => data) ?? summary, + via: linkInfo.via, + ), + ), + ); + } +} diff --git a/lib/helpers/extensions/refocus_after_rebuild.dart b/lib/helpers/extensions/refocus_after_rebuild.dart new file mode 100644 index 0000000..a9ce60d --- /dev/null +++ b/lib/helpers/extensions/refocus_after_rebuild.dart @@ -0,0 +1,9 @@ +import "package:material_ui/material_ui.dart"; + +extension RefocusAfterRebuild on FocusNode { + /// Focuses this again once the text field using it has been replaced. + void refocusAfterRebuild() { + unfocus(); + WidgetsBinding.instance.addPostFrameCallback((_) => requestFocus()); + } +} diff --git a/lib/helpers/extensions/room_destinations.dart b/lib/helpers/extensions/room_destinations.dart index 59bb3d2..3d0323b 100644 --- a/lib/helpers/extensions/room_destinations.dart +++ b/lib/helpers/extensions/room_destinations.dart @@ -2,22 +2,30 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:material_ui/material_ui.dart"; import "package:navigation_rail_m3e/navigation_rail_m3e.dart"; import "package:nexus/models/room.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; + +extension RoomDestination on Room { + NavigationRailM3EDestination toDestination({ + required bool isDm, + String? label, + Widget? icon, + }) => NavigationRailM3EDestination( + label: label ?? metadata?.name ?? "Unnamed Room", + badgeCount: switch (metadata?.unreadNotifications) { + 0 || null => metadata?.unreadMessages == 0 ? null : 0, + int unread => unread, + }, + icon: + icon ?? + AvatarOrHash( + metadata?.avatar, + metadata?.name ?? "Unnamed Room", + fallback: isDm ? null : const Icon(Icons.numbers), + ), + ); +} extension RoomDestinations on IList { List toDestinations({required bool isDm}) => - map( - (room) => NavigationRailM3EDestination( - label: room.metadata?.name ?? "Unnamed Room", - badgeCount: switch (room.metadata?.unreadNotifications) { - 0 || null => room.metadata?.unreadMessages == 0 ? null : 0, - int unread => unread, - }, - icon: AvatarOrHash( - room.metadata?.avatar, - room.metadata?.name ?? "Unnamed Room", - fallback: isDm ? null : const Icon(Icons.numbers), - ), - ), - ).toList(); + map((room) => room.toDestination(isDm: isDm)).toList(); } diff --git a/lib/helpers/extensions/room_image_packs.dart b/lib/helpers/extensions/room_image_packs.dart new file mode 100644 index 0000000..9b9d9ce --- /dev/null +++ b/lib/helpers/extensions/room_image_packs.dart @@ -0,0 +1,34 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:nexus/models/content/content.dart"; +import "package:nexus/models/content/image_pack.dart"; +import "package:nexus/models/event.dart"; +import "package:nexus/models/image_pack.dart"; +import "package:nexus/models/room.dart"; + +extension RoomImagePacks on Room { + /// The room's image packs by state key, preferring the stable type when a + /// pack has both, and leaving out deleted ones. [roomId] names those without + /// a name when the room has none either. + IMap imagePacks(String roomId) => .fromEntries( + const [EventType.legacyImagePack, EventType.imagePack].expand( + (type) => (state[type.type] ?? .new()).entries + .map( + (entry) => switch (events[entry.value]) { + Event(redactedBy: null, content: final ImagePackContent content) + when content.hasContent => + MapEntry( + entry.key, + ImagePack.fromContent( + content, + roomId: roomId, + roomName: metadata?.name ?? roomId, + stateKey: entry.key, + ), + ), + _ => null, + }, + ) + .nonNulls, + ), + ); +} diff --git a/lib/helpers/extensions/room_summary_display.dart b/lib/helpers/extensions/room_summary_display.dart new file mode 100644 index 0000000..7b59a16 --- /dev/null +++ b/lib/helpers/extensions/room_summary_display.dart @@ -0,0 +1,18 @@ +import "package:material_ui/material_ui.dart"; +import "package:nexus/models/content/create.dart"; +import "package:nexus/models/room_summary.dart"; + +extension RoomSummaryDisplay on RoomSummary { + bool get isSpace => roomType == RoomType.space; + + IconData get icon => isSpace ? Icons.workspaces : Icons.numbers; + + String get displayName => + name ?? canonicalAlias ?? (isSpace ? "Unnamed Space" : "Unnamed Room"); + + /// E.g. "Space · 12 members" + String get details => [ + if (isSpace) "Space", + if (joinedMembers case final members?) "$members members", + ].join(" · "); +} diff --git a/lib/helpers/extensions/room_version_at_least.dart b/lib/helpers/extensions/room_version_at_least.dart new file mode 100644 index 0000000..f66d573 --- /dev/null +++ b/lib/helpers/extensions/room_version_at_least.dart @@ -0,0 +1,8 @@ +extension RoomVersionAtLeast on String? { + /// Whether this room version is [version] or newer. Unknown ones, like + /// unstable versions, are assumed to be new enough. + bool versionAtLeast(int version) => switch (int.tryParse(this ?? "")) { + final number? => number >= version, + null => true, + }; +} diff --git a/lib/helpers/extensions/scheme_to_theme.dart b/lib/helpers/extensions/scheme_to_theme.dart index 97d239d..73ce176 100644 --- a/lib/helpers/extensions/scheme_to_theme.dart +++ b/lib/helpers/extensions/scheme_to_theme.dart @@ -20,6 +20,8 @@ extension SchemeToTheme on ColorScheme { shape: RoundedRectangleBorder(borderRadius: .circular(16)), color: surfaceContainerHigh, ), + // So ink at the edges of a sheet doesn't spill past its rounded corners + bottomSheetTheme: .new(clipBehavior: .antiAlias), appBarTheme: AppBarTheme( titleSpacing: 0, backgroundColor: surfaceContainerLow, diff --git a/lib/helpers/extensions/send_failed.dart b/lib/helpers/extensions/send_failed.dart new file mode 100644 index 0000000..cb0ba78 --- /dev/null +++ b/lib/helpers/extensions/send_failed.dart @@ -0,0 +1,6 @@ +import "package:nexus/models/event.dart"; + +extension SendFailed on Event { + /// gomuks marks events that are still sending as "not sent" (and often forgets to clear it at all) + bool get sendFailed => sendError != null && sendError != "not sent"; +} diff --git a/lib/helpers/extensions/show_about_sheet.dart b/lib/helpers/extensions/show_about_sheet.dart index ee49283..951b07d 100644 --- a/lib/helpers/extensions/show_about_sheet.dart +++ b/lib/helpers/extensions/show_about_sheet.dart @@ -1,9 +1,8 @@ import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; -import "package:nexus/widgets/sheet_layout.dart"; import "package:flutter_svg/flutter_svg.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:m3e_card_list/m3e_card_list.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/helpers/launch_helper.dart"; import "package:package_info_plus/package_info_plus.dart"; diff --git a/lib/helpers/extensions/show_adaptive_menu.dart b/lib/helpers/extensions/show_adaptive_menu.dart deleted file mode 100644 index 2fe21f5..0000000 --- a/lib/helpers/extensions/show_adaptive_menu.dart +++ /dev/null @@ -1,52 +0,0 @@ -import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/global_rect.dart"; -import "package:nexus/helpers/extensions/is_desktop.dart"; - -extension ShowAdaptiveMenu on BuildContext { - /// Shows [items] in a popup menu on desktop, or a bottom sheet on mobile. - /// - /// On desktop, the menu opens at [globalPosition] if given (e.g. where the - /// user right clicked), or over the widget this context belongs to. - Future showAdaptiveMenu( - List items, { - Offset? globalPosition, - }) async { - if (!isDesktop) { - await showModalBottomSheet( - context: this, - isScrollControlled: true, - showDragHandle: true, - builder: (context) => SafeArea( - child: SingleChildScrollView( - padding: const .only(bottom: 8), - // PopupMenuItems must be inside something with the menu role - child: Semantics( - role: .menu, - explicitChildNodes: true, - child: ListTileTheme.merge( - contentPadding: const .symmetric(horizontal: 24), - minTileHeight: 48, - titleTextStyle: Theme.of(context).textTheme.titleMedium, - child: Column(mainAxisSize: .min, children: items), - ), - ), - ), - ), - ); - return; - } - - final overlay = Overlay.of(this).context.findRenderObject() as RenderBox; - final anchor = switch (globalPosition) { - final position? => position & Size.zero, - null => globalRect, - }; - - await showMenu( - context: this, - constraints: .loose(.infinite), - position: .fromRect(anchor, Offset.zero & overlay.size), - items: items, - ); - } -} diff --git a/lib/helpers/extensions/show_adaptive_popover.dart b/lib/helpers/extensions/show_adaptive_popover.dart deleted file mode 100644 index 8a100e8..0000000 --- a/lib/helpers/extensions/show_adaptive_popover.dart +++ /dev/null @@ -1,35 +0,0 @@ -import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/global_rect.dart"; -import "package:nexus/helpers/extensions/is_desktop.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; -import "package:nexus/widgets/popover_layout.dart"; - -extension ShowAdaptivePopover on BuildContext { - /// Shows the widget from [builder] in a popover next to the widget this - /// context belongs to on desktop, or a bottom sheet on mobile. Use the - /// context passed to [builder] to close it. - Future showAdaptivePopover(WidgetBuilder builder) { - if (!isDesktop) return showAdaptiveSheet(builder); - - final anchor = globalRect; - - return showDialog( - context: this, - barrierColor: Colors.transparent, - useSafeArea: false, - builder: (context) => CustomSingleChildLayout( - delegate: PopoverLayout(anchor), - child: ConstrainedBox( - constraints: const .new(maxWidth: 420, maxHeight: 600), - child: Material( - elevation: 8, - clipBehavior: .antiAlias, - color: Theme.of(context).colorScheme.surfaceContainer, - borderRadius: .circular(16), - child: Builder(builder: builder), - ), - ), - ), - ); - } -} diff --git a/lib/helpers/extensions/show_adaptive_sheet.dart b/lib/helpers/extensions/show_adaptive_sheet.dart deleted file mode 100644 index 1e916a2..0000000 --- a/lib/helpers/extensions/show_adaptive_sheet.dart +++ /dev/null @@ -1,24 +0,0 @@ -import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/is_desktop.dart"; - -extension ShowAdaptiveSheet on BuildContext { - /// Shows the widget from [builder] in a dialog on desktop, or a bottom sheet - /// on mobile. Use the context passed to [builder] to close it. - Future showAdaptiveSheet(WidgetBuilder builder) => isDesktop - ? showDialog( - context: this, - builder: (context) => Dialog( - clipBehavior: .antiAlias, - child: ConstrainedBox( - constraints: const .new(maxWidth: 450, maxHeight: 600), - child: Builder(builder: builder), - ), - ), - ) - : showModalBottomSheet( - context: this, - isScrollControlled: true, - constraints: .new(maxHeight: MediaQuery.sizeOf(this).height - 80), - builder: (context) => SafeArea(child: builder(context)), - ); -} diff --git a/lib/helpers/extensions/show_image_viewer.dart b/lib/helpers/extensions/show_image_viewer.dart new file mode 100644 index 0000000..9be95b8 --- /dev/null +++ b/lib/helpers/extensions/show_image_viewer.dart @@ -0,0 +1,83 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:m3e_buttons/m3e_buttons.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/helpers/extensions/save_attachment.dart"; +import "package:nexus/helpers/extensions/size_to_string.dart"; +import "package:nexus/helpers/mxc_image.dart"; +import "package:nexus/models/requests/download_media.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; + +extension ShowImageViewer on BuildContext { + /// Shows the image from [request] fullscreen, zoomable. + /// + /// If [downloadFilename] is set, a download button is shown, suggesting it. + void showImageViewer( + WidgetRef ref, + DownloadMediaRequest request, { + String? downloadFilename, + int? size, + }) => showDialog( + context: this, + builder: (context) => SafeArea( + child: Stack( + children: [ + Positioned.fill( + child: GestureDetector( + onTap: Navigator.of(context).pop, + child: InteractiveViewer( + maxScale: 10, + child: Image( + errorBuilder: (_, error, stackTrace) => ErrorDialog( + "Loading failed for ${request.mxc}\nError: $error", + stackTrace, + ), + image: MxcImage(ref, request), + ), + ), + ), + ), + if (size != null) + Align( + alignment: .topLeft, + child: Padding( + padding: .all(32), + child: Card( + margin: .zero, + child: Padding( + padding: .symmetric(horizontal: 12, vertical: 8), + child: Text(size.sizeAsString), + ), + ), + ), + ), + Align( + alignment: .topRight, + child: Padding( + padding: .all(32), + child: Row( + mainAxisSize: .min, + spacing: 8, + children: [ + if (downloadFilename != null) + M3EButton( + onPressed: () => context.saveAttachment( + ref, + request.mxc, + encrypted: request.encrypted, + filename: downloadFilename, + ), + child: Icon(Icons.download), + ), + M3EButton( + onPressed: Navigator.of(context).pop, + child: Icon(Icons.close), + ), + ], + ), + ), + ), + ], + ), + ), + ); +} diff --git a/lib/helpers/extensions/show_leave_room_sheet.dart b/lib/helpers/extensions/show_leave_room_sheet.dart index 7dd8d3a..42ff87f 100644 --- a/lib/helpers/extensions/show_leave_room_sheet.dart +++ b/lib/helpers/extensions/show_leave_room_sheet.dart @@ -1,9 +1,8 @@ import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; import "package:nexus/helpers/extensions/with_progress_snackbar.dart"; -import "package:nexus/widgets/sheet_layout.dart"; extension ShowLeaveRoomSheet on BuildContext { /// Asks the user to confirm leaving the room, then leaves it. diff --git a/lib/helpers/extensions/show_user_popover.dart b/lib/helpers/extensions/show_user_popover.dart index a56417e..e7018c0 100644 --- a/lib/helpers/extensions/show_user_popover.dart +++ b/lib/helpers/extensions/show_user_popover.dart @@ -1,8 +1,11 @@ import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/show_adaptive_popover.dart"; -import "package:nexus/widgets/user_bottom_sheet.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/widgets/users/user_bottom_sheet.dart"; extension ShowUserPopover on BuildContext { - void showUserPopover(String userId, {String? roomId}) => - showAdaptivePopover((context) => UserBottomSheet(userId, roomId: roomId)); + void showUserPopover(String userId, {String? roomId, Rect? anchor}) => + showAdaptivePopover( + (context) => UserBottomSheet(userId, roomId: roomId), + anchor: anchor, + ); } diff --git a/lib/helpers/extensions/success_scheme.dart b/lib/helpers/extensions/success_scheme.dart new file mode 100644 index 0000000..77f83ae --- /dev/null +++ b/lib/helpers/extensions/success_scheme.dart @@ -0,0 +1,11 @@ +import "package:dynamic_color/dynamic_color.dart"; +import "package:material_ui/material_ui.dart"; + +extension SuccessScheme on ThemeData { + /// Green colors for positive things, like accepting knocks or new pins, + /// harmonized so they fit the current theme. + ColorScheme get successScheme => ColorScheme.fromSeed( + seedColor: Colors.green.harmonizeWith(colorScheme.primary), + brightness: brightness, + ); +} diff --git a/lib/helpers/extensions/thread_events.dart b/lib/helpers/extensions/thread_events.dart new file mode 100644 index 0000000..31c7808 --- /dev/null +++ b/lib/helpers/extensions/thread_events.dart @@ -0,0 +1,50 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:nexus/helpers/extensions/event_id_is_fake.dart"; +import "package:nexus/models/event.dart"; +import "package:nexus/models/room.dart"; + +typedef ThreadInfo = ({int count, Event? latest}); +typedef Thread = ({Event root, ThreadInfo info}); + +extension ThreadEvents on Room { + /// The threads in the loaded events, most recently active first. + IList get threads { + DateTime lastActive(Thread thread) => + thread.info.latest?.timestamp ?? thread.root.timestamp; + + return events.values + .where((event) => event.threadCount > 0) + .map((root) => (root: root, info: thread(root))) + .sorted((a, b) => lastActive(b).compareTo(lastActive(a))) + .toIList(); + } + + /// The events in the thread from [threadRoot], oldest first, without the + /// root itself. + IList threadEvents(String threadRoot) => + (relations[threadRoot] ?? const .empty()) + .map((rowId) => events[rowId]) + .nonNulls + .where( + (event) => + event.threadRoot == threadRoot && + (!event.eventId.isFake || clientSticky.contains(event.rowId)), + ) + .sorted((a, b) => a.timestamp.compareTo(b.timestamp)) + .toIList(); + + /// How many replies the thread from [root] has, and its latest event, from + /// gomuks' aggregate on it + ThreadInfo thread(Event root) => + (count: root.threadCount, latest: events[root.threadLatestRowId]); + + /// The latest event in the thread from [threadRoot], if it's loaded. + Event? latestThreadEvent(String threadRoot) => switch (eventIds[threadRoot]) { + final rowId? => switch (events[rowId]) { + final root? => thread(root).latest, + null => null, + }, + null => null, + }; +} diff --git a/lib/helpers/extensions/weighted_search.dart b/lib/helpers/extensions/weighted_search.dart new file mode 100644 index 0000000..1f76b0a --- /dev/null +++ b/lib/helpers/extensions/weighted_search.dart @@ -0,0 +1,47 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; + +extension WeightedSearch on Iterable { + /// The items with a field matching [query], best match first. + IList search( + String query, + Iterable<(String?, int)> Function(T item) fieldsOf, + ) { + final needle = query.trim().toLowerCase(); + if (needle.isEmpty) return toIList(); + + int qualityOf(String text) { + final haystack = text.toLowerCase(); + if (haystack == needle) return 4; + if (haystack.startsWith(needle)) return 3; + if (haystack + .split(RegExp(r"[\s_\-:/.@#!]+")) + .any((w) => w.startsWith(needle))) { + return 2; + } + if (haystack.contains(needle)) return 1; + return 0; + } + + return .new( + map( + (item) => ( + item, + fieldsOf(item) + .map( + (field) => switch (field) { + (final text?, final weight) => + qualityOf(text) * weight, + (null, _) => 0, + }, + ) + .maxOrNull ?? + 0, + ), + ) + .where((scored) => scored.$2 > 0) + .sortedBy((scored) => -scored.$2) + .map((scored) => scored.$1), + ); + } +} diff --git a/lib/helpers/extensions/with_latest_edit.dart b/lib/helpers/extensions/with_latest_edit.dart new file mode 100644 index 0000000..6b07313 --- /dev/null +++ b/lib/helpers/extensions/with_latest_edit.dart @@ -0,0 +1,20 @@ +import "package:nexus/models/event.dart"; +import "package:nexus/models/room.dart"; + +extension WithLatestEdit on Room { + Event? withLatestEdit(int rowId) { + final event = events[rowId]; + if (event == null) return null; + + final edited = event.lastEditRowId == 0 + ? null + : events[event.lastEditRowId]; + + return edited == null + ? event + : event.copyWith( + content: edited.content, + localContent: edited.localContent, + ); + } +} diff --git a/lib/helpers/hooks/chat_composer.dart b/lib/helpers/hooks/chat_composer.dart new file mode 100644 index 0000000..44b5352 --- /dev/null +++ b/lib/helpers/hooks/chat_composer.dart @@ -0,0 +1,54 @@ +import "package:flutter/services.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/composer_draft.dart"; +import "package:nexus/helpers/extensions/refocus_after_rebuild.dart"; +import "package:nexus/models/composer_params.dart"; +import "package:nexus/models/relation_type.dart"; + +final class ChatComposer({ + required final int? relatedEvent, + required final RelationType relationType, + required final ComposerDraftController notifier, + required final FocusNode node, +}) { + factory use(WidgetRef ref, ComposerParams composer) { + final provider = ComposerDraftController.provider(composer); + final node = useFocusNode( + onKeyEvent: (node, event) { + if (event is KeyDownEvent && event.logicalKey == .escape) { + final isEditing = ref.read(provider).isEditing; + ref.read(provider.notifier).dismiss(); + // Ending an edit replaces the text field + if (isEditing) node.refocusAfterRebuild(); + return .handled; + } + + return .ignored; + }, + ); + final (relatedEvent, relationType) = ref.watch( + provider.select((draft) => (draft.relatedEvent, draft.relationType)), + ); + + return .new( + relatedEvent: relatedEvent, + relationType: relationType, + notifier: ref.watch(provider.notifier), + node: node, + ); + } + + int? get repliedEventRowId => relationType == .reply ? relatedEvent : null; + + void relate(int rowId, RelationType type) { + notifier.relate(rowId, type); + // Starting or ending an edit replaces the text field + if (type == .edit || relationType == .edit) { + node.refocusAfterRebuild(); + } else { + node.requestFocus(); + } + } +} diff --git a/lib/helpers/hooks/chat_scroll.dart b/lib/helpers/hooks/chat_scroll.dart index 50d9a32..77d688a 100644 --- a/lib/helpers/hooks/chat_scroll.dart +++ b/lib/helpers/hooks/chat_scroll.dart @@ -14,7 +14,10 @@ final class ChatScroll({ required final IList liveRows, required final GlobalKey centerKey, required final ScrollController scrollController, + required final bool atBottom, + required final int? highlightedEvent, + required final JumpToEvent jumpToEvent, required final Future Function() jumpToBottom, required final GlobalKey Function(int eventRowId) keyFor, @@ -28,6 +31,8 @@ final class ChatScroll({ final anchorId = useState(null); final atBottom = useState(true); final pendingJump = useState(null); + final highlightedEvent = useState(null); + final hookContext = useContext(); final pendingJumpDone = useRef?>(null); void finishPendingJump() { pendingJumpDone.value?.complete(); @@ -95,17 +100,23 @@ final class ChatScroll({ final anchorIndex = items.indexOf(anchor); - if (anchorIndex == -1) return (history: const .empty(), live: items); - + final historyLength = anchorIndex == -1 ? items.length : anchorIndex + 1; return ( - history: items.take(anchorIndex).toIList().reversed.toIList(), - live: items.skip(anchorIndex).toIList(), + history: items.take(historyLength).toIList().reversed.toIList(), + live: items.skip(historyLength).toIList(), ); }, [controllerData, anchorId.value]); - final lastRowId = split.live.lastOrNull; + final lastRowId = controllerData.value?.timeline.lastOrNull; final previousLastRowId = useRef(null); + void updateAtBottom() { + if (!hookContext.mounted || !scrollController.hasClients) return; + + final isAtBottom = scrollController.position.extentBefore <= 0; + if (isAtBottom != atBottom.value) atBottom.value = isAtBottom; + } + useEffect(() { final previous = previousLastRowId.value; previousLastRowId.value = lastRowId; @@ -118,7 +129,12 @@ final class ChatScroll({ WidgetsBinding.instance.addPostFrameCallback((_) { if (!scrollController.hasClients) return; - scrollController.jumpTo(scrollController.position.minScrollExtent); + anchorId.value = lastRowId; + scrollController.position.correctPixels(0); + + // Other callbacks this frame still see the new event below the old + // anchor, so they think it isn't at the bottom until the next frame + WidgetsBinding.instance.addPostFrameCallback((_) => updateAtBottom()); }); return null; @@ -132,9 +148,7 @@ final class ChatScroll({ if (!scrollController.hasClients) return; final position = scrollController.position; - - final isAtBottom = position.extentBefore <= 0; - if (isAtBottom != atBottom.value) atBottom.value = isAtBottom; + updateAtBottom(); // contextualEvent updates immediately when jumping, but // controllerData is only for the historical timeline once it loads @@ -146,10 +160,12 @@ final class ChatScroll({ await paginate(.backward); } else if (isHistorical && position.extentBefore <= loadThreshold) { await paginate(.forward); - } else if (position.extentBefore <= 0) { - await markRead(); } + if (!hookContext.mounted || !scrollController.hasClients) return; + + if (!isHistorical && position.extentBefore <= 0) await markRead(); + if (controllerData.isLoading == false && position.extentBefore <= 0 && controllerData.value?.hasMoreForward == false && @@ -173,37 +189,49 @@ final class ChatScroll({ ], ); + Future scrollToEvent(int rowId) async { + if (!scrollController.hasClients) return; + + final context = keyFor(rowId).currentContext; + if (context != null) { + await Scrollable.ensureVisible( + context, + alignment: 0.5, + duration: Durations.extralong1, + curve: Curves.easeInOut, + ); + return; + } + + finishPendingJump(); + final done = pendingJumpDone.value = Completer(); + pendingJump.value = rowId; + if (controllerData.value?.timeline.contains(rowId) ?? false) { + anchorId.value = rowId; + } else { + anchorId.value = null; + contextualEvent.value = rowId; + } + await done.future; + } + return .new( historyRows: split.history, liveRows: split.live, centerKey: centerKey, scrollController: scrollController, - atBottom: atBottom.value, + atBottom: atBottom.value && contextualEvent.value == null, + highlightedEvent: highlightedEvent.value, keyFor: keyFor, jumpToEvent: (int rowId) async { - if (!scrollController.hasClients) return; + highlightedEvent.value = rowId; - final context = keyFor(rowId).currentContext; - if (context != null) { - await Scrollable.ensureVisible( - context, - alignment: 0.5, - duration: Durations.extralong1, - curve: Curves.easeInOut, - ); - return; - } - - finishPendingJump(); - final done = pendingJumpDone.value = Completer(); - pendingJump.value = rowId; - if (controllerData.value?.timeline.contains(rowId) ?? false) { - anchorId.value = rowId; - } else { - anchorId.value = null; - contextualEvent.value = rowId; - } - await done.future; + await scrollToEvent(rowId); + await Future.delayed(Durations.extralong1, () { + if (hookContext.mounted && highlightedEvent.value == rowId) { + highlightedEvent.value = null; + } + }); }, jumpToBottom: () async { finishPendingJump(); diff --git a/lib/helpers/hooks/tap_recognizer.dart b/lib/helpers/hooks/tap_recognizer.dart new file mode 100644 index 0000000..97c5534 --- /dev/null +++ b/lib/helpers/hooks/tap_recognizer.dart @@ -0,0 +1,11 @@ +import "package:flutter/gestures.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; + +/// A recognizer for a tappable span in text, like a name, disposed with the +/// widget. +TapGestureRecognizer useTapRecognizer() { + final recognizer = useMemoized(TapGestureRecognizer.new); + useEffect(() => recognizer.dispose, [recognizer]); + + return recognizer; +} diff --git a/lib/helpers/launch_helper.dart b/lib/helpers/launch_helper.dart index 89c7015..82f1806 100644 --- a/lib/helpers/launch_helper.dart +++ b/lib/helpers/launch_helper.dart @@ -1,17 +1,30 @@ import "package:flutter/services.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/helpers/extensions/show_error_snack_bar.dart"; +import "package:nexus/main.dart"; import "package:url_launcher/url_launcher.dart" as ul; class LaunchHelper(Ref ref) { Future launchUrl(Uri url, {bool useWebview = false}) async { - try { - return await ul.launchUrl( - url, - mode: useWebview ? .inAppBrowserView : .externalApplication, + final launched = await ul + .launchUrl( + url, + mode: useWebview ? .inAppBrowserView : .externalApplication, + ) + .catchError((_) => false, test: (error) => error is PlatformException); + + if (navigatorKey.currentContext case final context? + when !launched && context.mounted) { + ScaffoldMessenger.of(context).showErrorSnackBar( + "Couldn't open $url. Is there a browser installed?", + action: ( + label: "Copy link", + onPressed: () => Clipboard.setData(.new(text: url.toString())), + ), ); - } on PlatformException catch (_) { - return false; } + return launched; } static final provider = Provider(LaunchHelper.new); diff --git a/lib/helpers/matrix_linkifier.dart b/lib/helpers/matrix_linkifier.dart new file mode 100644 index 0000000..addf468 --- /dev/null +++ b/lib/helpers/matrix_linkifier.dart @@ -0,0 +1,38 @@ +import "package:linkify/linkify.dart"; + +/// Splits [text] into plain text and URL, `matrix:` and email links. +List linkifyText(String text) => linkify( + text, + options: const LinkifyOptions(humanize: false), + linkifiers: const [UrlLinkifier(), MatrixLinkifier(), EmailLinkifier()], +); + +/// Linkifies `matrix:` URIs, which [UrlLinkifier] only handles for http(s). +final class const MatrixLinkifier() extends Linkifier { + static final _regex = RegExp( + r"\bmatrix:[^\s<>\x22\x27]*[^\s<>\x22\x27.,;:!?)\]}]", + caseSensitive: false, + ); + + @override + List parse( + List elements, + LinkifyOptions options, + ) => elements + .expand( + (element) => element is TextElement ? _split(element.text) : [element], + ) + .toList(); + + Iterable _split(String text) sync* { + var start = 0; + for (final match in _regex.allMatches(text)) { + if (match.start > start) { + yield TextElement(text.substring(start, match.start)); + } + yield UrlElement(match[0]!); + start = match.end; + } + if (start < text.length) yield TextElement(text.substring(start)); + } +} diff --git a/lib/helpers/mxc_image.dart b/lib/helpers/mxc_image.dart index 4013397..d82d485 100644 --- a/lib/helpers/mxc_image.dart +++ b/lib/helpers/mxc_image.dart @@ -1,6 +1,7 @@ import "dart:async"; import "dart:io"; import "dart:isolate"; +import "dart:typed_data"; import "dart:ui" as ui; import "package:avif_native/avif_native.dart"; @@ -20,20 +21,28 @@ class MxcImage(final WidgetRef ref, final DownloadMediaRequest request) MultiFrameImageStreamCompleter(codec: _loadAsync(decode), scale: 1.0); Future _loadAsync(ImageDecoderCallback decode) async { - final file = await ref - .read(ClientController.provider.notifier) - .downloadMedia(request); - final bytes = await File(file.path).readAsBytes(); + try { + final file = await ref + .read(ClientController.provider.notifier) + .downloadMedia(request); + final bytes = await File(file.path).readAsBytes(); - // Flutter can't decode AVIF on Linux/Windows (or older Android/iOS), so we do it ourselves - if (String.fromCharCodes(bytes.skip(4).take(8)) - case "ftypavif" || "ftypavis") { - return AvifCodec(await Isolate.run(() => decodeAvif(bytes))); + // Flutter can't decode AVIF on Linux/Windows (or older Android/iOS), so we do it ourselves + if (String.fromCharCodes(bytes.skip(4).take(8)) + case "ftypavif" || "ftypavis") { + return AvifCodec(await _decodeAvifInIsolate(bytes)); + } + + return await decode(await .fromUint8List(bytes)); + } catch (_) { + scheduleMicrotask(() => PaintingBinding.instance.imageCache.evict(this)); + rethrow; } - - return decode(await .fromUint8List(bytes)); } + static Future _decodeAvifInIsolate(Uint8List bytes) => + Isolate.run(() => decodeAvif(bytes)); + @override bool operator ==(Object other) => other is MxcImage && other.request == request; diff --git a/lib/main.dart b/lib/main.dart index 5cd2129..299e95a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -4,7 +4,7 @@ import "package:dynamic_color/dynamic_color.dart"; import "package:flutter/foundation.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:material_emoji_picker/material_emoji_picker.dart"; -import "package:media_kit/media_kit.dart"; +import "package:nexus/controllers/active_account.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/controllers/gomuks_listener.dart"; @@ -20,9 +20,10 @@ import "package:nexus/widgets/pages/chat.dart"; import "package:nexus/widgets/pages/select_server.dart"; import "package:nexus/widgets/pages/settings.dart"; import "package:nexus/widgets/pages/verify.dart"; -import "package:nexus/widgets/appbar.dart"; -import "package:nexus/widgets/error_dialog.dart"; -import "package:nexus/widgets/loading.dart"; +import "package:nexus/widgets/account_scope.dart"; +import "package:nexus/widgets/common/appbar.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/widgets/common/loading.dart"; import "package:window_manager/window_manager.dart"; import "package:material_ui/material_ui.dart"; @@ -44,7 +45,11 @@ New Value: ${newValue is AsyncData ? newValue.value : newValue} } void showError(Object error, [StackTrace? stackTrace]) { - if (error.toString().contains("'_nextFrame != null': is not true.")) { + // Harmless Flutter race in animated images (the assert in debug, a null check in release) + if (error.toString().contains("'_nextFrame != null': is not true.") || + stackTrace.toString().contains( + "MultiFrameImageStreamCompleter._handleAppFrame", + )) { return; } @@ -63,7 +68,6 @@ void showError(Object error, [StackTrace? stackTrace]) { void main(List args) async { WidgetsFlutterBinding.ensureInitialized(); - MediaKit.ensureInitialized(); LicenseRegistry.addLicense(() => .fromIterable(fontLicenses)); @@ -74,10 +78,17 @@ void main(List args) async { Platform.environment["FLUTTER_HEADLESS"] != null || args.contains("--unifiedpush-bg"); + final accountId = await ActiveAccountController.stored(); + if (isInBackground) { - await ProviderContainer() - .read(UnifiedPushController.provider.future) - .timeout(Duration(seconds: 5)); + await ProviderContainer( + overrides: [ + // Nothing to switch to in the background + ActiveAccountController.provider.overrideWith( + () => ActiveAccountController(accountId, (_) {}), + ), + ], + ).read(UnifiedPushController.provider.future).timeout(Duration(seconds: 5)); await Future.delayed(Duration(seconds: 10)); exit(0); @@ -86,11 +97,12 @@ void main(List args) async { WindowManager.instance.getCurrent() ?..titleBarStyle = .hidden ..isWindowControlButtonsVisible = false - ..minimumSize = Size.square(300).toNative(); + ..minimumSize = Size.square(320).toNative(); } runApp( - ProviderScope( + AccountScope( + initialAccountId: accountId, retry: (_, _) => null, observers: [ // Change false to true if you want debug information on provider reloads @@ -147,7 +159,7 @@ class const App({super.key}) extends StatelessWidget { .watch(SettingsController.provider) .maybeWhen( data: (settings) => settings.theme, - orElse: () => ThemeMode.system, + orElse: () => .system, ), home: child, ); @@ -160,8 +172,8 @@ class const App({super.key}) extends StatelessWidget { MultiProviderController.provider( .new([ GomuksListenerController.provider, - NotificationController.provider, UnifiedPushController.provider, + NotificationController.provider, MemberListOpenedController.provider, KeyController.provider(KeyController.roomKey), KeyController.provider(KeyController.spaceKey), diff --git a/lib/models/account.dart b/lib/models/account.dart new file mode 100644 index 0000000..a171bda --- /dev/null +++ b/lib/models/account.dart @@ -0,0 +1,26 @@ +import "package:freezed_annotation/freezed_annotation.dart"; + +part "account.freezed.dart"; +part "account.g.dart"; + +/// An account slot, each with its own gomuks directories. +/// +/// Everything but [id] is cached from the last time the account was active, so +/// the account switcher and push routing work while it isn't. +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const Account({ + required final String id, + final String? userId, + final String? deviceId, + final String? displayName, + final Uri? avatar, +}) with _$Account { + /// The slot accounts from before account switching existed + static const String legacyId = "default"; + + Map toJson() => _$AccountToJson(this); + + factory Account.fromJson(Map json) => + _$AccountFromJson(json); +} diff --git a/lib/models/account_data.dart b/lib/models/account_data.dart index 0ab5990..51176cd 100644 --- a/lib/models/account_data.dart +++ b/lib/models/account_data.dart @@ -1,5 +1,6 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/push_rules.dart"; part "account_data.freezed.dart"; part "account_data.g.dart"; @@ -16,10 +17,27 @@ class const AccountData({ @JsonKey(name: AccountData.recentEmojiKey) final RecentEmojiData recentEmoji = const RecentEmojiData(), + + /// Room image packs the user has enabled everywhere + @JsonKey(name: AccountData.imagePackRoomsKey) + final ImagePackRooms? imagePackRooms, + @JsonKey(name: AccountData.legacyImagePackRoomsKey) + final ImagePackRooms? legacyImagePackRooms, + @JsonKey(name: AccountData.pushRulesKey) + final PushRules pushRules = const .new(), + @JsonKey(name: AccountData.ignoredUserListKey) + final IgnoredUserList ignoredUserList = const .new(), }) with _$AccountData { static const invitePermissionConfigKey = "m.invite_permission_config"; static const directKey = "m.direct"; static const recentEmojiKey = "m.recent_emoji"; + static const imagePackRoomsKey = "m.image_pack.rooms"; + static const legacyImagePackRoomsKey = "im.ponies.emote_rooms"; + static const pushRulesKey = "m.push_rules"; + static const ignoredUserListKey = "m.ignored_user_list"; + + ImagePackRooms get enabledImagePacks => + imagePackRooms ?? legacyImagePackRooms ?? const .new(); Map toJson() => _$AccountDataToJson(this); @@ -38,6 +56,63 @@ class const RecentEmojiData({ _$RecentEmojiDataFromJson(json); } +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const ImagePackRooms({ + /// Room IDs to the state keys of their enabled packs, each to a (currently + /// empty) object + final IMap>> rooms = const .empty(), +}) with _$ImagePackRooms { + bool contains(String roomId, String stateKey) => + rooms[roomId]?.containsKey(stateKey) ?? false; + + ImagePackRooms withPack( + String roomId, + String stateKey, { + required bool enabled, + }) { + final packs = + rooms[roomId] ?? const IMap>.empty(); + final updated = switch ((enabled, packs.containsKey(stateKey))) { + (true, false) => packs.add(stateKey, const {}), + (false, true) => packs.remove(stateKey), + _ => packs, + }; + + return copyWith( + rooms: updated.isEmpty + ? rooms.remove(roomId) + : rooms.add(roomId, updated), + ); + } + + Map toJson() => _$ImagePackRoomsToJson(this); + + factory ImagePackRooms.fromJson(Map json) => + _$ImagePackRoomsFromJson(json); +} + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const IgnoredUserList({ + /// Blocked user IDs, each to a (currently empty) object + @JsonKey(name: "ignored_users") + final IMap> ignoredUsers = const .empty(), +}) with _$IgnoredUserList { + bool contains(String userId) => ignoredUsers.containsKey(userId); + + IgnoredUserList withUser(String userId, {required bool ignored}) => copyWith( + ignoredUsers: ignored + ? ignoredUsers.add(userId, const {}) + : ignoredUsers.remove(userId), + ); + + Map toJson() => _$IgnoredUserListToJson(this); + + factory IgnoredUserList.fromJson(Map json) => + _$IgnoredUserListFromJson(json); +} + @Freezed(toJson: false, fromJson: false) @JsonSerializable() class const InvitePermissionConfig({ diff --git a/lib/models/bot_argument_suggestion.dart b/lib/models/bot_argument_suggestion.dart new file mode 100644 index 0000000..4b27cce --- /dev/null +++ b/lib/models/bot_argument_suggestion.dart @@ -0,0 +1,13 @@ +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/room.dart"; + +part "bot_argument_suggestion.freezed.dart"; + +@Freezed(toJson: false, fromJson: false) +class const BotArgumentSuggestion({ + required final String title, + final String? subtitle, + final Uri? avatar, + required final String text, + final Room? room, +}) with _$BotArgumentSuggestion; diff --git a/lib/models/bot_command.dart b/lib/models/bot_command.dart new file mode 100644 index 0000000..e25f4dd --- /dev/null +++ b/lib/models/bot_command.dart @@ -0,0 +1,38 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/content/bot_command_description.dart"; + +part "bot_command.freezed.dart"; + +@Freezed(toJson: false, fromJson: false) +class const BotCommand({ + required final String sender, + required final String botName, + final Uri? botAvatar, + required final BotCommandDescriptionContent description, +}) with _$BotCommand { + /// Commands gomuks handles itself, which bots can't override. + static const builtIn = ISetConst({ + "me", + "notice", + "timestamp", + "unencrypted", + "rawinputbody", + "rainbow", + "plain", + "html", + "htmlmd", + }); + + static const gomuksSender = "@gomuks"; + + String get prefix => "/${description.command}"; + String get about => [botName, ?description.description].join(" · "); + + bool completes(String text) => + text.startsWith("/") && + (prefix.startsWith(text) || argumentsIn(text) != null); + + String? argumentsIn(String text) => + text.startsWith("$prefix ") ? text.substring(prefix.length + 1) : null; +} diff --git a/lib/models/bot_command_draft.dart b/lib/models/bot_command_draft.dart new file mode 100644 index 0000000..d8339e0 --- /dev/null +++ b/lib/models/bot_command_draft.dart @@ -0,0 +1,104 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/bot_command.dart"; +import "package:nexus/models/composer_params.dart"; +import "package:nexus/models/content/bot_command.dart"; +import "package:nexus/models/content/bot_command_description.dart"; + +part "bot_command_draft.freezed.dart"; + +@Freezed(toJson: false, fromJson: false) +class const BotCommandDraft({ + required final BotCommand command, + required final ComposerParams composer, + final IMap texts = const .empty(), + + // The servers to join rooms picked from suggestions through, by room ID + final IMap> vias = const .empty(), + final ISet options = const .empty(), + final String? focused, +}) with _$BotCommandDraft { + IList get shown => command.description.parameters + .where( + (parameter) => !parameter.optional || options.contains(parameter.key), + ) + .toIList(); + + IList get hiddenOptions => command.description.parameters + .where( + (parameter) => parameter.optional && !options.contains(parameter.key), + ) + .toIList(); + + BotParameter? get focusedParameter => command.description.parameters + .firstWhereOrNull((parameter) => parameter.key == focused); + + ({Object? value, String? error}) parse(BotParameter parameter) => parameter + .schema + .parseText(texts[parameter.key] ?? "", roomId: composer.roomId); + + IMap get arguments => .fromEntries( + shown + .map( + (parameter) => switch (parse(parameter).value) { + final value? => MapEntry(parameter.key, withVias(value)), + null => null, + }, + ) + .nonNulls, + ); + + IMap get errors => .fromEntries( + shown + .map( + (parameter) => switch (parse(parameter).error) { + final error? => MapEntry(parameter.key, error), + null => null, + }, + ) + .nonNulls, + ); + + IList get missing => shown + .where( + (parameter) => !parameter.optional && parse(parameter).value == null, + ) + .toIList(); + + String? get problem => errors.isNotEmpty + ? errors.entries.map((error) => "${error.key}: ${error.value}").join("\n") + : missing.isNotEmpty + ? "Fill in ${missing.map((parameter) => parameter.key).join(", ")} first." + : null; + + BotCommandInput get input => + .new(command: command.description.command, arguments: arguments); + + String get body => [ + command.prefix, + ...shown + .map( + (parameter) => switch (texts[parameter.key] + ?.split(BotParameterSchema.separator) + .where((part) => part.isNotEmpty) + .join(" ")) { + final text? when text.isEmpty => null, + final text? when parameter.optional => "--${parameter.key} $text", + final text => text, + }, + ) + .nonNulls, + ].join(" "); + + Object withVias(Object value) => switch (value) { + List() => value.whereType().map(withVias).toList(), + final Map room && {"type": "room_id", "id": final String id} + when !room.containsKey("via") => + switch (vias[id]) { + final via? => {...room, "via": via.unlock}, + null => room, + }, + _ => value, + }; +} diff --git a/lib/models/capabilities.dart b/lib/models/capabilities.dart index 6830170..cdf86b7 100644 --- a/lib/models/capabilities.dart +++ b/lib/models/capabilities.dart @@ -1,3 +1,4 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:freezed_annotation/freezed_annotation.dart"; part "capabilities.freezed.dart"; @@ -7,6 +8,7 @@ part "capabilities.g.dart"; @JsonSerializable() class const Capabilities({ @JsonKey(name: "org.matrix.msc4174.webpush") final WebPush? webpush, + @JsonKey(name: "m.room_versions") final RoomVersions? roomVersions, }) with _$Capabilities { Map toJson() => _$CapabilitiesToJson(this); @@ -23,3 +25,30 @@ class const WebPush({required final bool enabled, final String? vapid}) factory WebPush.fromJson(Map json) => _$WebPushFromJson(json); } + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const RoomVersions({ + @JsonKey(name: "default") required final String defaultVersion, + @JsonKey(fromJson: RoomVersionStability.mapFromJson) + required final IMap available, +}) with _$RoomVersions { + Map toJson() => _$RoomVersionsToJson(this); + + factory RoomVersions.fromJson(Map json) => + _$RoomVersionsFromJson(json); +} + +enum RoomVersionStability { + stable, + unstable, + unknown; + + static IMap mapFromJson( + Map json, + ) => IMap.fromJson( + json, + (version) => version as String, + (stability) => values.asNameMap()[stability] ?? unknown, + ); +} diff --git a/lib/models/composer_draft.dart b/lib/models/composer_draft.dart new file mode 100644 index 0000000..ea72f30 --- /dev/null +++ b/lib/models/composer_draft.dart @@ -0,0 +1,31 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:fluttertagger/fluttertagger.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/bot_command_draft.dart"; +import "package:nexus/models/content/image_pack.dart"; +import "package:nexus/models/content/message.dart"; +import "package:nexus/models/content/poll_start.dart"; +import "package:nexus/models/relation_type.dart"; +import "package:nexus/models/text_command.dart"; + +part "composer_draft.freezed.dart"; + +@Freezed(toJson: false, fromJson: false) +class const ComposerDraft({ + // Formatted like ":id#name#", see the composer's tagTextFormatter + final String text = "", + final IList tags = const .empty(), + final IList textCommands = const .empty(), + final int? relatedEvent, + final RelationType relationType = .reply, + + // Replace the text field until they are sent or removed + final (String, PackImage)? sticker, + final PollStart? poll, + final LocationMessageContent? location, + + // The draft from before an edit, restored once it is sent or cancelled + final ({ComposerDraft draft, BotCommandDraft? botCommand})? beforeEdit, +}) with _$ComposerDraft { + bool get isEditing => beforeEdit != null; +} diff --git a/lib/models/composer_params.dart b/lib/models/composer_params.dart new file mode 100644 index 0000000..12edb46 --- /dev/null +++ b/lib/models/composer_params.dart @@ -0,0 +1 @@ +typedef ComposerParams = ({String roomId, String? threadRoot}); diff --git a/lib/models/configs/author.dart b/lib/models/configs/author.dart new file mode 100644 index 0000000..a3a15e9 --- /dev/null +++ b/lib/models/configs/author.dart @@ -0,0 +1,19 @@ +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/event.dart"; + +part "author.freezed.dart"; + +@freezed +class const AuthorConfig({ + required final String roomId, + required final String userId, + final Uri? avatarUrl, + final String? displayName, +}) with _$AuthorConfig { + factory AuthorConfig.fromEvent(Event event) => .new( + roomId: event.roomId, + userId: event.sender, + avatarUrl: event.pmp?.avatarUrl, + displayName: event.pmp?.displayName, + ); +} diff --git a/lib/models/configs/event.dart b/lib/models/configs/event.dart new file mode 100644 index 0000000..9f41fbe --- /dev/null +++ b/lib/models/configs/event.dart @@ -0,0 +1,16 @@ +import "package:freezed_annotation/freezed_annotation.dart"; + +part "event.freezed.dart"; +part "event.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const EventConfig({ + required final String roomId, + required final int eventRowId, +}) with _$EventConfig { + Map toJson() => _$EventConfigToJson(this); + + factory EventConfig.fromJson(Map json) => + _$EventConfigFromJson(json); +} diff --git a/lib/models/configs/reactions.dart b/lib/models/configs/reactions.dart deleted file mode 100644 index b9de793..0000000 --- a/lib/models/configs/reactions.dart +++ /dev/null @@ -1,16 +0,0 @@ -import "package:freezed_annotation/freezed_annotation.dart"; - -part "reactions.freezed.dart"; -part "reactions.g.dart"; - -@Freezed(toJson: false, fromJson: false) -@JsonSerializable() -class const ReactionsConfig({ - required final String roomId, - required final int eventRowId, -}) with _$ReactionsConfig { - Map toJson() => _$ReactionsConfigToJson(this); - - factory ReactionsConfig.fromJson(Map json) => - _$ReactionsConfigFromJson(json); -} diff --git a/lib/models/content/avatar.dart b/lib/models/content/avatar.dart index 25167e9..9efdb64 100644 --- a/lib/models/content/avatar.dart +++ b/lib/models/content/avatar.dart @@ -4,10 +4,13 @@ import "package:nexus/models/info/image.dart"; part "avatar.freezed.dart"; part "avatar.g.dart"; -@freezed -sealed class AvatarContent extends Content with _$AvatarContent { - AvatarContent._(); - factory AvatarContent({ImageInfo? info, Uri? url}) = _AvatarContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const AvatarContent({final ImageInfo? info, final Uri? url}) + extends Content + with _$AvatarContent { + @override + Map toJson() => _$AvatarContentToJson(this); factory AvatarContent.fromJson(Map json) => _$AvatarContentFromJson(json); diff --git a/lib/models/content/bot_command.dart b/lib/models/content/bot_command.dart new file mode 100644 index 0000000..b5ce39d --- /dev/null +++ b/lib/models/content/bot_command.dart @@ -0,0 +1,33 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/content/content.dart"; + +part "bot_command.freezed.dart"; +part "bot_command.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const BotCommandMessageContent({ + required final String body, + @JsonKey(name: "org.matrix.msc4391.command") + required final BotCommandInput command, + final String msgtype = "m.text", +}) extends Content with _$BotCommandMessageContent { + @override + Map toJson() => _$BotCommandMessageContentToJson(this); + + factory BotCommandMessageContent.fromJson(Map json) => + _$BotCommandMessageContentFromJson(json); +} + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const BotCommandInput({ + required final String command, + final IMap arguments = const .empty(), +}) with _$BotCommandInput { + Map toJson() => _$BotCommandInputToJson(this); + + factory BotCommandInput.fromJson(Map json) => + _$BotCommandInputFromJson(json); +} diff --git a/lib/models/content/bot_command_description.dart b/lib/models/content/bot_command_description.dart new file mode 100644 index 0000000..f563d9a --- /dev/null +++ b/lib/models/content/bot_command_description.dart @@ -0,0 +1,226 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/helpers/extensions/get_link_info.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/models/content/content.dart"; + +part "bot_command_description.freezed.dart"; +part "bot_command_description.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const BotCommandDescriptionContent({ + required final String command, + final IList parameters = const .empty(), + @JsonKey(fromJson: BotCommandDescriptionContent.plainText) + final String? description, +}) extends Content with _$BotCommandDescriptionContent { + // The plain text from an extensible events m.text block + static String? plainText(Map? json) => + switch (json?["m.text"]) { + final List representations => + representations + .map( + (representation) => switch (representation) { + {"mimetype": final String mimetype} + when mimetype != "text/plain" => + null, + {"body": final String body} => body, + _ => null, + }, + ) + .nonNulls + .firstOrNull, + _ => null, + }; + + bool get isValid => + command.trim().isNotEmpty && + parameters.map((parameter) => parameter.key).toISet().length == + parameters.length && + parameters.every((parameter) => parameter.schema.isValid()); + + @override + Map toJson() => _$BotCommandDescriptionContentToJson(this); + + factory BotCommandDescriptionContent.fromJson(Map json) => + _$BotCommandDescriptionContentFromJson(json); +} + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const BotParameter({ + required final String key, + required final BotParameterSchema schema, + final bool optional = false, + @JsonKey(fromJson: BotCommandDescriptionContent.plainText) + final String? description, +}) with _$BotParameter { + Map toJson() => _$BotParameterToJson(this); + + factory BotParameter.fromJson(Map json) => + _$BotParameterFromJson(json); +} + +@Freezed(unionKey: "schema_type") +sealed class BotParameterSchema with _$BotParameterSchema { + const BotParameterSchema._(); + + static final separator = RegExp(r"[\s,]+"); + + const factory BotParameterSchema.primitive({required BotPrimitiveType type}) = + PrimitiveSchema; + + const factory BotParameterSchema.literal({required Object value}) = + LiteralSchema; + + const factory BotParameterSchema.union({ + required IList variants, + }) = UnionSchema; + + const factory BotParameterSchema.array({required BotParameterSchema items}) = + ArraySchema; + + bool isValid({BotParameterSchema? parent}) => switch (this) { + PrimitiveSchema() => true, + LiteralSchema(:final value) => + value is String || value is int || value is bool, + UnionSchema(:final variants) => + (parent == null || parent is ArraySchema) && + variants.isNotEmpty && + variants.every( + (variant) => + variant is! UnionSchema && variant.isValid(parent: this), + ), + ArraySchema(:final items) => parent == null && items.isValid(parent: this), + }; + + String get label => switch (this) { + PrimitiveSchema(:final type) => type.label, + LiteralSchema(:final value) => "$value", + UnionSchema(:final variants) => + variants.map((variant) => variant.label).join(" | "), + ArraySchema(:final items) => "${items.label}...", + }; + + String get expected => switch (this) { + PrimitiveSchema(:final type) => type.expected, + LiteralSchema(:final value) => '"$value"', + UnionSchema(:final variants) => + variants.map((variant) => variant.expected).join(" or "), + ArraySchema(:final items) => items.expected, + }; + + bool allows(BotPrimitiveType type) => switch (this) { + PrimitiveSchema(type: final allowed) => allowed == type, + LiteralSchema() => false, + UnionSchema(:final variants) => variants.any( + (variant) => variant.allows(type), + ), + ArraySchema(:final items) => items.allows(type), + }; + + IList get literals => switch (this) { + PrimitiveSchema() => const .empty(), + LiteralSchema(:final value) => [value].lock, + UnionSchema(:final variants) => + variants.expand((variant) => variant.literals).toIList(), + ArraySchema(:final items) => items.literals, + }; + + Object? parse(String text, {required String roomId}) => switch (this) { + PrimitiveSchema(:final type) => type.parse(text, roomId: roomId), + LiteralSchema(:final value) => "$value" == text ? value : null, + UnionSchema(:final variants) => + variants + .map((variant) => variant.parse(text, roomId: roomId)) + .nonNulls + .firstOrNull, + ArraySchema(:final items) => items.parse(text, roomId: roomId), + }; + + ({Object? value, String? error}) parseText( + String text, { + required String roomId, + }) { + final parts = (this is ArraySchema ? text.split(separator) : [text.trim()]) + .where((part) => part.isNotEmpty) + .map((part) => (part, parse(part, roomId: roomId))) + .toIList(); + + return switch (parts.firstWhereOrNull((part) => part.$2 == null)) { + (final part, _) => (value: null, error: '"$part" isn\'t $expected.'), + null when parts.isEmpty => (value: null, error: null), + null when this is ArraySchema => ( + value: parts.map((part) => part.$2).nonNulls.toList(), + error: null, + ), + null => (value: parts.first.$2, error: null), + }; + } + + factory BotParameterSchema.fromJson(Map json) => + _$BotParameterSchemaFromJson(json); +} + +enum BotPrimitiveType(final String label, final String expected) { + @JsonValue("string") + string("text", "text"), + @JsonValue("integer") + integer("number", "a whole number"), + @JsonValue("boolean") + boolean("yes/no", "yes or no"), + @JsonValue("user_id") + userId("user", "a user ID like @alice:example.org"), + @JsonValue("server_name") + serverName("server", "a server name like example.org"), + @JsonValue("room_alias") + roomAlias("room alias", "a room alias like #room:example.org"), + @JsonValue("room_id") + roomId("room", "a room ID or link like !abc:example.org"), + @JsonValue("event_id") + eventId("event", r"a message link or event ID like $abc"); + + Object? parse(String text, {required String roomId}) { + final (:identifier, :eventId, :via) = + text.linkInfo ?? + (identifier: text, eventId: null, via: const IList.empty()); + + return switch (this) { + .string => text, + // In the range canonical JSON allows + .integer => switch (int.tryParse(text, radix: 10)) { + final value? when value.abs() <= 9007199254740991 => value, + _ => null, + }, + .boolean => switch (text.toLowerCase()) { + "true" || "yes" => true, + "false" || "no" => false, + _ => null, + }, + .userId when identifier.startsWith("@") && identifier.contains(":") => + identifier, + .roomAlias when identifier.startsWith("#") && identifier.contains(":") => + identifier, + .serverName when text.isValidServerName => text, + .roomId when identifier.startsWith("!") && eventId == null => { + "type": "room_id", + "id": identifier, + if (via.isNotEmpty) "via": via.unlock, + }, + .eventId when identifier.startsWith("!") && eventId != null => { + "type": "event_id", + "id": identifier, + "event_id": eventId, + if (via.isNotEmpty) "via": via.unlock, + }, + .eventId when identifier.startsWith(r"$") => { + "type": "event_id", + "id": roomId, + "event_id": identifier, + }, + _ => null, + }; + } +} diff --git a/lib/models/content/canonical_alias.dart b/lib/models/content/canonical_alias.dart index 6fb2829..058c007 100644 --- a/lib/models/content/canonical_alias.dart +++ b/lib/models/content/canonical_alias.dart @@ -4,14 +4,14 @@ import "package:nexus/models/content/content.dart"; part "canonical_alias.freezed.dart"; part "canonical_alias.g.dart"; -@freezed -sealed class CanonicalAliasContent extends Content - with _$CanonicalAliasContent { - CanonicalAliasContent._(); - factory CanonicalAliasContent({ - @JsonKey(includeIfNull: false) String? alias, - @Default(ISet.empty()) ISet altAliases, - }) = _CanonicalAliasContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const CanonicalAliasContent({ + @JsonKey(includeIfNull: false) final String? alias, + final ISet altAliases = const .empty(), +}) extends Content with _$CanonicalAliasContent { + @override + Map toJson() => _$CanonicalAliasContentToJson(this); factory CanonicalAliasContent.fromJson(Map json) => _$CanonicalAliasContentFromJson(json); diff --git a/lib/models/content/content.dart b/lib/models/content/content.dart index 37a87b7..46e87bd 100644 --- a/lib/models/content/content.dart +++ b/lib/models/content/content.dart @@ -1,5 +1,6 @@ import "package:collection/collection.dart"; import "package:nexus/models/content/avatar.dart"; +import "package:nexus/models/content/bot_command_description.dart"; import "package:nexus/models/content/canonical_alias.dart"; import "package:nexus/models/content/create.dart"; import "package:nexus/models/content/encryption.dart"; @@ -13,9 +14,15 @@ import "package:nexus/models/content/reaction.dart"; import "package:nexus/models/content/encrypted.dart"; import "package:nexus/models/content/redaction.dart"; import "package:nexus/models/content/server_acl.dart"; +import "package:nexus/models/content/space_child.dart"; import "package:nexus/models/content/topic.dart"; +import "package:nexus/models/content/tombstone.dart"; import "package:nexus/models/content/sticker.dart"; import "package:nexus/models/content/history_visibility.dart"; +import "package:nexus/models/content/image_pack.dart"; +import "package:nexus/models/content/poll_end.dart"; +import "package:nexus/models/content/poll_response.dart"; +import "package:nexus/models/content/poll_start.dart"; class const Content({final String? parseError, final StackTrace? stackTrace}) { factory Content.fromJson(Map json) => const Content(); @@ -58,7 +65,21 @@ enum EventType( avatar("m.room.avatar", AvatarContent.fromJson), topic("m.room.topic", TopicContent.fromJson), name("m.room.name", NameContent.fromJson), + tombstone("m.room.tombstone", TombstoneContent.fromJson), reaction("m.reaction", ReactionContent.fromJson), pinnedEvents("m.room.pinned_events", PinnedEventsContent.fromJson), + spaceChild("m.space.child", SpaceChildContent.fromJson), + imagePack("m.room.image_pack", ImagePackContent.fromJson), + legacyImagePack("im.ponies.room_emotes", ImagePackContent.fromJson), + pollStart("org.matrix.msc3381.poll.start", PollStartContent.fromJson), + pollResponse( + "org.matrix.msc3381.poll.response", + PollResponseContent.fromJson, + ), + pollEnd("org.matrix.msc3381.poll.end", PollEndContent.fromJson), + botCommandDescription( + "org.matrix.msc4391.command_description", + BotCommandDescriptionContent.fromJson, + ), message("m.room.message", MessageContent.fromJson), } diff --git a/lib/models/content/create.dart b/lib/models/content/create.dart index b937a94..1f9f125 100644 --- a/lib/models/content/create.dart +++ b/lib/models/content/create.dart @@ -4,21 +4,18 @@ import "package:nexus/models/content/content.dart"; part "create.freezed.dart"; part "create.g.dart"; -@freezed -sealed class CreateContent extends Content with _$CreateContent { - CreateContent._(); - factory CreateContent({ - @JsonKey(name: "additional_creators") - @Default(IList.empty()) - IList additionalCreatorIds, - - PreviousRoom? predecessor, - - @JsonKey(name: "m.federate") @Default(true) bool federated, - - @Default("1") String roomVersion, - @JsonKey(unknownEnumValue: RoomType.room) RoomType? type, - }) = _CreateContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const CreateContent({ + @JsonKey(name: "additional_creators") + final IList additionalCreatorIds = const .empty(), + final PreviousRoom? predecessor, + @JsonKey(name: "m.federate") final bool federated = true, + final String roomVersion = "1", + @JsonKey(unknownEnumValue: RoomType.room) final RoomType? type, +}) extends Content with _$CreateContent { + @override + Map toJson() => _$CreateContentToJson(this); factory CreateContent.fromJson(Map json) => _$CreateContentFromJson(json); diff --git a/lib/models/content/encrypted.dart b/lib/models/content/encrypted.dart index 8658a71..2fd7e4a 100644 --- a/lib/models/content/encrypted.dart +++ b/lib/models/content/encrypted.dart @@ -3,10 +3,11 @@ import "package:nexus/models/content/content.dart"; part "encrypted.freezed.dart"; part "encrypted.g.dart"; -@freezed -sealed class EncryptedContent extends Content with _$EncryptedContent { - EncryptedContent._(); - factory EncryptedContent() = _EncryptedContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const EncryptedContent() extends Content with _$EncryptedContent { + @override + Map toJson() => _$EncryptedContentToJson(this); factory EncryptedContent.fromJson(Map json) => _$EncryptedContentFromJson(json); diff --git a/lib/models/content/encryption.dart b/lib/models/content/encryption.dart index 52c7b34..cb7f1cd 100644 --- a/lib/models/content/encryption.dart +++ b/lib/models/content/encryption.dart @@ -3,20 +3,15 @@ import "package:nexus/models/content/content.dart"; part "encryption.freezed.dart"; part "encryption.g.dart"; -@freezed -sealed class EncryptionContent extends Content with _$EncryptionContent { - EncryptionContent._(); - factory EncryptionContent({ - required String algorithm, - - @JsonKey(name: "rotation_period_ms") - @Default(604800000) - int rotationPeriodMS, - - @JsonKey(name: "rotation_period_msgs") - @Default(100) - int rotationPeriodMessages, - }) = _EncryptionContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const EncryptionContent({ + required final String algorithm, + @JsonKey(name: "rotation_period_ms") final int rotationPeriodMS = 604800000, + @JsonKey(name: "rotation_period_msgs") final int rotationPeriodMessages = 100, +}) extends Content with _$EncryptionContent { + @override + Map toJson() => _$EncryptionContentToJson(this); factory EncryptionContent.fromJson(Map json) => _$EncryptionContentFromJson(json); diff --git a/lib/models/content/history_visibility.dart b/lib/models/content/history_visibility.dart index 3cfc011..516cac8 100644 --- a/lib/models/content/history_visibility.dart +++ b/lib/models/content/history_visibility.dart @@ -3,17 +3,18 @@ import "package:nexus/models/content/content.dart"; part "history_visibility.freezed.dart"; part "history_visibility.g.dart"; -@freezed -sealed class HistoryVisibilityContent extends Content - with _$HistoryVisibilityContent { - HistoryVisibilityContent._(); - factory HistoryVisibilityContent({ - required HistoryVisibility historyVisibility, - }) = _HistoryVisibilityContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const HistoryVisibilityContent({ + @JsonKey(unknownEnumValue: HistoryVisibility.unknown) + required final HistoryVisibility historyVisibility, +}) extends Content with _$HistoryVisibilityContent { + @override + Map toJson() => _$HistoryVisibilityContentToJson(this); factory HistoryVisibilityContent.fromJson(Map json) => _$HistoryVisibilityContentFromJson(json); } @JsonEnum(fieldRename: FieldRename.snake) -enum HistoryVisibility { invited, joined, shared, worldReadable } +enum HistoryVisibility { invited, joined, shared, worldReadable, unknown } diff --git a/lib/models/content/image_pack.dart b/lib/models/content/image_pack.dart new file mode 100644 index 0000000..5bcbb54 --- /dev/null +++ b/lib/models/content/image_pack.dart @@ -0,0 +1,76 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/content/content.dart"; +import "package:nexus/models/info/image.dart"; +part "image_pack.freezed.dart"; +part "image_pack.g.dart"; + +/// An image pack (MSC2545), from a room's state. +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(includeIfNull: false) +class const ImagePackContent({ + final IMap images = const .empty(), + final PackInfo? pack, +}) extends Content with _$ImagePackContent { + /// Whether the pack has images or a name, as deleted packs are left empty. + bool get hasContent => images.isNotEmpty || pack?.displayName != null; + + IMap imagesFor(ImageUsage usage) => images.where( + (_, image) => switch ((image.usage, pack?.usage ?? const .empty())) { + (final usages, _) when usages.isNotEmpty => usages.contains(usage), + (_, final packUsages) when packUsages.isNotEmpty => packUsages.contains( + usage, + ), + _ => true, + }, + ); + + @override + Map toJson() => _$ImagePackContentToJson(this); + + factory ImagePackContent.fromJson(Map json) => + _$ImagePackContentFromJson(json); +} + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(includeIfNull: false) +class const PackImage({ + required final Uri url, + final String? body, + final ImageInfo? info, + @JsonKey(fromJson: ImageUsage.setFromJson, toJson: ImageUsage.setToJson) + final ISet usage = const .empty(), +}) with _$PackImage { + Map toJson() => _$PackImageToJson(this); + + factory PackImage.fromJson(Map json) => + _$PackImageFromJson(json); +} + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(includeIfNull: false) +class const PackInfo({ + final String? displayName, + final Uri? avatarUrl, + final String? attribution, + @JsonKey(fromJson: ImageUsage.setFromJson, toJson: ImageUsage.setToJson) + final ISet usage = const .empty(), +}) with _$PackInfo { + Map toJson() => _$PackInfoToJson(this); + + factory PackInfo.fromJson(Map json) => + _$PackInfoFromJson(json); +} + +enum ImageUsage { + emoticon, + sticker; + + /// Ignores usages we don't know about. + static ISet setFromJson(List? json) => + ISet(values.where((value) => json?.contains(value.name) ?? false)); + + /// Omits an empty set, which means every usage. + static List? setToJson(ISet usages) => + usages.isEmpty ? null : usages.map((usage) => usage.name).toList(); +} diff --git a/lib/models/content/join_rules.dart b/lib/models/content/join_rules.dart index 948a762..4f1a929 100644 --- a/lib/models/content/join_rules.dart +++ b/lib/models/content/join_rules.dart @@ -5,13 +5,14 @@ import "package:nexus/models/join_rule.dart"; part "join_rules.freezed.dart"; part "join_rules.g.dart"; -@freezed -sealed class JoinRulesContent extends Content with _$JoinRulesContent { - JoinRulesContent._(); - factory JoinRulesContent({ - required JoinRule joinRule, - @Default(ISet.empty()) ISet allow, - }) = _JoinRulesContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const JoinRulesContent({ + @JsonKey(unknownEnumValue: JoinRule.unknown) required final JoinRule joinRule, + final ISet allow = const .empty(), +}) extends Content with _$JoinRulesContent { + @override + Map toJson() => _$JoinRulesContentToJson(this); factory JoinRulesContent.fromJson(Map json) => _$JoinRulesContentFromJson(json); diff --git a/lib/models/content/membership.dart b/lib/models/content/membership.dart index b1a5508..e082bf6 100644 --- a/lib/models/content/membership.dart +++ b/lib/models/content/membership.dart @@ -4,24 +4,22 @@ import "package:nexus/models/membership_status.dart"; part "membership.freezed.dart"; part "membership.g.dart"; -@freezed -sealed class MembershipContent extends Content with _$MembershipContent { - MembershipContent._(); - +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const MembershipContent({ + @JsonKey(name: "displayname", fromJson: MembershipContent.displaynameFromJson) + required final String? displayName, + @JsonKey(name: "membership", unknownEnumValue: MembershipStatus.unknown) + required final MembershipStatus status, + final Uri? avatarUrl, + final String? reason, + final bool isDirect = false, +}) extends Content with _$MembershipContent { static String? displaynameFromJson(String? displayName) => displayName?.isEmpty == true ? null : displayName; - factory MembershipContent({ - @JsonKey( - name: "displayname", - fromJson: MembershipContent.displaynameFromJson, - ) - required String? displayName, - @JsonKey(name: "membership") required MembershipStatus status, - Uri? avatarUrl, - String? reason, - @Default(false) bool isDirect, - }) = _MembershipContent; + @override + Map toJson() => _$MembershipContentToJson(this); factory MembershipContent.fromJson(Map json) => _$MembershipContentFromJson(json); diff --git a/lib/models/content/message.dart b/lib/models/content/message.dart index 36bd725..3e7c373 100644 --- a/lib/models/content/message.dart +++ b/lib/models/content/message.dart @@ -1,9 +1,11 @@ import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/content/bot_command.dart"; import "package:nexus/models/info/audio.dart"; import "package:nexus/models/content/content.dart"; import "package:nexus/models/info/file.dart"; import "package:nexus/models/info/image.dart"; import "package:nexus/models/info/video.dart"; +import "package:nexus/models/location.dart"; part "message.freezed.dart"; part "message.g.dart"; @@ -20,13 +22,16 @@ sealed class MessageContent extends Content with _$MessageContent { @FreezedUnionValue("m.text") factory MessageContent.text({ required String body, + @JsonKey(unknownEnumValue: JsonKey.nullForUndefinedEnumValue) MessageFormat? format, String? formattedBody, + @JsonKey(name: "org.matrix.msc4391.command") BotCommandInput? botCommand, }) = TextMessageContent; @FreezedUnionValue("m.notice") factory MessageContent.notice({ required String body, + @JsonKey(unknownEnumValue: JsonKey.nullForUndefinedEnumValue) MessageFormat? format, String? formattedBody, }) = NoticeMessageContent; @@ -34,6 +39,7 @@ sealed class MessageContent extends Content with _$MessageContent { @FreezedUnionValue("m.emote") factory MessageContent.emote({ required String body, + @JsonKey(unknownEnumValue: JsonKey.nullForUndefinedEnumValue) MessageFormat? format, String? formattedBody, }) = EmoteMessageContent; @@ -41,6 +47,7 @@ sealed class MessageContent extends Content with _$MessageContent { @FreezedUnionValue("m.image") factory MessageContent.image({ required String body, + @JsonKey(unknownEnumValue: JsonKey.nullForUndefinedEnumValue) MessageFormat? format, String? formattedBody, EncryptedFile? file, @@ -52,6 +59,7 @@ sealed class MessageContent extends Content with _$MessageContent { @FreezedUnionValue("m.file") factory MessageContent.file({ required String body, + @JsonKey(unknownEnumValue: JsonKey.nullForUndefinedEnumValue) MessageFormat? format, String? formattedBody, EncryptedFile? file, @@ -63,6 +71,7 @@ sealed class MessageContent extends Content with _$MessageContent { @FreezedUnionValue("m.audio") factory MessageContent.audio({ required String body, + @JsonKey(unknownEnumValue: JsonKey.nullForUndefinedEnumValue) MessageFormat? format, String? formattedBody, EncryptedFile? file, @@ -74,6 +83,7 @@ sealed class MessageContent extends Content with _$MessageContent { @FreezedUnionValue("m.video") factory MessageContent.video({ required String body, + @JsonKey(unknownEnumValue: JsonKey.nullForUndefinedEnumValue) MessageFormat? format, String? formattedBody, EncryptedFile? file, @@ -83,8 +93,12 @@ sealed class MessageContent extends Content with _$MessageContent { }) = VideoMessageContent; @FreezedUnionValue("m.location") - factory MessageContent.location({required String body, required Uri geoUri}) = - LocationMessageContent; + factory MessageContent.location({ + required String body, + required Uri geoUri, + @JsonKey(name: "m.location", includeIfNull: false) LocationInfo? location, + @JsonKey(name: "m.asset", includeIfNull: false) LocationAsset? asset, + }) = LocationMessageContent; factory MessageContent.fromJson(Map json) => _$MessageContentFromJson(json); diff --git a/lib/models/content/name.dart b/lib/models/content/name.dart index c451d64..74f583d 100644 --- a/lib/models/content/name.dart +++ b/lib/models/content/name.dart @@ -3,10 +3,13 @@ import "package:nexus/models/content/content.dart"; part "name.freezed.dart"; part "name.g.dart"; -@freezed -sealed class NameContent extends Content with _$NameContent { - NameContent._(); - factory NameContent({required String name}) = _NameContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const NameContent({required final String name}) + extends Content + with _$NameContent { + @override + Map toJson() => _$NameContentToJson(this); factory NameContent.fromJson(Map json) => _$NameContentFromJson(json); diff --git a/lib/models/content/pinned_events.dart b/lib/models/content/pinned_events.dart index 9dac5de..cf322af 100644 --- a/lib/models/content/pinned_events.dart +++ b/lib/models/content/pinned_events.dart @@ -4,12 +4,13 @@ import "package:nexus/models/content/content.dart"; part "pinned_events.freezed.dart"; part "pinned_events.g.dart"; -@freezed -sealed class PinnedEventsContent extends Content with _$PinnedEventsContent { - PinnedEventsContent._(); - factory PinnedEventsContent({ - @Default(IList.empty()) @JsonKey(name: "pinned") IList pinnedEvents, - }) = _PinnedEventsContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const PinnedEventsContent({ + @JsonKey(name: "pinned") final IList pinnedEvents = const .empty(), +}) extends Content with _$PinnedEventsContent { + @override + Map toJson() => _$PinnedEventsContentToJson(this); factory PinnedEventsContent.fromJson(Map json) => _$PinnedEventsContentFromJson(json); diff --git a/lib/models/content/poll_end.dart b/lib/models/content/poll_end.dart new file mode 100644 index 0000000..51fe58c --- /dev/null +++ b/lib/models/content/poll_end.dart @@ -0,0 +1,12 @@ +import "package:nexus/models/content/content.dart"; + +class const PollEndContent() extends Content { + factory PollEndContent.fromJson(Map json) => + const PollEndContent(); + + @override + Map toJson() => { + "org.matrix.msc3381.poll.end": {}, + "org.matrix.msc1767.text": "Ended the poll", + }; +} diff --git a/lib/models/content/poll_response.dart b/lib/models/content/poll_response.dart new file mode 100644 index 0000000..f151cdf --- /dev/null +++ b/lib/models/content/poll_response.dart @@ -0,0 +1,23 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/content/content.dart"; +part "poll_response.freezed.dart"; +part "poll_response.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(createToJson: false) +class const PollResponseContent({ + @JsonKey(readValue: PollResponseContent.answersFromJson) + final IList answers = const .empty(), +}) extends Content with _$PollResponseContent { + static List? answersFromJson(Map json, _) => + json["org.matrix.msc3381.poll.response"]?["answers"]; + + @override + Map toJson() => { + "org.matrix.msc3381.poll.response": {"answers": answers.toList()}, + }; + + factory PollResponseContent.fromJson(Map json) => + _$PollResponseContentFromJson(json); +} diff --git a/lib/models/content/poll_start.dart b/lib/models/content/poll_start.dart new file mode 100644 index 0000000..197ca69 --- /dev/null +++ b/lib/models/content/poll_start.dart @@ -0,0 +1,90 @@ +import "dart:math"; + +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/content/content.dart"; +part "poll_start.freezed.dart"; +part "poll_start.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(createToJson: false) +class const PollStartContent({ + @JsonKey(name: "org.matrix.msc3381.poll.start") required final PollStart poll, +}) extends Content with _$PollStartContent { + @override + Map toJson() => { + "org.matrix.msc3381.poll.start": poll.toJson(), + // Shown by clients without poll support + "org.matrix.msc1767.text": [ + poll.question, + ...poll.answers.mapIndexed( + (index, answer) => "${index + 1}. ${answer.text}", + ), + ].join("\n"), + }; + + factory PollStartContent.fromJson(Map json) => + _$PollStartContentFromJson(json); +} + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const PollStart({ + @JsonKey(readValue: PollStart.questionFromJson) final String question = "", + final int? maxSelections, + @JsonKey(readValue: PollStart.answersFromJson) + final IList answers = const .empty(), +}) with _$PollStart { + static const maxAnswers = 20; + + static String? extensibleTextFromJson(Object? json) => switch (json) { + {"org.matrix.msc1767.text": final String text} => text, + {"body": final String body} => body, + {"org.matrix.msc1767.message": final List message} => + message + .whereType() + .map((part) => part["body"]) + .whereType() + .firstOrNull, + _ => null, + }; + + static String? questionFromJson(Map json, String key) => + PollStart.extensibleTextFromJson(json[key]); + + static List? answersFromJson( + Map json, + String key, + ) => (json[key] as List?)?.take(maxAnswers).toList(); + + /// [maxSelections], defaulting to 1, and at most the number of answers + int get selectionLimit => + (maxSelections ?? 1).clamp(1, max(answers.length, 1)); + + Map toJson() => { + ..._$PollStartToJson(this), + // We don't allow undisclosed polls as they make no sense + "kind": "org.matrix.msc3381.poll.disclosed", + "question": {"org.matrix.msc1767.text": question}, + "answers": answers.map((answer) => answer.toJson()).toList(), + }; + + factory PollStart.fromJson(Map json) => + _$PollStartFromJson(json); +} + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(createToJson: false) +class const PollAnswer({ + required final String id, + @JsonKey(readValue: PollAnswer.textFromJson) final String text = "", +}) with _$PollAnswer { + static String? textFromJson(Map json, _) => + PollStart.extensibleTextFromJson(json); + + Map toJson() => {"id": id, "org.matrix.msc1767.text": text}; + + factory PollAnswer.fromJson(Map json) => + _$PollAnswerFromJson(json); +} diff --git a/lib/models/content/power_levels.dart b/lib/models/content/power_levels.dart index afa0e23..cdffd68 100644 --- a/lib/models/content/power_levels.dart +++ b/lib/models/content/power_levels.dart @@ -4,21 +4,22 @@ import "package:nexus/models/content/content.dart"; part "power_levels.freezed.dart"; part "power_levels.g.dart"; -@freezed -sealed class PowerLevelsContent extends Content with _$PowerLevelsContent { - PowerLevelsContent._(); - factory PowerLevelsContent({ - @Default(IMap.empty()) IMap events, - @Default(IMap.empty()) IMap users, - @JsonKey(includeIfNull: false) Notifications? notifications, - @Default(50) int ban, - @Default(0) int eventsDefault, - @Default(0) int invite, - @Default(50) int kick, - @Default(50) int redact, - @Default(50) int stateDefault, - @Default(0) int usersDefault, - }) = _PowerLevelsContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const PowerLevelsContent({ + final IMap events = const .empty(), + final IMap users = const .empty(), + @JsonKey(includeIfNull: false) final Notifications? notifications, + final int ban = 50, + final int eventsDefault = 0, + final int invite = 0, + final int kick = 50, + final int redact = 50, + final int stateDefault = 50, + final int usersDefault = 0, +}) extends Content with _$PowerLevelsContent { + @override + Map toJson() => _$PowerLevelsContentToJson(this); factory PowerLevelsContent.fromJson(Map json) => _$PowerLevelsContentFromJson(json); @@ -26,10 +27,7 @@ sealed class PowerLevelsContent extends Content with _$PowerLevelsContent { @Freezed(toJson: false, fromJson: false) @JsonSerializable() -class const Notifications({ - final int room = 50, - final IMap other = const .empty(), -}) with _$Notifications { +class const Notifications({final int room = 50}) with _$Notifications { Map toJson() => _$NotificationsToJson(this); factory Notifications.fromJson(Map json) => diff --git a/lib/models/content/reaction.dart b/lib/models/content/reaction.dart index 93c563d..3990788 100644 --- a/lib/models/content/reaction.dart +++ b/lib/models/content/reaction.dart @@ -3,19 +3,21 @@ import "package:nexus/models/content/content.dart"; part "reaction.freezed.dart"; part "reaction.g.dart"; -@Freezed(toJson: false) -sealed class ReactionContent extends Content with _$ReactionContent { - ReactionContent._(); +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const ReactionContent({ + @JsonKey(readValue: ReactionContent.keyJsonFromJson) final String? key, + + /// For custom emoji reactions + @JsonKey(name: "com.beeper.reaction.shortcode") final String? shortcode, +}) extends Content with _$ReactionContent { static String? keyJsonFromJson(Map json, String key) => json["m.relates_to"]?["key"]; - factory ReactionContent({ - @JsonKey(readValue: ReactionContent.keyJsonFromJson) String? key, - }) = _ReactionContent; - @override Map toJson() => { "m.relates_to": {"key": key}, + "com.beeper.reaction.shortcode": ?shortcode, }; factory ReactionContent.fromJson(Map json) => diff --git a/lib/models/content/redaction.dart b/lib/models/content/redaction.dart index 2ed6436..9864c1f 100644 --- a/lib/models/content/redaction.dart +++ b/lib/models/content/redaction.dart @@ -3,11 +3,13 @@ import "package:nexus/models/content/content.dart"; part "redaction.freezed.dart"; part "redaction.g.dart"; -@freezed -sealed class RedactionContent extends Content with _$RedactionContent { - RedactionContent._(); - factory RedactionContent({String? reason, String? redacts}) = - _RedactionContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const RedactionContent({final String? reason, final String? redacts}) + extends Content + with _$RedactionContent { + @override + Map toJson() => _$RedactionContentToJson(this); factory RedactionContent.fromJson(Map json) => _$RedactionContentFromJson(json); diff --git a/lib/models/content/server_acl.dart b/lib/models/content/server_acl.dart index 3873bf3..3c33072 100644 --- a/lib/models/content/server_acl.dart +++ b/lib/models/content/server_acl.dart @@ -4,14 +4,15 @@ import "package:nexus/models/content/content.dart"; part "server_acl.freezed.dart"; part "server_acl.g.dart"; -@freezed -sealed class ServerACLContent extends Content with _$ServerACLContent { - ServerACLContent._(); - factory ServerACLContent({ - @Default(IList.empty()) IList allow, - @Default(IList.empty()) IList deny, - @Default(true) allowIpLiterals, - }) = _ServerACLContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const ServerACLContent({ + final IList allow = const .empty(), + final IList deny = const .empty(), + final bool allowIpLiterals = true, +}) extends Content with _$ServerACLContent { + @override + Map toJson() => _$ServerACLContentToJson(this); factory ServerACLContent.fromJson(Map json) => _$ServerACLContentFromJson(json); diff --git a/lib/models/content/space_child.dart b/lib/models/content/space_child.dart new file mode 100644 index 0000000..07ed5c6 --- /dev/null +++ b/lib/models/content/space_child.dart @@ -0,0 +1,20 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/content/content.dart"; + +part "space_child.freezed.dart"; +part "space_child.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(includeIfNull: false) +class const SpaceChildContent({ + final IList via = const .empty(), + final String? order, + final bool suggested = false, +}) extends Content with _$SpaceChildContent { + @override + Map toJson() => _$SpaceChildContentToJson(this); + + factory SpaceChildContent.fromJson(Map json) => + _$SpaceChildContentFromJson(json); +} diff --git a/lib/models/content/sticker.dart b/lib/models/content/sticker.dart index c6fa893..a47a576 100644 --- a/lib/models/content/sticker.dart +++ b/lib/models/content/sticker.dart @@ -4,14 +4,15 @@ import "package:nexus/models/info/image.dart"; part "sticker.freezed.dart"; part "sticker.g.dart"; -@freezed -sealed class StickerContent extends Content with _$StickerContent { - StickerContent._(); - factory StickerContent({ - required String body, - required ImageInfo info, - required Uri url, - }) = _StickerContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const StickerContent({ + required final String body, + required final ImageInfo info, + required final Uri url, +}) extends Content with _$StickerContent { + @override + Map toJson() => _$StickerContentToJson(this); factory StickerContent.fromJson(Map json) => _$StickerContentFromJson(json); diff --git a/lib/models/content/tombstone.dart b/lib/models/content/tombstone.dart new file mode 100644 index 0000000..220d0b1 --- /dev/null +++ b/lib/models/content/tombstone.dart @@ -0,0 +1,17 @@ +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/content/content.dart"; +part "tombstone.freezed.dart"; +part "tombstone.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const TombstoneContent({ + final String body = "", + required final String replacementRoom, +}) extends Content with _$TombstoneContent { + @override + Map toJson() => _$TombstoneContentToJson(this); + + factory TombstoneContent.fromJson(Map json) => + _$TombstoneContentFromJson(json); +} diff --git a/lib/models/content/topic.dart b/lib/models/content/topic.dart index c8256e3..cd187fa 100644 --- a/lib/models/content/topic.dart +++ b/lib/models/content/topic.dart @@ -5,13 +5,14 @@ import "package:nexus/models/content/content.dart"; part "topic.freezed.dart"; part "topic.g.dart"; -@freezed -sealed class TopicContent extends Content with _$TopicContent { - TopicContent._(); - factory TopicContent({ - required String topic, - @JsonKey(name: "m.topic") TopicContentBlock? content, - }) = _TopicContent; +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const TopicContent({ + required final String topic, + @JsonKey(name: "m.topic") final TopicContentBlock? content, +}) extends Content with _$TopicContent { + @override + Map toJson() => _$TopicContentToJson(this); factory TopicContent.fromJson(Map json) => _$TopicContentFromJson(json); @@ -20,7 +21,7 @@ sealed class TopicContent extends Content with _$TopicContent { @Freezed(toJson: false, fromJson: false) @JsonSerializable() class const TopicContentBlock({ - final IList representations = const IList.empty(), + final IList representations = const .empty(), }) with _$TopicContentBlock { Map toJson() => _$TopicContentBlockToJson(this); diff --git a/lib/models/emoji.dart b/lib/models/emoji.dart deleted file mode 100644 index 75faf08..0000000 --- a/lib/models/emoji.dart +++ /dev/null @@ -1,25 +0,0 @@ -import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:freezed_annotation/freezed_annotation.dart"; -import "package:flutter/widgets.dart"; -part "emoji.freezed.dart"; -part "emoji.g.dart"; - -@Freezed(toJson: false, fromJson: false) -@JsonSerializable(createToJson: false) -class Emoji({ - @JsonKey( - fromJson: Emoji.widgetFromJson, - readValue: Emoji.readWidgetValueFromJson, - ) - required final Widget widget, - @JsonKey(name: "emoji") required final String value, - required final IList aliases, - required final String description, - required final IList tags, -}) with _$Emoji { - static Widget widgetFromJson(String emoji) => Text(emoji); - - static String readWidgetValueFromJson(Map json, _) => - json["emoji"]; - factory Emoji.fromJson(Map json) => _$EmojiFromJson(json); -} diff --git a/lib/models/emoji_category.dart b/lib/models/emoji_category.dart deleted file mode 100644 index cc39bc3..0000000 --- a/lib/models/emoji_category.dart +++ /dev/null @@ -1,12 +0,0 @@ -import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:freezed_annotation/freezed_annotation.dart"; -import "package:nexus/models/emoji.dart"; -import "package:flutter/widgets.dart"; -part "emoji_category.freezed.dart"; - -@Freezed(toJson: false, fromJson: false) -class EmojiCategory({ - required final Widget icon, - required final String name, - required final IList emojis, -}) with _$EmojiCategory; diff --git a/lib/models/event.dart b/lib/models/event.dart index 93352ca..1467750 100644 --- a/lib/models/event.dart +++ b/lib/models/event.dart @@ -29,6 +29,8 @@ class const Event({ final String? sendError, final IMap reactions = const .empty(), @JsonKey(name: "last_edit_rowid") final int lastEditRowId = 0, + final int threadCount = 0, + @JsonKey(name: "thread_latest_rowid") final int threadLatestRowId = 0, final UnreadType? unreadType, final Profile? pmp, required final Content content, @@ -36,6 +38,8 @@ class const Event({ }) with _$Event { Map toJson() => _$EventToJson(this); + String? get threadRoot => relationType == "m.thread" ? relatesTo : null; + static String typeJsonFromJson(Map json, _) => json["decrypted_type"] ?? json["type"]; @@ -47,7 +51,15 @@ class const Event({ static String? replyToFromJson(Map json) { try { - return json["m.relates_to"]?["m.in_reply_to"]?["event_id"]; + final relatesTo = json["m.relates_to"]; + + // Thread fallbacks are only for clients without thread support + if (relatesTo?["rel_type"] == "m.thread" && + relatesTo?["is_falling_back"] == true) { + return null; + } + + return relatesTo?["m.in_reply_to"]?["event_id"]; } catch (_) { return null; } diff --git a/lib/models/gomuks_event.dart b/lib/models/gomuks_event.dart new file mode 100644 index 0000000..821ea4a --- /dev/null +++ b/lib/models/gomuks_event.dart @@ -0,0 +1,34 @@ +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/client_state.dart"; +import "package:nexus/models/event.dart"; +import "package:nexus/models/events_decrypted.dart"; +import "package:nexus/models/sync_data.dart"; +import "package:nexus/models/sync_status.dart"; +import "package:nexus/models/typing.dart"; + +part "gomuks_event.freezed.dart"; + +@freezed +sealed class GomuksEvent with _$GomuksEvent { + const factory GomuksEvent.clientState(ClientState state) = ClientStateEvent; + const factory GomuksEvent.syncStatus(SyncStatus status) = SyncStatusEvent; + const factory GomuksEvent.initComplete() = InitCompleteEvent; + const factory GomuksEvent.sendComplete(Event event) = SendCompleteEvent; + const factory GomuksEvent.typing(Typing typing) = TypingEvent; + const factory GomuksEvent.eventsDecrypted(EventsDecrypted decrypted) = + EventsDecryptedEvent; + const factory GomuksEvent.syncComplete(SyncData sync) = SyncCompleteEvent; + const factory GomuksEvent.unknown(String type) = UnknownGomuksEvent; + + factory GomuksEvent.parse(String type, Map json) => + switch (type) { + "client_state" => .clientState(.fromJson(json)), + "sync_status" => .syncStatus(.fromJson(json)), + "init_complete" => const .initComplete(), + "send_complete" => .sendComplete(.fromJson(json["event"])), + "typing" => .typing(.fromJson(json)), + "events_decrypted" => .eventsDecrypted(.fromJson(json)), + "sync_complete" => .syncComplete(.fromJson(json)), + _ => .unknown(type), + }; +} diff --git a/lib/models/homeserver.dart b/lib/models/homeserver.dart index 5504941..ca1a271 100644 --- a/lib/models/homeserver.dart +++ b/lib/models/homeserver.dart @@ -1,4 +1,5 @@ import "package:freezed_annotation/freezed_annotation.dart"; +import "package:material_ui/material_ui.dart"; part "homeserver.freezed.dart"; @@ -7,5 +8,5 @@ class const Homeserver({ required final String name, required final String description, required final Uri url, - required final String iconUrl, + required final Widget icon, }) with _$Homeserver; diff --git a/lib/models/image_pack.dart b/lib/models/image_pack.dart new file mode 100644 index 0000000..33528c2 --- /dev/null +++ b/lib/models/image_pack.dart @@ -0,0 +1,54 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/content/image_pack.dart"; + +part "image_pack.freezed.dart"; + +@Freezed(toJson: false, fromJson: false) +class const ImagePack({ + required final String id, + required final String name, + final Uri? avatar, + + /// Map of shortcode to images + required final IMap emoticons, + required final IMap stickers, + + /// The state event the pack is from, for editing it. + required final ImagePackContent content, +}) with _$ImagePack { + /// The pack's avatar, or its first image if it has none. + Uri? get icon => avatar ?? content.images.values.firstOrNull?.url; + + String get imageCountLabel => content.images.length == 1 + ? "1 image" + : "${content.images.length} images"; + + /// The name of a pack without one, from its room's name and state key. + static String fallbackName(String roomName, String stateKey) => + stateKey.isEmpty ? roomName : "$roomName - $stateKey"; + + static String emojiMarkdown( + String shortcode, + String url, { + String? description, + }) => + '![:$shortcode:]($url "Emoji: ${switch (description) { + final description? when description.isNotEmpty => description, + _ => ":$shortcode:", + }.replaceAll(r"\", r"\\").replaceAll('"', r'\"')}")'; + + factory ImagePack.fromContent( + ImagePackContent content, { + required String roomId, + required String roomName, + required String stateKey, + }) => .new( + id: "$roomId/$stateKey", + name: content.pack?.displayName ?? fallbackName(roomName, stateKey), + avatar: content.pack?.avatarUrl, + emoticons: content.imagesFor(.emoticon), + stickers: content.imagesFor(.sticker), + content: content, + ); +} diff --git a/lib/models/join_rule.dart b/lib/models/join_rule.dart index 44fb9bb..a82c62a 100644 --- a/lib/models/join_rule.dart +++ b/lib/models/join_rule.dart @@ -1,4 +1,13 @@ import "package:freezed_annotation/freezed_annotation.dart"; @JsonEnum(fieldRename: .snake) -enum JoinRule { public, knock, invite, private, restricted, knockRestricted } +enum JoinRule { + public, + knock, + invite, + private, + restricted, + knockRestricted, + + unknown, +} diff --git a/lib/models/location.dart b/lib/models/location.dart new file mode 100644 index 0000000..767e2dc --- /dev/null +++ b/lib/models/location.dart @@ -0,0 +1,84 @@ +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:latlong2/latlong.dart"; +import "package:nexus/models/content/message.dart"; + +part "location.freezed.dart"; +part "location.g.dart"; + +/// A location message's `m.location` block. +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(includeIfNull: false) +class const LocationInfo({required final Uri uri, final String? description}) + with _$LocationInfo { + Map toJson() => _$LocationInfoToJson(this); + + factory LocationInfo.fromJson(Map json) => + _$LocationInfoFromJson(json); +} + +/// A location message's `m.asset` block. +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const LocationAsset({ + @JsonKey(unknownEnumValue: LocationAssetType.pin) + final LocationAssetType type = .self, +}) with _$LocationAsset { + Map toJson() => _$LocationAssetToJson(this); + + factory LocationAsset.fromJson(Map json) => + _$LocationAssetFromJson(json); +} + +enum LocationAssetType { + @JsonValue("m.self") + self, + + @JsonValue("m.pin") + pin, +} + +extension LocationMessagePoint on LocationMessageContent { + LatLng? get point => location?.uri.latLng ?? geoUri.latLng; + + String? get description => switch (location?.description?.trim()) { + final description? when description.isNotEmpty => description, + _ => null, + }; + + LocationAssetType get assetType => asset?.type ?? .self; +} + +extension FormatLatLng on LatLng { + String get formatted => + "${latitude.toStringAsFixed(5)}, ${longitude.toStringAsFixed(5)}"; +} + +extension GeoUri on Uri { + /// The coordinates of a geo: URI, like `geo:51.5,-0.12;u=35`. + LatLng? get latLng { + if (scheme != "geo") return null; + final coordinates = path.split(";").first.split(","); + if (coordinates.length < 2) return null; + + return switch (( + double.tryParse(coordinates[0]), + double.tryParse(coordinates[1]), + )) { + (final latitude?, final longitude?) + when latitude.abs() <= 90 && longitude.abs() <= 180 => + LatLng(latitude, longitude), + _ => null, + }; + } + + static Uri openStreetMap(LatLng point) => Uri.https( + "www.openstreetmap.org", + "/", + {"mlat": "${point.latitude}", "mlon": "${point.longitude}"}, + ).replace(fragment: "map=16/${point.latitude}/${point.longitude}"); + + static Uri fromLatLng(LatLng point, {double? uncertainty}) => Uri.parse( + "geo:${point.latitude},${point.longitude}" + "${uncertainty == null ? "" : ";u=${uncertainty.round()}"}", + ); +} diff --git a/lib/models/location_exception.dart b/lib/models/location_exception.dart new file mode 100644 index 0000000..107cc55 --- /dev/null +++ b/lib/models/location_exception.dart @@ -0,0 +1,11 @@ +enum LocationException(final String message) implements Exception { + servicesOff("Location services are turned off."), + denied("Nexus doesn't have permission to see your location."), + timedOut("Couldn't get your location in time."), + failed( + "Couldn't get your location. Check that location services are on, and that Nexus is allowed to use them.", + ); + + @override + String toString() => message; +} diff --git a/lib/models/membership_status.dart b/lib/models/membership_status.dart index 7eb5f72..f8197cb 100644 --- a/lib/models/membership_status.dart +++ b/lib/models/membership_status.dart @@ -1 +1 @@ -enum MembershipStatus { leave, invite, ban, join, knock } +enum MembershipStatus { leave, invite, ban, join, knock, unknown } diff --git a/lib/models/name_color.dart b/lib/models/name_color.dart new file mode 100644 index 0000000..f67429e --- /dev/null +++ b/lib/models/name_color.dart @@ -0,0 +1,2 @@ +/// What users' name colors are hashed from. +enum NameColor { powerLevel, user } diff --git a/lib/models/poll_votes.dart b/lib/models/poll_votes.dart new file mode 100644 index 0000000..47895b9 --- /dev/null +++ b/lib/models/poll_votes.dart @@ -0,0 +1,25 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; + +class const PollVotes({ + /// Each user's answers, by user ID + final IMap> votes = const .empty(), + final String? endEventId, + final int undecryptable = 0, +}) { + bool get hasEnded => endEventId != null; + + IMap> get votersByAnswer => votes.entries.fold( + const .empty(), + (acc, entry) => entry.value.fold( + acc, + (acc, answer) => acc.update( + answer, + (voters) => voters.add(entry.key), + ifAbsent: () => .new([entry.key]), + ), + ), + ); + + int get voterCount => + votes.values.where((answers) => answers.isNotEmpty).length; +} diff --git a/lib/models/power_level_permission.dart b/lib/models/power_level_permission.dart new file mode 100644 index 0000000..8c26ee2 --- /dev/null +++ b/lib/models/power_level_permission.dart @@ -0,0 +1,247 @@ +import "dart:math"; + +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/models/content/content.dart"; +import "package:nexus/models/content/power_levels.dart"; + +enum PowerLevelPermission( + final String title, + final String description, + final IconData icon, +) { + usersDefault( + "Default Power Level", + "The power level of users who aren't given one.", + Icons.person, + ), + eventsDefault( + "Default for Events", + "The power level needed to send events without their own.", + Icons.more_horiz, + ), + stateDefault( + "Default for State Events", + "The power level needed to send state events without their own.", + Icons.tune, + ), + invite( + "Invite Users", + "The power level needed to invite users.", + Icons.person_add, + ), + kick( + "Kick Users", + "The power level needed to kick users.", + Icons.sports_martial_arts, + ), + ban( + "Ban Users", + "The power level needed to ban and unban users.", + Icons.gavel, + ), + redact( + "Delete Others' Messages", + "The power level needed to remove others' messages.", + Icons.delete, + ), + notifyRoom( + "Notify Everyone", + "The power level needed to notify everyone in the room with @room.", + Icons.campaign, + ); + + int levelIn(PowerLevelsContent content) => switch (this) { + .usersDefault => content.usersDefault, + .eventsDefault => content.eventsDefault, + .stateDefault => content.stateDefault, + .invite => content.invite, + .kick => content.kick, + .ban => content.ban, + .redact => content.redact, + .notifyRoom => content.notifications?.room ?? 50, + }; + + PowerLevelsContent withLevel(PowerLevelsContent content, int level) => + switch (this) { + .usersDefault => content.copyWith(usersDefault: level), + .eventsDefault => content.copyWith(eventsDefault: level), + .stateDefault => content.copyWith(stateDefault: level), + .invite => content.copyWith(invite: level), + .kick => content.copyWith(kick: level), + .ban => content.copyWith(ban: level), + .redact => content.copyWith(redact: level), + .notifyRoom => content.copyWith( + notifications: (content.notifications ?? const Notifications()) + .copyWith(room: level), + ), + }; +} + +enum PowerLevelEvent( + final EventType type, + final String title, + final String description, + final IconData icon, +) { + message( + .message, + "Send Messages", + "The power level needed to send messages.", + Icons.message, + ), + // Everything a client encrypts is sent as this, so its level is what limits + // messages, stickers, and the like in encrypted rooms + encrypted( + .encrypted, + "Send Encrypted Events", + "The power level needed to send messages, stickers, files and anything else encrypted.", + Icons.lock, + ), + sticker( + .sticker, + "Send Stickers", + "The power level needed to send stickers.", + Icons.sticky_note_2, + ), + reaction( + .reaction, + "Send Reactions", + "The power level needed to react to messages.", + Icons.add_reaction, + ), + pinnedEvents( + .pinnedEvents, + "Pin Messages", + "The power level needed to pin messages.", + Icons.push_pin, + ), + name( + .name, + "Change Name", + "The power level needed to change the room's name.", + Icons.title, + ), + topic( + .topic, + "Change Topic", + "The power level needed to change the room's topic.", + Icons.description, + ), + avatar( + .avatar, + "Change Avatar", + "The power level needed to change the room's avatar.", + Icons.image, + ), + canonicalAlias( + .canonicalAlias, + "Change Aliases", + "The power level needed to change the room's canonical alias and published aliases.", + Icons.numbers, + ), + powerLevels( + .powerLevels, + "Change Power Levels", + "The power level needed to change power levels, including these.", + Icons.admin_panel_settings, + ), + joinRules( + .joinRules, + "Change Join Rule", + "The power level needed to change who can join the room.", + Icons.login, + ), + historyVisibility( + .historyVisibility, + "Change History Visibility", + "The power level needed to change who can read the room's history.", + Icons.history, + ), + serverACL( + .serverACL, + "Change Server ACL", + "The power level needed to change which servers can take part in the room.", + Icons.dns, + ), + encryption( + .encryption, + "Enable Encryption", + "The power level needed to enable encryption, which can't be turned off.", + Icons.lock, + ), + tombstone( + .tombstone, + "Upgrade Room", + "The power level needed to replace the room with an upgraded one.", + Icons.upgrade, + ); + + static IList shownIn({required bool encrypted}) => .new([ + if (encrypted) .encrypted else ...[.message, .sticker], + .reaction, + ]); + + static PowerLevelEvent? of(String type) => + values.where((event) => event.type.type == type).firstOrNull; +} + +/// Power levels set together, like everything moderators need, to save +/// setting each one. Each can still be set on its own, by expanding it. +enum PowerLevelGroup(final String title, final IconData icon) { + moderation("Moderation", Icons.shield), + roomDetails("Room Details", Icons.edit), + administration("Administration", Icons.admin_panel_settings); + + IList get permissions => .new(switch (this) { + .moderation => [.kick, .ban, .redact, .notifyRoom], + .roomDetails || .administration => [], + }); + + IList get events => .new(switch (this) { + .moderation => [], + .roomDetails => [.name, .topic, .avatar, .canonicalAlias, .pinnedEvents], + .administration => [ + .powerLevels, + .joinRules, + .historyVisibility, + .serverACL, + .encryption, + .tombstone, + ], + }); + + String get description => [ + ...permissions.map((permission) => permission.title), + ...events.map((event) => event.title), + ].join(", "); + + int? levelIn(PowerLevelsContent content) { + final levels = { + ...permissions.map((permission) => permission.levelIn(content)), + ...events.map( + (event) => content.events[event.type.type] ?? content.stateDefault, + ), + }; + return levels.length == 1 ? levels.single : null; + } + + int highestIn(PowerLevelsContent content) => [ + ...permissions.map((permission) => permission.levelIn(content)), + ...events.map( + (event) => content.events[event.type.type] ?? content.stateDefault, + ), + ].reduce(max); + + PowerLevelsContent withLevel(PowerLevelsContent content, int level) => + permissions + .fold( + content, + (content, permission) => permission.withLevel(content, level), + ) + .copyWith( + events: content.events.addEntries( + events.map((event) => MapEntry(event.type.type, level)), + ), + ); +} diff --git a/lib/models/push_rule_switch.dart b/lib/models/push_rule_switch.dart new file mode 100644 index 0000000..1c385d2 --- /dev/null +++ b/lib/models/push_rule_switch.dart @@ -0,0 +1,150 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/models/push_rules.dart"; + +enum PushRuleSection( + final String title, + final String description, + final IconData icon, +) { + messages("Messages", "Which messages notify you.", Icons.chat), + otherEvents("Other Events", "Events other than messages.", Icons.more_horiz), +} + +/// Default push rules turned on or off together, as some match the same events +/// in different ways, like encrypted ones, which the server can't read. +enum PushRuleSwitch( + final PushRuleSection section, + final String title, + final String description, + final IconData icon, + + /// What the rules do when on. + final PushActions actions, + + /// Whether turning it off disables the rules, so the next rule that matches + /// decides, rather than not notifying. + final bool disableWhenOff, +) { + mentions( + .messages, + "Mentions", + "Messages that mention you, or contain your name.", + Icons.alternate_email, + .highlightWithSound, + true, + ), + roomMentions( + .messages, + "Room Mentions", + "Messages that notify everyone in the room with @room.", + Icons.campaign, + .highlightWithSound, + true, + ), + directMessages( + .messages, + "Direct Messages", + "Messages in rooms with just you and one other person.", + Icons.person, + .notifyWithSound, + false, + ), + groupMessages( + .messages, + "Group Messages", + "Messages in rooms with more people, rather than only mentions and keywords.", + Icons.group, + .notifyWithSound, + false, + ), + invites( + .otherEvents, + "Invites", + "Invites for you to join rooms.", + Icons.mail, + .notifyWithSound, + false, + ), + calls( + .otherEvents, + "Calls", + "Incoming calls.", + Icons.call, + .new(notify: true, sound: "ring"), + false, + ), + tombstones( + .otherEvents, + "Room Tombstones", + "Rooms being upgraded or locked.", + Icons.lock, + .notifyWithSound, + false, + ); + + IList<({PushRuleKind kind, String ruleId})> get rules => .new(switch (this) { + .mentions => [ + (kind: .override, ruleId: ".m.rule.is_user_mention"), + (kind: .override, ruleId: ".m.rule.contains_display_name"), + (kind: .content, ruleId: ".m.rule.contains_user_name"), + ], + .roomMentions => [ + (kind: .override, ruleId: ".m.rule.is_room_mention"), + (kind: .override, ruleId: ".m.rule.roomnotif"), + ], + .directMessages => [ + (kind: .underride, ruleId: ".m.rule.room_one_to_one"), + (kind: .underride, ruleId: ".m.rule.encrypted_room_one_to_one"), + ], + .groupMessages => [ + (kind: .underride, ruleId: ".m.rule.message"), + (kind: .underride, ruleId: ".m.rule.encrypted"), + ], + .invites => [(kind: .override, ruleId: ".m.rule.invite_for_me")], + .calls => [(kind: .underride, ruleId: ".m.rule.call")], + .tombstones => [(kind: .override, ruleId: ".m.rule.tombstone")], + }); + + /// The rules in [ruleset], as servers may not have them all. + IList<({PushRuleKind kind, PushRule rule})> rulesIn(PushRuleset ruleset) => + rules + .map( + (rule) => switch (ruleset.find(rule.kind, rule.ruleId)) { + final found? => (kind: rule.kind, rule: found), + null => null, + }, + ) + .nonNulls + .toIList(); + + /// Whether the rules in [ruleset] are on or off, or null if they're set up + /// some other way. + bool? valueIn(PushRuleset ruleset) => switch (rulesIn(ruleset) + .map((entry) => entry.rule)) { + final rules + when rules.every((rule) => rule.enabled && rule.actions == actions) => + true, + final rules + when rules.every((rule) => !rule.enabled || !rule.actions.notify) => + false, + _ => null, + }; + + /// The rules in [ruleset], turned on or off. + IList<({PushRuleKind kind, PushRule rule})> changesIn( + PushRuleset ruleset, + bool value, + ) => rulesIn(ruleset) + .map( + (entry) => ( + kind: entry.kind, + rule: value + ? entry.rule.copyWith(enabled: true, actions: actions) + : disableWhenOff + ? entry.rule.copyWith(enabled: false) + : entry.rule.copyWith(enabled: true, actions: const .new()), + ), + ) + .toIList(); +} diff --git a/lib/models/push_rules.dart b/lib/models/push_rules.dart new file mode 100644 index 0000000..88fb050 --- /dev/null +++ b/lib/models/push_rules.dart @@ -0,0 +1,128 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; + +part "push_rules.freezed.dart"; +part "push_rules.g.dart"; + +/// The content of the m.push_rules account data. +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const PushRules({final PushRuleset global = const .new()}) + with _$PushRules { + Map toJson() => _$PushRulesToJson(this); + + factory PushRules.fromJson(Map json) => + _$PushRulesFromJson(json); +} + +/// Push rules by kind, apart from sender rules, which Nexus doesn't use. The +/// first rule that matches decides what happens. +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const PushRuleset({ + final IList override = const .empty(), + final IList content = const .empty(), + final IList room = const .empty(), + final IList underride = const .empty(), +}) with _$PushRuleset { + IList ofKind(PushRuleKind kind) => switch (kind) { + .override => override, + .content => content, + .room => room, + .underride => underride, + }; + + PushRule? find(PushRuleKind kind, String ruleId) => + ofKind(kind).where((rule) => rule.ruleId == ruleId).firstOrNull; + + /// Mutes everything when enabled, as it matches every event. + PushRule? get master => find(.override, ".m.rule.master"); + + /// The content rules the user added, which match these words. + IList get keywords => + content.where((rule) => !rule.isDefault).toIList(); + + Map toJson() => _$PushRulesetToJson(this); + + factory PushRuleset.fromJson(Map json) => + _$PushRulesetFromJson(json); +} + +enum PushRuleKind { override, content, room, underride } + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const PushRule({ + required final String ruleId, + final PushActions actions = const .new(), + + /// Whether the server made the rule, so it can't be deleted. + @JsonKey(name: "default") final bool isDefault = false, + final bool enabled = true, + + /// What content rules match in messages' bodies. + final String? pattern, + + /// What override and underride rules match. + final IList conditions = const .empty(), +}) with _$PushRule { + Map toJson() => _$PushRuleToJson(this); + + factory PushRule.fromJson(Map json) => + _$PushRuleFromJson(json); +} + +/// Only the fields of event_match conditions are kept. +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const PushCondition({ + required final String kind, + final String? key, + final String? pattern, +}) with _$PushCondition { + /// Matches events in the room with [roomId]. + factory PushCondition.inRoom(String roomId) => + .new(kind: "event_match", key: "room_id", pattern: roomId); + + Map toJson() => _$PushConditionToJson(this); + + factory PushCondition.fromJson(Map json) => + _$PushConditionFromJson(json); +} + +/// What happens when a push rule matches. Actions Nexus doesn't support are +/// dropped, so they're replaced when these are changed. +@Freezed(toJson: false, fromJson: false) +class const PushActions({ + final bool notify = false, + final bool highlight = false, + final String? sound, +}) with _$PushActions { + static const defaultSound = "default"; + static const notifyWithSound = PushActions(notify: true, sound: defaultSound); + static const highlightWithSound = PushActions( + notify: true, + highlight: true, + sound: defaultSound, + ); + + List toJson() => [ + if (notify) "notify", + if (highlight) {"set_tweak": "highlight"}, + if (sound != null) {"set_tweak": "sound", "value": sound}, + ]; + + factory PushActions.fromJson(List json) => json.fold( + const .new(), + (actions, action) => switch (action) { + "notify" => actions.copyWith(notify: true), + {"set_tweak": "highlight", "value": final bool highlight} => + actions.copyWith(highlight: highlight), + {"set_tweak": "highlight"} => actions.copyWith(highlight: true), + {"set_tweak": "sound", "value": final String sound} => actions.copyWith( + sound: sound, + ), + _ => actions, + }, + ); +} diff --git a/lib/models/reaction_group.dart b/lib/models/reaction_group.dart new file mode 100644 index 0000000..b3ea32c --- /dev/null +++ b/lib/models/reaction_group.dart @@ -0,0 +1,10 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; + +part "reaction_group.freezed.dart"; + +@Freezed(toJson: false, fromJson: false) +class const ReactionGroup({ + required final IList senders, + final String? shortcode, +}) with _$ReactionGroup; diff --git a/lib/models/requests/get_room_directory.dart b/lib/models/requests/get_room_directory.dart new file mode 100644 index 0000000..e46f203 --- /dev/null +++ b/lib/models/requests/get_room_directory.dart @@ -0,0 +1,28 @@ +import "package:freezed_annotation/freezed_annotation.dart"; + +part "get_room_directory.freezed.dart"; +part "get_room_directory.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(includeIfNull: false, explicitToJson: true) +class const GetRoomDirectoryRequest({ + final String? server, + final int limit = 48, + final String? since, + final PublicRoomsFilter? filter, +}) with _$GetRoomDirectoryRequest { + Map toJson() => _$GetRoomDirectoryRequestToJson(this); + + factory GetRoomDirectoryRequest.fromJson(Map json) => + _$GetRoomDirectoryRequestFromJson(json); +} + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(includeIfNull: false) +class const PublicRoomsFilter({final String? genericSearchTerm}) + with _$PublicRoomsFilter { + Map toJson() => _$PublicRoomsFilterToJson(this); + + factory PublicRoomsFilter.fromJson(Map json) => + _$PublicRoomsFilterFromJson(json); +} diff --git a/lib/models/requests/get_specific_room_state.dart b/lib/models/requests/get_specific_room_state.dart new file mode 100644 index 0000000..1559bc0 --- /dev/null +++ b/lib/models/requests/get_specific_room_state.dart @@ -0,0 +1,29 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; + +part "get_specific_room_state.freezed.dart"; +part "get_specific_room_state.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const GetSpecificRoomStateRequest({ + required final IList keys, +}) with _$GetSpecificRoomStateRequest { + Map toJson() => _$GetSpecificRoomStateRequestToJson(this); + + factory GetSpecificRoomStateRequest.fromJson(Map json) => + _$GetSpecificRoomStateRequestFromJson(json); +} + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const RoomStateKey({ + required final String roomId, + required final String type, + required final String stateKey, +}) with _$RoomStateKey { + Map toJson() => _$RoomStateKeyToJson(this); + + factory RoomStateKey.fromJson(Map json) => + _$RoomStateKeyFromJson(json); +} diff --git a/lib/models/requests/get_threads.dart b/lib/models/requests/get_threads.dart new file mode 100644 index 0000000..e88227b --- /dev/null +++ b/lib/models/requests/get_threads.dart @@ -0,0 +1,17 @@ +import "package:freezed_annotation/freezed_annotation.dart"; + +part "get_threads.freezed.dart"; +part "get_threads.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const GetThreadsRequest({ + required final String roomId, + final String? since, + final int limit = 20, +}) with _$GetThreadsRequest { + Map toJson() => _$GetThreadsRequestToJson(this); + + factory GetThreadsRequest.fromJson(Map json) => + _$GetThreadsRequestFromJson(json); +} diff --git a/lib/models/requests/send_event.dart b/lib/models/requests/send_event.dart index acad57f..13d8f86 100644 --- a/lib/models/requests/send_event.dart +++ b/lib/models/requests/send_event.dart @@ -1,5 +1,6 @@ import "package:freezed_annotation/freezed_annotation.dart"; import "package:nexus/models/content/content.dart"; +import "package:nexus/models/requests/send_message.dart"; part "send_event.freezed.dart"; part "send_event.g.dart"; @@ -10,12 +11,34 @@ class const SendEventRequest({ required final String roomId, required final String type, required final Content content, - final String? relatesTo, - final String? relationType, + // Merged into the content by toJson, as gomuks doesn't take these + @JsonKey(includeToJson: false) final String? relatesTo, + @JsonKey(includeToJson: false) final String? relationType, + @JsonKey(includeToJson: false) final Relation? reply, + @JsonKey(includeToJson: false) final Mentions? mentions, final bool synchronous = false, final bool disableEncryption = false, }) with _$SendEventRequest { - Map toJson() => _$SendEventRequestToJson(this); + Map toJson() { + final content = this.content.toJson(); + + return { + ..._$SendEventRequestToJson(this), + "content": { + ...content, + "m.mentions": ?mentions?.toJson(), + if (relatesTo != null || reply != null) + "m.relates_to": { + ...((content["m.relates_to"] as Map?) ?? {}), + if (relatesTo != null) ...{ + "event_id": relatesTo, + "rel_type": relationType, + }, + ...?reply?.toJson(), + }, + }, + }; + } factory SendEventRequest.fromJson(Map json) => _$SendEventRequestFromJson(json); diff --git a/lib/models/requests/send_message.dart b/lib/models/requests/send_message.dart index 10a9330..f6b61ac 100644 --- a/lib/models/requests/send_message.dart +++ b/lib/models/requests/send_message.dart @@ -38,11 +38,18 @@ class const Mentions({ class const Relation({ required final String eventId, required final RelationType relationType, + final String? threadRoot, + final bool isFallingBack = false, }) with _$Relation { Map toJson() { switch (relationType) { case RelationType.reply: return { + if (threadRoot != null) ...{ + "rel_type": "m.thread", + "event_id": threadRoot, + "is_falling_back": isFallingBack, + }, "m.in_reply_to": {"event_id": eventId}, }; diff --git a/lib/models/requests/update_push_rule.dart b/lib/models/requests/update_push_rule.dart new file mode 100644 index 0000000..3a4fde3 --- /dev/null +++ b/lib/models/requests/update_push_rule.dart @@ -0,0 +1,27 @@ +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/push_rules.dart"; + +part "update_push_rule.freezed.dart"; +part "update_push_rule.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable() +class const UpdatePushRuleRequest({ + required final PushRuleKind kind, + required final String ruleId, + required final UpdatePushRuleAction action, + + /// The new rule, when putting it. Only its actions and pattern are used. + final PushRule? newContent, + + /// The new actions, when putting only them. + final PushActions? actions, +}) with _$UpdatePushRuleRequest { + Map toJson() => _$UpdatePushRuleRequestToJson(this); + + factory UpdatePushRuleRequest.fromJson(Map json) => + _$UpdatePushRuleRequestFromJson(json); +} + +@JsonEnum(fieldRename: .snake) +enum UpdatePushRuleAction { enable, disable, put, putActions, delete } diff --git a/lib/models/room.dart b/lib/models/room.dart index f02c6ac..b809a23 100644 --- a/lib/models/room.dart +++ b/lib/models/room.dart @@ -24,6 +24,14 @@ class const Room({ @JsonKey(fromJson: Room.eventsJsonToIMap) final IMap events = const .empty(), + /// [relations] is an IMap of event ID to the eventRowIds relating to it + @JsonKey(includeFromJson: false, includeToJson: false) + final IMap> relations = const .empty(), + + /// [eventIds] is an IMap of event ID to eventRowId + @JsonKey(includeFromJson: false, includeToJson: false) + final IMap eventIds = const .empty(), + final bool reset = false, @JsonKey(includeFromJson: false, includeToJson: false) final bool resetClientSticky = false, diff --git a/lib/models/room_directory.dart b/lib/models/room_directory.dart new file mode 100644 index 0000000..fa58e20 --- /dev/null +++ b/lib/models/room_directory.dart @@ -0,0 +1,17 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/room_summary.dart"; + +part "room_directory.freezed.dart"; +part "room_directory.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(createToJson: false) +class const RoomDirectory({ + @JsonKey(name: "chunk") final IList rooms = const .empty(), + final String? nextBatch, + final int? totalRoomCountEstimate, +}) with _$RoomDirectory { + factory RoomDirectory.fromJson(Map json) => + _$RoomDirectoryFromJson(json); +} diff --git a/lib/models/room_notification_level.dart b/lib/models/room_notification_level.dart new file mode 100644 index 0000000..36a5029 --- /dev/null +++ b/lib/models/room_notification_level.dart @@ -0,0 +1,49 @@ +import "package:material_ui/material_ui.dart"; +import "package:nexus/models/push_rules.dart"; + +enum RoomNotificationLevel( + final String title, + final String description, + final IconData icon, +) { + global( + "Default", + "Follows your global notification rules.", + Icons.notifications, + ), + allMessages( + "All Messages", + "Every message notifies you.", + Icons.notifications_active, + ), + mentionsAndKeywords( + "Mentions & Keywords", + "Only messages that mention you or contain your keywords notify you.", + Icons.alternate_email, + ), + mute("Mute", "Nothing in this room notifies you.", Icons.notifications_off); + + static RoomNotificationLevel of(PushRuleset ruleset, String roomId) => + switch ((ruleset.find(.override, roomId), ruleset.find(.room, roomId))) { + (PushRule(enabled: true, actions: PushActions(notify: false)), _) => + .mute, + (_, PushRule(enabled: true, actions: PushActions(notify: true))) => + .allMessages, + (_, PushRule(enabled: true)) => .mentionsAndKeywords, + _ => .global, + }; + + ({PushRuleKind kind, PushRule rule})? ruleFor(String roomId) => + switch (this) { + .global => null, + .allMessages => ( + kind: .room, + rule: .new(ruleId: roomId, actions: .notifyWithSound), + ), + .mentionsAndKeywords => (kind: .room, rule: .new(ruleId: roomId)), + .mute => ( + kind: .override, + rule: .new(ruleId: roomId, conditions: .new([.inRoom(roomId)])), + ), + }; +} diff --git a/lib/models/room_power_levels.dart b/lib/models/room_power_levels.dart index 028d161..a40c1a1 100644 --- a/lib/models/room_power_levels.dart +++ b/lib/models/room_power_levels.dart @@ -8,4 +8,7 @@ class const RoomPowerLevels({ double levelOf(String userId) => creators.contains(userId) ? double.infinity : (content.users[userId] ?? content.usersDefault).toDouble(); + + bool canEndPoll(String userId, {required String pollSender}) => + userId == pollSender || levelOf(userId) >= content.redact; } diff --git a/lib/models/room_summary.dart b/lib/models/room_summary.dart index 05eaf43..2688ca3 100644 --- a/lib/models/room_summary.dart +++ b/lib/models/room_summary.dart @@ -14,7 +14,7 @@ part "room_summary.g.dart"; class const RoomSummary({ required final String roomId, @JsonKey(name: "num_joined_members") final int? joinedMembers, - final JoinRule? joinRule, + @JsonKey(unknownEnumValue: JoinRule.unknown) final JoinRule? joinRule, /// Rooms whose members may join without an invite, for restricted rooms. final IList allowedRoomIds = const .empty(), diff --git a/lib/models/settings.dart b/lib/models/settings.dart index 7ea61d9..79c3d64 100644 --- a/lib/models/settings.dart +++ b/lib/models/settings.dart @@ -1,5 +1,7 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:material_ui/material_ui.dart"; import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/name_color.dart"; import "package:nexus/models/room_order.dart"; import "package:nexus/models/show_and_send.dart"; @@ -16,12 +18,18 @@ class const Settings({ final bool showMinimizeButton = false, final bool swipeToReply = false, final bool hideMembershipEvents = false, + final bool hideServerAclEvents = true, final RoomOrder roomOrder = .unreadFirst, + final NameColor nameColor = .powerLevel, final ShowAndSend typingIndicators = .showAndSend, /// When not sending, read receipts are still sent privately, so that the /// user's other devices know what has been read. final ShowAndSend readReceipts = .showAndSend, + final IList directoryServers = const IListConst([ + "matrix.org", + "matrixrooms.info", + ]), }) with _$Settings { Map toJson() => _$SettingsToJson(this); diff --git a/lib/models/text_command.dart b/lib/models/text_command.dart new file mode 100644 index 0000000..7ee2f77 --- /dev/null +++ b/lib/models/text_command.dart @@ -0,0 +1,48 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; + +enum TextCommandGroup { messageType, format } + +// Prefixes gomuks parses out of sent text, in the order it expects them +enum TextCommand(final String description, {final TextCommandGroup? group}) { + me("Send as an emote", group: .messageType), + notice("Send as a notice", group: .messageType), + unencrypted("Send unencrypted, even if the room is encrypted"), + rawinputbody("Use the text as the body as-is, rather than from the HTML"), + plain("Send without any formatting", group: .format), + html("Send with only HTML, without markdown", group: .format), + htmlmd("Send with both HTML and markdown", group: .format), + rainbow("Send in rainbow colors, with markdown", group: .format); + + String get prefix => "/$name"; + + bool completes(String text) => + text.startsWith("/") && prefix.startsWith(text.toLowerCase()); + + // Replaces any command from the same group, as gomuks only uses one + IList addTo(IList commands) => .new( + commands + .where( + (other) => other != this && (group == null || other.group != group), + ) + .toIList() + .add(this) + .sortedBy((command) => command.index), + ); + + static String prefixOf(IList commands) => + commands.map((command) => "${command.prefix} ").join(); + + static ({IList commands, String text}) parse( + String text, [ + IList commands = const .empty(), + ]) => switch (values.firstWhereOrNull( + (command) => text.toLowerCase().startsWith("${command.prefix} "), + )) { + final command? => parse( + text.substring(command.prefix.length + 1), + command.addTo(commands), + ), + null => (commands: commands, text: text), + }; +} diff --git a/lib/widgets/account_scope.dart b/lib/widgets/account_scope.dart new file mode 100644 index 0000000..ff8db09 --- /dev/null +++ b/lib/widgets/account_scope.dart @@ -0,0 +1,46 @@ +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:flutter_riverpod/misc.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/active_account.dart"; +import "package:nexus/controllers/notification_request.dart"; + +/// Runs [child] as one account, in a [ProviderScope] of its own that's +/// replaced when switching accounts, so no state leaks between them. +class const AccountScope({ + required final String initialAccountId, + required final Widget child, + final List? observers, + final Duration? Function(int retryCount, Object error)? retry, + + /// Applied to each account's scope, after its own, e.g. for test fakes + final List overrides = const [], + super.key, +}) extends HookWidget { + @override + Widget build(BuildContext context) { + final active = useState(( + accountId: initialAccountId, + notificationRowId: null, + )); + + return ProviderScope( + key: ValueKey(active.value.accountId), + retry: retry, + observers: observers, + overrides: [ + ActiveAccountController.provider.overrideWith( + () => ActiveAccountController( + active.value.accountId, + (next) => active.value = next, + ), + ), + NotificationRequestController.provider.overrideWithBuild( + (_, _) => active.value.notificationRowId, + ), + ...overrides, + ], + child: child, + ); + } +} diff --git a/lib/widgets/adaptive_menu_button.dart b/lib/widgets/adaptive_menu_button.dart deleted file mode 100644 index 1928358..0000000 --- a/lib/widgets/adaptive_menu_button.dart +++ /dev/null @@ -1,21 +0,0 @@ -import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/show_adaptive_menu.dart"; - -/// Like [PopupMenuButton], but shows a bottom sheet on mobile. -class const AdaptiveMenuButton({ - required final Widget icon, - required final List Function(BuildContext context) - itemBuilder, - final String? tooltip, - final bool enabled = true, - super.key, -}) extends StatelessWidget { - @override - Widget build(BuildContext context) => IconButton( - icon: icon, - tooltip: tooltip, - onPressed: enabled - ? () => context.showAdaptiveMenu(itemBuilder(context)) - : null, - ); -} diff --git a/lib/widgets/avatar_or_hash.dart b/lib/widgets/avatars/avatar_or_hash.dart similarity index 79% rename from lib/widgets/avatar_or_hash.dart rename to lib/widgets/avatars/avatar_or_hash.dart index bdaf657..bb14c78 100644 --- a/lib/widgets/avatar_or_hash.dart +++ b/lib/widgets/avatars/avatar_or_hash.dart @@ -12,9 +12,18 @@ final class const AvatarOrHash( }) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { + final color = ColorHash(title).color; final box = ColoredBox( - color: ColorHash(title).color, - child: Center(child: Icon(Icons.person, size: dimension / 2)), + color: color, + child: Center( + child: Icon( + Icons.person, + size: dimension / 2, + color: ThemeData.estimateBrightnessForColor(color) == .dark + ? Colors.white + : Colors.black, + ), + ), ); return SizedBox( diff --git a/lib/widgets/avatar_ring.dart b/lib/widgets/avatars/avatar_ring.dart similarity index 100% rename from lib/widgets/avatar_ring.dart rename to lib/widgets/avatars/avatar_ring.dart diff --git a/lib/widgets/editable_avatar.dart b/lib/widgets/avatars/editable_avatar.dart similarity index 97% rename from lib/widgets/editable_avatar.dart rename to lib/widgets/avatars/editable_avatar.dart index d8d387f..5640342 100644 --- a/lib/widgets/editable_avatar.dart +++ b/lib/widgets/avatars/editable_avatar.dart @@ -1,7 +1,7 @@ import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client.dart"; -import "package:nexus/helpers/extensions/show_adaptive_menu.dart"; import "package:nexus/helpers/file_dialog_helper.dart"; import "package:nexus/helpers/hooks/saving.dart"; import "package:nexus/main.dart"; diff --git a/lib/widgets/avatars/image_pack_avatar.dart b/lib/widgets/avatars/image_pack_avatar.dart new file mode 100644 index 0000000..42504ae --- /dev/null +++ b/lib/widgets/avatars/image_pack_avatar.dart @@ -0,0 +1,14 @@ +import "package:material_ui/material_ui.dart"; +import "package:nexus/widgets/emoji/mxc_emoji.dart"; + +class const ImagePackAvatar(final Uri? icon, {super.key}) + extends StatelessWidget { + @override + Widget build(BuildContext context) => SizedBox.square( + dimension: 40, + child: switch (icon) { + final icon? => MxcEmoji(icon), + null => Icon(Icons.emoji_emotions), + }, + ); +} diff --git a/lib/widgets/common/account_switcher.dart b/lib/widgets/common/account_switcher.dart new file mode 100644 index 0000000..3d0f996 --- /dev/null +++ b/lib/widgets/common/account_switcher.dart @@ -0,0 +1,133 @@ +import "package:collection/collection.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/accounts.dart"; +import "package:nexus/controllers/active_account.dart"; +import "package:nexus/helpers/extensions/log_out.dart"; +import "package:nexus/main.dart"; +import "package:nexus/models/account.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; + +/// Switches between, adds and logs out of accounts. With [onlyWithOthers], it's +/// hidden when there's only one account. +class const AccountSwitcher({final bool onlyWithOthers = false, super.key}) + extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final danger = Theme.of(context).colorScheme.error; + final accounts = ref.watch(AccountsController.provider).value; + final activeId = ref.watch(ActiveAccountController.provider); + if (accounts == null || (onlyWithOthers && accounts.length < 2)) { + return const SizedBox.shrink(); + } + + String nameOf(Account account) => + account.displayName ?? account.userId ?? "New account"; + + Widget avatarOf(Account account, double dimension) => AvatarOrHash( + account.avatar, + nameOf(account), + dimension: dimension, + fallback: account.userId == null + ? Icon(Icons.account_circle, size: dimension) + : null, + ); + + final active = accounts.firstWhereOrNull( + (account) => account.id == activeId, + ); + + void switchTo(String accountId) => ref + .read(ActiveAccountController.provider.notifier) + .switchTo(accountId) + .onError(showError); + + final loggingOut = ref.watch(LogOut.mutation).isPending; + + return AdaptiveMenuButton( + tooltip: loggingOut ? "Logging out..." : "Switch account", + enabled: !loggingOut, + icon: loggingOut + ? const SizedBox.square( + dimension: 24, + child: CircularProgressIndicator(), + ) + : active == null + ? const Icon(Icons.account_circle) + : avatarOf(active, 28), + itemBuilder: (_) => [ + for (final account in accounts) + PopupMenuItem( + onTap: () => switchTo(account.id), + child: ListTile( + selected: account.id == activeId, + leading: avatarOf(account, 32), + title: Text(nameOf(account)), + subtitle: switch (account) { + Account(displayName: _?, :final userId?) => Text(userId), + _ => null, + }, + trailing: account.userId == null + ? null + // Inside the menu, so it can close it + : Builder( + builder: (menuContext) => IconButton( + tooltip: "Log out", + icon: Icon(Icons.logout, color: danger), + onPressed: () async { + Navigator.of(menuContext).pop(); + + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text("Log out of ${nameOf(account)}?"), + content: Text( + account.id == activeId + ? "You'll be switched to another account, or returned to the login page if this is your only one." + : "You'll stop receiving notifications for this account.", + ), + actions: [ + TextButton( + onPressed: () => + Navigator.of(dialogContext).pop(false), + child: const Text("Cancel"), + ), + TextButton( + onPressed: () => + Navigator.of(dialogContext).pop(true), + style: TextButton.styleFrom( + foregroundColor: danger, + ), + child: const Text("Log out"), + ), + ], + ), + ); + if (confirmed != true) return; + + await ref.logOut(account.id).onError(showError); + }, + ), + ), + ), + ), + const PopupMenuDivider(), + PopupMenuItem( + onTap: () { + final id = DateTime.now().millisecondsSinceEpoch.toString(); + ref + .read(AccountsController.provider.notifier) + .save(.new(id: id)) + .then((_) => switchTo(id)) + .onError(showError); + }, + child: const ListTile( + leading: Icon(Icons.person_add), + title: Text("Add account"), + ), + ), + ], + ); + } +} diff --git a/lib/widgets/appbar.dart b/lib/widgets/common/appbar.dart similarity index 87% rename from lib/widgets/appbar.dart rename to lib/widgets/common/appbar.dart index 123ae79..586d578 100644 --- a/lib/widgets/appbar.dart +++ b/lib/widgets/common/appbar.dart @@ -77,11 +77,17 @@ final class const Appbar({ onPressed: maximize, icon: const Icon(Icons.fullscreen), ), - IconButton( - tooltip: "Close window", - onPressed: () => exit(0), - icon: const Icon(Icons.close), - ), + if (ref + .watch(SettingsController.provider) + .whenOrNull( + data: (settings) => !settings.linuxMobileMode, + ) ?? + true) + IconButton( + tooltip: "Close window", + onPressed: () => exit(0), + icon: const Icon(Icons.close), + ), ], ], ), diff --git a/lib/widgets/bouncing_dots.dart b/lib/widgets/common/bouncing_dots.dart similarity index 100% rename from lib/widgets/bouncing_dots.dart rename to lib/widgets/common/bouncing_dots.dart diff --git a/lib/widgets/count_badge.dart b/lib/widgets/common/count_badge.dart similarity index 100% rename from lib/widgets/count_badge.dart rename to lib/widgets/common/count_badge.dart diff --git a/lib/widgets/divider_text.dart b/lib/widgets/common/divider_text.dart similarity index 82% rename from lib/widgets/divider_text.dart rename to lib/widgets/common/divider_text.dart index c44ae11..2c623ba 100644 --- a/lib/widgets/divider_text.dart +++ b/lib/widgets/common/divider_text.dart @@ -1,5 +1,5 @@ import "package:material_ui/material_ui.dart"; -import "package:nexus/widgets/divider_widget.dart"; +import "package:nexus/widgets/common/divider_widget.dart"; final class const DividerText(final String text, {super.key}) extends StatelessWidget { diff --git a/lib/widgets/divider_widget.dart b/lib/widgets/common/divider_widget.dart similarity index 100% rename from lib/widgets/divider_widget.dart rename to lib/widgets/common/divider_widget.dart diff --git a/lib/widgets/error_dialog.dart b/lib/widgets/common/error_dialog.dart similarity index 100% rename from lib/widgets/error_dialog.dart rename to lib/widgets/common/error_dialog.dart diff --git a/lib/widgets/common/expandable_image.dart b/lib/widgets/common/expandable_image.dart new file mode 100644 index 0000000..34a1f76 --- /dev/null +++ b/lib/widgets/common/expandable_image.dart @@ -0,0 +1,28 @@ +import "package:material_ui/material_ui.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:nexus/helpers/extensions/show_image_viewer.dart"; +import "package:nexus/models/requests/download_media.dart"; + +final class const ExpandableImage( + final DownloadMediaRequest? request, { + required final Widget child, + + /// If set, a download button is shown, suggesting this filename + final String? downloadFilename, + final int? size, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) => InkWell( + onTap: switch (request) { + final request? => () => context.showImageViewer( + ref, + request, + downloadFilename: downloadFilename, + size: size, + ), + null => null, + }, + child: child, + ); +} diff --git a/lib/widgets/highlight_wrapper.dart b/lib/widgets/common/highlight_wrapper.dart similarity index 100% rename from lib/widgets/highlight_wrapper.dart rename to lib/widgets/common/highlight_wrapper.dart diff --git a/lib/widgets/common/linkified_text.dart b/lib/widgets/common/linkified_text.dart new file mode 100644 index 0000000..d0c558b --- /dev/null +++ b/lib/widgets/common/linkified_text.dart @@ -0,0 +1,49 @@ +import "package:flutter/gestures.dart"; +import "package:material_ui/material_ui.dart"; +import "package:linkify/linkify.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/helpers/extensions/get_link_info.dart"; +import "package:nexus/helpers/launch_helper.dart"; +import "package:nexus/helpers/matrix_linkifier.dart"; +import "package:nexus/widgets/html/mention_chip.dart"; + +final class const LinkifiedText( + final String text, { + final String? roomId, + final int? maxLines, + final TextStyle? style, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) => Text.rich( + TextSpan( + style: style, + children: linkifyText(text) + .map( + (element) => switch (element) { + LinkableElement(:final url) when url.linkInfo != null => + WidgetSpan( + alignment: .baseline, + baseline: .alphabetic, + child: MentionChip(url, roomId), + ), + LinkableElement(:final text, :final url) => TextSpan( + text: text, + style: .new( + color: Theme.of(context).colorScheme.primary, + decoration: .underline, + ), + mouseCursor: SystemMouseCursors.click, + recognizer: TapGestureRecognizer() + ..onTap = () => + ref.read(LaunchHelper.provider).launchUrl(.parse(url)), + ), + _ => TextSpan(text: element.text), + }, + ) + .toList(), + ), + maxLines: maxLines, + overflow: maxLines == null ? null : .ellipsis, + ); +} diff --git a/lib/widgets/loading.dart b/lib/widgets/common/loading.dart similarity index 100% rename from lib/widgets/loading.dart rename to lib/widgets/common/loading.dart diff --git a/lib/widgets/common/m3e_rail_theme.dart b/lib/widgets/common/m3e_rail_theme.dart new file mode 100644 index 0000000..3ca5ed2 --- /dev/null +++ b/lib/widgets/common/m3e_rail_theme.dart @@ -0,0 +1,36 @@ +import "package:material_ui/material_ui.dart"; +import "package:m3e_design/m3e_design.dart"; + +// Needed for navigation_rail_m3e (#65). +import "package:flutter/material.dart" as old_mat; + +/// Themes a navigation_rail_m3e rail, which still uses the old Material theme. +class const M3ERailTheme({ + required final WidgetBuilder builder, + final List extensions = const [], + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) => MaterialUiCompatibilityBridge( + child: Builder( + builder: (context) { + final theme = old_mat.Theme.of(context); + return old_mat.Theme( + data: theme.copyWith( + extensions: [ + ...extensions, + // Otherwise the FAB label falls back to Roboto + M3ETheme.defaults(theme.colorScheme).copyWith( + typography: .defaultFor( + theme.brightness, + baseOverride: theme.textTheme, + ), + ), + ], + ), + child: Builder(builder: builder), + ); + }, + ), + ); +} diff --git a/lib/widgets/sync_status_banner.dart b/lib/widgets/common/sync_status_banner.dart similarity index 92% rename from lib/widgets/sync_status_banner.dart rename to lib/widgets/common/sync_status_banner.dart index 3f1e47e..0eccff3 100644 --- a/lib/widgets/sync_status_banner.dart +++ b/lib/widgets/common/sync_status_banner.dart @@ -1,7 +1,8 @@ import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/clock.dart"; import "package:nexus/controllers/sync_status.dart"; -import "package:nexus/widgets/error_dialog.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; import "package:timeago/timeago.dart"; class const SyncStatusBanner({super.key}) extends ConsumerWidget { @@ -38,7 +39,7 @@ class const SyncStatusBanner({super.key}) extends ConsumerWidget { ?status.error, if (status.errorCount > 0) "Failed attempts: ${status.errorCount}.", if (status.lastSync case final lastSync?) - "Last synced ${format(lastSync)}.", + "Last synced ${format(lastSync, clock: ref.watch(ClockController.provider))}.", ]; return AnimatedSize( @@ -67,7 +68,7 @@ class const SyncStatusBanner({super.key}) extends ConsumerWidget { banner.title, maxLines: 1, overflow: .ellipsis, - style: TextStyle( + style: .new( color: banner.foreground, fontWeight: .bold, ), diff --git a/lib/widgets/timestamp.dart b/lib/widgets/common/timestamp.dart similarity index 50% rename from lib/widgets/timestamp.dart rename to lib/widgets/common/timestamp.dart index bcdabd1..2f7a2fc 100644 --- a/lib/widgets/timestamp.dart +++ b/lib/widgets/common/timestamp.dart @@ -1,13 +1,15 @@ -import "package:flutter/material.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/clock.dart"; import "package:timeago/timeago.dart"; class const Timestamp(final DateTime timestamp, {super.key}) - extends StatelessWidget { + extends ConsumerWidget { @override - Widget build(BuildContext context) => Tooltip( + Widget build(BuildContext context, WidgetRef ref) => Tooltip( message: timestamp.toString(), child: Text( - format(timestamp), + format(timestamp, clock: ref.watch(ClockController.provider)), maxLines: 1, overflow: .ellipsis, style: Theme.of(context).textTheme.labelSmall diff --git a/lib/widgets/composer/bot_command_form.dart b/lib/widgets/composer/bot_command_form.dart new file mode 100644 index 0000000..fdd0dc4 --- /dev/null +++ b/lib/widgets/composer/bot_command_form.dart @@ -0,0 +1,53 @@ +import "package:collection/collection.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/bot_command_draft.dart"; +import "package:nexus/models/bot_command_draft.dart"; +import "package:nexus/widgets/composer/bot_option_pill.dart"; + +/// A bot command with its parameters filled in inline, like Discord's slash +/// commands. +class const BotCommandForm( + final BotCommandDraft draft, { + required final VoidCallback onSubmit, + + /// Called on backspace in the first parameter while empty. + required final VoidCallback onRemove, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + return Wrap( + spacing: 6, + runSpacing: 6, + crossAxisAlignment: .center, + children: [ + Text( + draft.command.prefix, + style: .new( + color: Theme.of(context).colorScheme.primary, + fontWeight: .bold, + ), + ), + ...draft.shown.mapIndexed( + (index, parameter) => BotOptionPill( + parameter, + key: ValueKey(parameter.key), + composer: draft.composer, + onSubmit: onSubmit, + onRemove: parameter.optional + ? () => ref + .read( + BotCommandDraftController.provider(draft.composer) + .notifier, + ) + .removeOption(parameter.key) + : index == 0 + ? onRemove + : null, + ), + ), + ], + ); + } +} diff --git a/lib/widgets/composer/bot_command_panel.dart b/lib/widgets/composer/bot_command_panel.dart new file mode 100644 index 0000000..bc6c05a --- /dev/null +++ b/lib/widgets/composer/bot_command_panel.dart @@ -0,0 +1,162 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter/scheduler.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/models/composer_params.dart"; +import "package:nexus/controllers/bot_argument_suggestions.dart"; +import "package:nexus/controllers/bot_command_draft.dart"; +import "package:nexus/models/bot_argument_suggestion.dart"; +import "package:nexus/models/bot_command.dart"; +import "package:nexus/models/text_command.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; + +class const BotCommandPanel( + final ComposerParams composer, { + required final IList commands, + required final IList textCommands, + required final TextEditingController controller, + required final void Function(BotCommand command) onPick, + required final void Function(TextCommand command) onPickText, + super.key, +}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final theme = Theme.of(context); + final draftProvider = BotCommandDraftController.provider(composer); + final suggestionsProvider = BotArgumentSuggestionsController.provider( + composer, + ); + + final text = useState(controller.text); + useEffect(() { + void update() { + if (SchedulerBinding.instance.schedulerPhase == .persistentCallbacks) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (context.mounted) text.value = controller.text; + }); + } else { + text.value = controller.text; + } + } + + controller.addListener(update); + return () => controller.removeListener(update); + }, [controller]); + + ListTile commandTile(BotCommand command, {VoidCallback? onTap}) => .new( + leading: AvatarOrHash(command.botAvatar, command.botName, dimension: 32), + title: Text(command.prefix), + subtitle: Text(command.about, maxLines: 1, overflow: .ellipsis), + onTap: onTap, + ); + + final children = switch (ref.watch(draftProvider)) { + null => [ + ...textCommands + .where((command) => command.completes(text.value)) + .map( + (command) => ListTile( + leading: AvatarOrHash(null, "gomuks", dimension: 32), + title: Text(command.prefix), + subtitle: Text( + "gomuks · ${command.description}", + maxLines: 1, + overflow: .ellipsis, + ), + onTap: () => onPickText(command), + ), + ), + ...commands + .where((command) => command.completes(text.value)) + .map( + (command) => commandTile(command, onTap: () => onPick(command)), + ), + ], + final draft => [ + commandTile(draft.command), + if (draft.focusedParameter case final parameter?) + ListTile( + title: Text( + parameter.key, + style: .new(color: theme.colorScheme.primary), + ), + subtitle: switch (( + draft.errors[parameter.key], + parameter.description, + )) { + (final error?, _) => Text( + error, + style: .new(color: theme.colorScheme.error), + ), + (null, final description?) => Text(description), + (null, null) => null, + }, + trailing: Text( + parameter.schema.label, + style: theme.textTheme.labelSmall, + ), + ), + ...ref + .watch(suggestionsProvider) + .map( + (suggestion) => ListTile( + leading: switch (suggestion) { + BotArgumentSuggestion(room: _?) => AvatarOrHash( + suggestion.avatar, + suggestion.title, + fallback: Icon(Icons.numbers), + ), + BotArgumentSuggestion(subtitle: _?) => AvatarOrHash( + suggestion.avatar, + suggestion.title, + ), + _ => null, + }, + title: Text(suggestion.title), + subtitle: switch (suggestion.subtitle) { + final subtitle? => Text(subtitle), + null => null, + }, + onTap: () => + ref.read(suggestionsProvider.notifier).pick(suggestion), + ), + ), + if (draft.hiddenOptions.isNotEmpty) + Padding( + padding: EdgeInsets.symmetric(horizontal: 16).copyWith(bottom: 12), + child: Wrap( + spacing: 8, + runSpacing: 8, + crossAxisAlignment: .center, + children: [ + Text("Optional", style: theme.textTheme.labelMedium), + ...draft.hiddenOptions.map( + (option) => ActionChip( + avatar: Icon(Icons.add), + label: Text(option.key), + tooltip: option.description, + onPressed: () => + ref.read(draftProvider.notifier).addOption(option.key), + ), + ), + ], + ), + ), + ], + }; + + return children.isEmpty + ? SizedBox(width: double.infinity) + : TextFieldTapRegion( + child: Card( + margin: .only(bottom: 8), + clipBehavior: .antiAlias, + child: ConstrainedBox( + constraints: .new(maxHeight: 320), + child: ListView(shrinkWrap: true, children: children), + ), + ), + ); + } +} diff --git a/lib/widgets/composer/bot_option_pill.dart b/lib/widgets/composer/bot_option_pill.dart new file mode 100644 index 0000000..0a86d8e --- /dev/null +++ b/lib/widgets/composer/bot_option_pill.dart @@ -0,0 +1,124 @@ +import "package:flutter/services.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/models/composer_params.dart"; +import "package:nexus/controllers/bot_command_draft.dart"; +import "package:nexus/models/content/bot_command_description.dart"; + +class const BotOptionPill( + final BotParameter parameter, { + required final ComposerParams composer, + + /// Called on backspace while empty, to remove the parameter or command. + final VoidCallback? onRemove, + required final VoidCallback onSubmit, + super.key, +}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final colorScheme = Theme.of(context).colorScheme; + final provider = BotCommandDraftController.provider(composer); + final (:text, :isFocused, :error, :isLast) = ref.watch( + provider.select( + (draft) => ( + text: draft?.texts[parameter.key] ?? "", + isFocused: draft?.focused == parameter.key, + error: draft?.errors[parameter.key], + isLast: + draft?.missing.every((other) => other.key == parameter.key) ?? + true, + ), + ), + ); + final controller = useTextEditingController(text: text); + final focusNode = useFocusNode(); + + useEffect(() { + if (controller.text != text) { + controller.value = .new( + text: text, + selection: .collapsed(offset: text.length), + ); + } + return null; + }, [text]); + + useEffect(() { + if (isFocused && !focusNode.hasFocus) { + WidgetsBinding.instance.addPostFrameCallback( + (_) => focusNode.requestFocus(), + ); + } + return null; + }, [isFocused]); + + return Focus( + canRequestFocus: false, + skipTraversal: true, + onFocusChange: (focused) { + if (focused) { + ref.read(provider.notifier).focus(parameter.key); + } + }, + onKeyEvent: (_, event) { + if (onRemove case final remove? + when event is KeyDownEvent && + event.logicalKey == .backspace && + controller.text.isEmpty) { + remove(); + return .handled; + } + return .ignored; + }, + child: Container( + padding: .symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: isFocused ? colorScheme.primaryContainer : colorScheme.surface, + border: error == null ? null : .all(color: colorScheme.error), + borderRadius: .all(.circular(8)), + ), + child: Row( + mainAxisSize: .min, + spacing: 4, + children: [ + Text( + "${parameter.key}:", + style: .new( + fontWeight: .bold, + color: isFocused + ? colorScheme.onPrimaryContainer + : colorScheme.onSurfaceVariant, + ), + ), + Flexible( + child: ConstrainedBox( + constraints: .new(minWidth: 16, maxWidth: 320), + child: IntrinsicWidth( + child: TextField( + controller: controller, + focusNode: focusNode, + readOnly: parameter.schema is LiteralSchema, + onChanged: (text) => ref + .read(provider.notifier) + .setText(parameter.key, text), + textInputAction: isLast ? .send : .next, + onSubmitted: (_) => onSubmit(), + // Keeps the keyboard open, rather than moving focus itself + onEditingComplete: () {}, + keyboardType: + parameter.schema.allows(.integer) && + !parameter.schema.allows(.string) + ? .number + : null, + decoration: .collapsed(hintText: null), + ), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/composer/composer.dart b/lib/widgets/composer/composer.dart index 2648347..3b722e0 100644 --- a/lib/widgets/composer/composer.dart +++ b/lib/widgets/composer/composer.dart @@ -1,10 +1,23 @@ import "dart:io"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:collection/collection.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/bot_argument_suggestions.dart"; +import "package:nexus/controllers/bot_command_draft.dart"; +import "package:nexus/controllers/bot_commands.dart"; +import "package:nexus/controllers/composer_draft.dart"; import "package:nexus/controllers/rooms.dart"; -import "package:nexus/widgets/emoji_picker.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; -import "package:nexus/widgets/adaptive_menu_button.dart"; +import "package:nexus/helpers/extensions/refocus_after_rebuild.dart"; +import "package:nexus/helpers/extensions/show_error_snack_bar.dart"; +import "package:nexus/helpers/extensions/with_latest_edit.dart"; +import "package:nexus/models/bot_command.dart"; +import "package:nexus/models/bot_command_draft.dart"; +import "package:nexus/models/composer_params.dart"; +import "package:nexus/models/text_command.dart"; +import "package:nexus/widgets/composer/bot_command_form.dart"; +import "package:nexus/widgets/composer/bot_command_panel.dart"; +import "package:nexus/widgets/emoji/emoji_picker.dart"; import "package:material_ui/material_ui.dart"; import "package:flutter/services.dart"; import "package:flutter_hooks/flutter_hooks.dart"; @@ -17,130 +30,214 @@ import "package:nexus/controllers/image_picker.dart"; import "package:nexus/helpers/file_dialog_helper.dart"; import "package:image_picker/image_picker.dart"; import "package:nexus/controllers/power_level.dart"; +import "package:nexus/controllers/image_packs.dart"; +import "package:nexus/models/content/image_pack.dart"; import "package:nexus/models/content/message.dart"; -import "package:nexus/models/relation_type.dart"; +import "package:nexus/widgets/renderers/message_media.dart"; +import "package:nexus/helpers/extensions/is_media.dart"; +import "package:nexus/models/content/poll_start.dart"; +import "package:nexus/models/image_pack.dart"; +import "package:nexus/widgets/emoji/mxc_emoji.dart"; +import "package:nexus/widgets/emoji/sticker_picker.dart"; +import "package:nexus/widgets/composer/create_poll_sheet.dart"; +import "package:nexus/widgets/location/location_picker_sheet.dart"; +import "package:nexus/models/location.dart"; import "package:nexus/widgets/composer/overlays/tagger_overlay.dart"; import "package:nexus/widgets/composer/paste_files_action.dart"; import "package:pasteboard/pasteboard.dart"; import "package:path/path.dart"; import "package:path_provider/path_provider.dart"; import "package:nexus/widgets/composer/relation_preview.dart"; +import "package:nexus/widgets/composer/composer_replacement.dart"; import "package:nexus/main.dart"; class const Composer( final String roomId, { - required final int? relatedEvent, - required final RelationType relationType, - required final VoidCallback onDismiss, required final Future Function( String text, { required bool shouldMention, required IList tags, }) onSend, + required final Future Function( + String shortcode, + PackImage image, { + required bool shouldMention, + }) + onSendSticker, + required final Future Function( + PollStart poll, { + required bool shouldMention, + }) + onSendPoll, + required final Future Function( + LocationMessageContent location, { + required bool shouldMention, + }) + onSendLocation, + required final Future Function(BotCommandDraft draft) onSendBotCommand, + final String? threadRoot, final FocusNode? node, super.key, }) extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); - final controller = useMemoized(FlutterTaggerController.new); + final ComposerParams composer = (roomId: roomId, threadRoot: threadRoot); + final draftProvider = ComposerDraftController.provider(composer); + final draftNotifier = ref.watch(draftProvider.notifier); + final ( + :relatedEventRowId, + :relationType, + :editingEvent, + :sticker, + :poll, + :location, + :textCommands, + ) = ref.watch( + draftProvider.select( + (draft) => ( + relatedEventRowId: draft.relatedEvent, + relationType: draft.relationType, + editingEvent: draft.isEditing ? draft.relatedEvent : null, + sticker: draft.sticker, + poll: draft.poll, + location: draft.location, + textCommands: draft.textCommands, + ), + ), + ); + final isEditing = editingEvent != null; + + final botCommandProvider = BotCommandDraftController.provider(composer); + final attachmentProvider = AttachmentController.provider(( + composer: composer, + editingRowId: editingEvent, + )); + final botCommand = ref.watch(botCommandProvider); + + final hasReplacement = + sticker != null || + poll != null || + location != null || + botCommand != null; + + final controller = useMemoized(() { + final draft = ref.read(draftProvider); + final ids = IMap.fromEntries( + draft.tags + .map((tag) => MapEntry("${tag.triggerCharacter}${tag.id}#", tag.id)) + .sortedBy((entry) => -entry.key.length), + ); + + return FlutterTaggerController(text: draft.text)..formatTags( + // Matches tags formatted by tagTextFormatter, like ":id#name#" + pattern: RegExp( + ids.isEmpty + ? "(?!)" + : "((?:${ids.keys.map(RegExp.escape).join("|")})[^#]*#)", + ), + parser: (formatted) { + final prefix = ids.keys.firstWhere(formatted.startsWith); + return [ + ids[prefix]!, + formatted.substring(prefix.length, formatted.length - 1), + ]; + }, + ); + }, [composer, editingEvent, hasReplacement]); + useEffect( + // After the frame, as FlutterTagger and TextField still use it until then + () => + () => WidgetsBinding.instance.addPostFrameCallback( + (_) => controller.dispose(), + ), + [controller], + ); + final triggerCharacter = useState(""); final shouldMention = useState(true); final query = useState(""); - final relatedEvent = this.relatedEvent == null + final canSendStickers = + ref.watch( + PowerLevelController.provider( + .new(eventType: .sticker, roomId: roomId), + ), + ) && + (ref + .watch(ImagePacksController.provider(roomId)) + .value + ?.any((pack) => pack.stickers.isNotEmpty) ?? + false); + final canSendPolls = ref.watch( + PowerLevelController.provider( + .new(eventType: .pollStart, roomId: roomId), + ), + ); + final relatedEvent = relatedEventRowId == null ? null : ref.watch( - RoomsController.provider.select((rooms) { - final event = rooms[roomId]?.events[this.relatedEvent!]; - if (event == null) return null; - - final edited = event.lastEditRowId == 0 - ? null - : rooms[roomId]?.events[event.lastEditRowId]; - - return edited == null - ? event - : event.copyWith( - content: edited.content, - localContent: edited.localContent, - ); - }), + RoomsController.provider.select( + (rooms) => rooms[roomId]?.withLatestEdit(relatedEventRowId), + ), ); - final textBefore = useState(null); - - useEffect(() { - if (relationType == .edit && relatedEvent != null) { - textBefore.value ??= controller.text; - - final text = - relatedEvent.localContent?.editSource ?? - switch (relatedEvent.content) { - TextMessageContent(:final body) => body, - _ => "", - }; - - controller.value = .new( - text: text, - selection: .collapsed(offset: text.length), - ); - } else if (textBefore.value case final draft?) { - controller.value = .new( - text: draft, - selection: .collapsed(offset: draft.length), - ); - textBefore.value = null; - } - - return null; - }, [relationType, relatedEvent == null]); + void dismiss() { + draftNotifier.dismiss(); + // Ending an edit replaces the text field + if (isEditing && (node?.hasFocus ?? false)) node?.refocusAfterRebuild(); + } final sinceTypingSent = useMemoized(Stopwatch.new); + final client = ref.watch(ClientController.provider.notifier); - useEffect(() { - final client = ref.read(ClientController.provider.notifier); + void stopTyping() { + if (!sinceTypingSent.isRunning) return; + sinceTypingSent + ..stop() + ..reset(); + client.setTyping(roomId, .zero).ignore(); + } - void stopTyping() { - if (!sinceTypingSent.isRunning) return; - sinceTypingSent - ..stop() - ..reset(); - client.setTyping(roomId, .zero).ignore(); + // Stops typing in the previous room, or the message before an edit + useEffect(() => stopTyping, [controller]); + + // Called by FlutterTagger for changes once attached, unlike a listener on + // the controller, which is also told about the draft being restored + // during the build + void onFormattedTextChanged(String text) { + final draft = ref.read(draftProvider); + if (text == draft.text || + (draft.isEditing ? draft.relatedEvent : null) != editingEvent) { + return; } - void onChanged() { - final shouldSend = - ref.read(SettingsController.provider).value?.typingIndicators == - .showAndSend; + draftNotifier.update( + (draft) => draft.copyWith(text: text, tags: controller.tags.toIList()), + ); - if (!shouldSend || controller.text.isEmpty) return stopTyping(); + final shouldSend = + ref.read(SettingsController.provider).value?.typingIndicators == + .showAndSend; - if (sinceTypingSent.isRunning && - sinceTypingSent.elapsed < const .new(seconds: 5)) { - return; - } + if (!shouldSend || controller.text.isEmpty) return stopTyping(); - sinceTypingSent - ..reset() - ..start(); - client.setTyping(roomId, const .new(seconds: 10)).ignore(); + if (sinceTypingSent.isRunning && + sinceTypingSent.elapsed < const .new(seconds: 5)) { + return; } - controller.addListener(onChanged); - return () { - controller.removeListener(onChanged); - stopTyping(); - }; - }, [roomId]); + sinceTypingSent + ..reset() + ..start(); + client.setTyping(roomId, const .new(seconds: 10)).ignore(); + } - final attachment = ref.watch(AttachmentController.provider(roomId)); + final attachment = ref.watch(attachmentProvider); Future attach(Future pick) async { if (await pick case final file?) { - await ref - .read(AttachmentController.provider(roomId).notifier) - .add(file); + await ref.read(attachmentProvider.notifier).add(file); } } @@ -153,9 +250,7 @@ class const Composer( final file = await File(join(directory.path, filename)) .writeAsBytes(bytes); - await ref - .read(AttachmentController.provider(roomId).notifier) - .add(.new(file.path)); + await ref.read(attachmentProvider.notifier).add(.new(file.path)); } /// Attaches the first file on the clipboard, or the image on it if there @@ -170,7 +265,7 @@ class const Composer( final files = await Pasteboard.files().onError((_, _) => const []); if (files.firstOrNull case final path?) { ref - .read(AttachmentController.provider(roomId).notifier) + .read(attachmentProvider.notifier) .add(XFile(path)) .onError(showError); return true; @@ -184,19 +279,197 @@ class const Composer( return false; } + // Bot commands can't follow text commands, which gomuks sends as text + final botCommands = + isEditing || + hasReplacement || + attachment != null || + textCommands.isNotEmpty + ? const IList.empty() + : ref.watch(BotCommandsController.provider(roomId)).value ?? + const .empty(); + + final availableTextCommands = hasReplacement || attachment != null + ? const IList.empty() + : TextCommand.values + .where((command) => !textCommands.contains(command)) + .toIList(); + + void setTextCommands(IList commands) => + draftNotifier.update((draft) => draft.copyWith(textCommands: commands)); + + void pickTextCommand(TextCommand command) { + setTextCommands(command.addTo(textCommands)); + controller.text = ""; + node?.requestFocus(); + } + + void removeTextCommand(TextCommand command) { + setTextCommands(textCommands.remove(command)); + node?.requestFocus(); + } + + /// Turns text commands typed at the start, like "/me ", into chips. + /// Returns whether there were any. + bool pickTypedTextCommands(String text) { + if (availableTextCommands.isEmpty) return false; + final parsed = TextCommand.parse(text, textCommands); + if (parsed.text == text) return false; + + setTextCommands(parsed.commands); + final removed = text.length - parsed.text.length; + controller.value = .new( + text: parsed.text, + selection: .collapsed( + offset: (controller.selection.baseOffset - removed).clamp( + 0, + parsed.text.length, + ), + ), + ); + return true; + } + + void pickBotCommand(BotCommand command) { + ref + .read(botCommandProvider.notifier) + .start(command, text: command.argumentsIn(controller.text) ?? ""); + controller.text = ""; + } + + BotCommand? typedBotCommand(String text) => switch (botCommands + .where((command) => command.argumentsIn(text) != null) + .sortedBy((command) => -command.prefix.length)) { + [final command, final other, ...] when command.prefix == other.prefix => + null, + [final command, ...] => command, + [] => null, + }; + + void pickTypedCommand(String text) { + if (pickTypedTextCommands(text)) return; + if (botCommands.any((command) => command.prefix.startsWith(text))) return; + if (typedBotCommand(text) case final command?) pickBotCommand(command); + } + + void removeBotCommand({required bool keepText}) { + // The text field gets a new controller from the draft once it's back + if (botCommand?.command.prefix case final prefix? when keepText) { + draftNotifier.update( + (draft) => draft.copyWith(text: prefix, tags: const .empty()), + ); + } + ref.read(botCommandProvider.notifier).clear(); + // The text field replaces the command form + node?.refocusAfterRebuild(); + } + void send() { + if (hasReplacement) { + if (botCommand != null) { + if (ref + .read( + BotArgumentSuggestionsController.provider(composer).notifier, + ) + .pickTop()) { + return; + } + if (botCommand.missing.firstOrNull case final next? + when next.key != botCommand.focused && + !botCommand.errors.containsKey(botCommand.focused)) { + ref.read(botCommandProvider.notifier).focus(next.key); + return; + } + if (botCommand.problem case final problem?) { + ScaffoldMessenger.of(context).showErrorSnackBar(problem); + ref.read(botCommandProvider.notifier).focusNext(); + return; + } + } + + if (sticker case (final shortcode, final image)?) { + onSendSticker(shortcode, image, shouldMention: shouldMention.value); + } else if (poll case final draft?) { + onSendPoll(draft, shouldMention: shouldMention.value); + } else if (location case final draft?) { + onSendLocation(draft, shouldMention: shouldMention.value); + } else if (botCommand != null) { + onSendBotCommand(botCommand); + } + dismiss(); + // The draft is kept, so it can still be sent after the replacement + draftNotifier.update( + (draft) => draft.copyWith(sticker: null, poll: null, location: null), + ); + ref.read(botCommandProvider.notifier).clear(); + // Once the text field is back + WidgetsBinding.instance.addPostFrameCallback( + (_) => node?.requestFocus(), + ); + return; + } + + // In the order the command panel shows them + if (typedBotCommand(controller.text) case final command?) { + return pickBotCommand(command); + } + if (availableTextCommands.firstWhereOrNull( + (command) => command.completes(controller.text), + ) + case final command?) { + return pickTextCommand(command); + } + if (botCommands.firstWhereOrNull( + (command) => command.completes(controller.text), + ) + case final command?) { + return pickBotCommand(command); + } + if (controller.value.text.isEmpty && attachment == null || attachment != null && attachment.$2 == null) { return; } onSend( - controller.formattedText, + "${TextCommand.prefixOf(textCommands)}${controller.formattedText}", shouldMention: shouldMention.value, tags: .new(controller.tags), ); - onDismiss(); + // Before dismissing, which restores the draft from before an edit controller.text = ""; + setTextCommands(const .empty()); + dismiss(); + } + + KeyEventResult sendOnEnter(FocusNode _, KeyEvent event) { + if (event is KeyDownEvent && + event.logicalKey == LogicalKeyboardKey.enter && + !HardwareKeyboard.instance.isShiftPressed) { + send(); + return .handled; + } + + return .ignored; + } + + KeyEventResult onTextFieldKeyEvent(FocusNode node, KeyEvent event) { + if (textCommands.lastOrNull case final command? + when event is KeyDownEvent && + event.logicalKey == .backspace && + controller.selection.isCollapsed && + controller.selection.baseOffset == 0) { + setTextCommands(textCommands.removeLast()); + if (controller.text.isEmpty) { + controller.value = .new( + text: command.prefix, + selection: .collapsed(offset: command.prefix.length), + ); + } + return .handled; + } + + return sendOnEnter(node, event); } final style = TextStyle( @@ -211,22 +484,61 @@ class const Composer( if (attachment != null) Card( margin: .only(bottom: 8), - child: ListTile( - leading: attachment.$2 == null - ? SizedBox( + child: Column( + children: [ + ListTile( + leading: switch (attachment.$2) { + null => SizedBox( width: 16, height: 16, child: CircularProgressIndicator(), - ) - : Icon(Icons.file_copy), - title: Text(attachment.$1), - trailing: IconButton( - onPressed: () => - ref.invalidate(AttachmentController.provider(roomId)), - icon: Icon(Icons.close), - ), + ), + ImageMessageContent() => Icon(Icons.image), + VideoMessageContent() => Icon(Icons.movie), + AudioMessageContent() => Icon(Icons.audiotrack), + _ => Icon(Icons.file_copy), + }, + title: Text(attachment.$1), + trailing: IconButton( + onPressed: () => ref.invalidate(attachmentProvider), + icon: Icon(Icons.close), + ), + ), + AnimatedSize( + duration: Durations.short4, + alignment: .topCenter, + child: switch (attachment.$2) { + final content? + when content is! FileMessageContent && + content.isMedia => + Padding( + padding: EdgeInsets.all(12).copyWith(top: 0), + child: Align( + alignment: .centerLeft, + child: ConstrainedBox( + constraints: .loose(.square(300)), + child: MessageMedia(content), + ), + ), + ), + _ => SizedBox(width: .infinity), + }, + ), + ], ), ), + AnimatedSize( + duration: Durations.short4, + alignment: .bottomCenter, + child: BotCommandPanel( + composer, + commands: botCommands, + textCommands: availableTextCommands, + controller: controller, + onPick: pickBotCommand, + onPickText: pickTextCommand, + ), + ), ClipRRect( borderRadius: .all(.circular(12)), child: Column( @@ -237,7 +549,7 @@ class const Composer( toggleShouldMention: () => shouldMention.value = !shouldMention.value, relationType: relationType, - onDismiss: onDismiss, + onDismiss: dismiss, ), Container( color: theme.colorScheme.surfaceContainerHighest, @@ -251,20 +563,43 @@ class const Composer( ) ? [ IconButton( - onPressed: () => context.showAdaptiveSheet( - (context) => EmojiPicker( - onSelection: (value) { - Navigator.of(context).pop(); - controller.text += value; - node?.requestFocus(); - }, - ), - ), + onPressed: hasReplacement + ? null + : () => context.showAdaptiveSheet( + (context) => EmojiPicker( + roomId: roomId, + onSelection: + (value, {shortcode, description}) { + Navigator.of(context).pop(); + if (shortcode == null) { + controller.text += value; + } else { + final text = + "${controller.text}:"; + controller.value = .new( + text: text, + selection: .collapsed( + offset: text.length, + ), + ); + controller.addTag( + id: ImagePack.emojiMarkdown( + shortcode, + value, + description: description, + ), + name: shortcode, + ); + } + node?.requestFocus(); + }, + ), + ), icon: Icon(Icons.emoji_emotions), ), AdaptiveMenuButton( tooltip: "Add media", - enabled: attachment == null, + enabled: attachment == null && !hasReplacement, itemBuilder: (context) => [ for (final (source, title, icon) in [ if (Platform.isAndroid || Platform.isIOS) @@ -308,110 +643,317 @@ class const Composer( leading: Icon(Icons.attachment), ), ), + if (canSendStickers) + PopupMenuItem( + // Stickers can't replace messages + enabled: !isEditing, + onTap: () => context.showAdaptiveSheet( + (context) => StickerPicker( + roomId: roomId, + onSelection: (shortcode, image) { + Navigator.of(context).pop(); + draftNotifier.update( + (draft) => draft.copyWith( + sticker: (shortcode, image), + ), + ); + }, + ), + ), + child: ListTile( + title: Text("Sticker"), + leading: Icon(Icons.sticky_note_2), + ), + ), + if (canSendPolls) + PopupMenuItem( + enabled: !isEditing, + onTap: () => context.showAdaptiveSheet( + (context) => CreatePollSheet( + onCreate: (created) { + Navigator.of(context).pop(); + draftNotifier.update( + (draft) => + draft.copyWith(poll: created), + ); + }, + ), + ), + child: ListTile( + title: Text("Poll"), + leading: Icon(Icons.poll), + ), + ), + PopupMenuItem( + enabled: !isEditing, + onTap: () => context.showAdaptiveSheet( + enableDrag: false, + (context) => LocationPickerSheet( + onPick: (picked) { + Navigator.of(context).pop(); + draftNotifier.update( + (draft) => + draft.copyWith(location: picked), + ); + }, + ), + ), + child: ListTile( + title: Text("Location"), + leading: Icon(Icons.location_on), + ), + ), ], icon: Icon(Icons.add), ), SizedBox(width: 8), Expanded( - child: FlutterTagger( - triggerStrategy: .eager, - overlay: TaggerOverlay( - query.value, - roomId: roomId, - triggerCharacter: triggerCharacter.value, - addTag: ({required id, required name}) { - controller.addTag(id: id, name: name); - node?.requestFocus(); - }, - ), - controller: controller, - onSearch: (newQuery, newTriggerCharacter) { - triggerCharacter.value = newTriggerCharacter; - query.value = newQuery; - }, - triggerCharacterAndStyles: { - "@": style, - "#": style, - ":": style, - }, - builder: (context, key) => Focus( - onKeyEvent: (_, event) { - if (event is KeyDownEvent && - event.logicalKey == - LogicalKeyboardKey.enter) { - final shiftPressed = HardwareKeyboard - .instance - .isShiftPressed; - - if (!shiftPressed) { - send(); - return KeyEventResult.handled; - } - } - - return KeyEventResult.ignored; - }, - // Overrides the keyboard shortcut for pasting - child: Actions( - actions: { - PasteTextIntent: PasteFilesAction( - pasteFiles, + child: AnimatedSize( + duration: Durations.short4, + alignment: .bottomCenter, + child: switch (( + sticker, + poll, + location, + botCommand, + )) { + (_, final draft?, _, _) => + ComposerReplacement( + removeTooltip: "Remove poll", + onRemove: () { + draftNotifier.update( + (draft) => draft.copyWith(poll: null), + ); + node?.requestFocus(); + }, + onKeyEvent: sendOnEnter, + ListTile( + leading: Icon( + Icons.poll, + color: theme.colorScheme.primary, + ), + title: Text(draft.question), + subtitle: Text( + draft.answers + .map((answer) => answer.text) + .join(" · "), + maxLines: 1, + overflow: .ellipsis, + ), ), + ), + ((final shortcode, final image)?, _, _, _) => + ComposerReplacement( + removeTooltip: "Remove sticker", + onRemove: () { + draftNotifier.update( + (draft) => + draft.copyWith(sticker: null), + ); + node?.requestFocus(); + }, + onKeyEvent: sendOnEnter, + Align( + alignment: .centerLeft, + child: ConstrainedBox( + constraints: .loose(.square(128)), + child: MxcEmoji( + image.url, + label: image.body ?? shortcode, + ), + ), + ), + ), + (_, _, final draft?, _) => + ComposerReplacement( + removeTooltip: "Remove location", + onRemove: () { + draftNotifier.update( + (draft) => + draft.copyWith(location: null), + ); + node?.requestFocus(); + }, + onKeyEvent: sendOnEnter, + ListTile( + leading: Icon( + draft.assetType == .pin + ? Icons.location_pin + : Icons.my_location, + color: theme.colorScheme.primary, + ), + title: Text( + draft.description ?? + (draft.assetType == .pin + ? "Location" + : "My location"), + ), + subtitle: Text( + draft.point?.formatted ?? + draft.geoUri.toString(), + maxLines: 1, + overflow: .ellipsis, + ), + ), + ), + (_, _, _, final draft?) => + ComposerReplacement( + removeTooltip: "Remove command", + onRemove: () => + removeBotCommand(keepText: false), + onKeyEvent: sendOnEnter, + BotCommandForm( + draft, + key: ValueKey(draft.command), + onSubmit: send, + onRemove: () => + removeBotCommand(keepText: true), + ), + ), + (null, null, null, null) => FlutterTagger( + // Attaches each new controller + key: ObjectKey(controller), + triggerStrategy: .eager, + onFormattedTextChanged: + onFormattedTextChanged, + // Keeps the trigger character, so tags + // can be restored from drafts + tagTextFormatter: ( + id, + tag, + triggerCharacter, + ) => "$triggerCharacter$id#$tag#", + // Characters that continue a search, for + // e.g. :+1, :custom_emoji or @user:server + searchRegex: .new(r"^[\w.:+-]*$"), + overlay: TaggerOverlay( + query.value, + roomId: roomId, + triggerCharacter: triggerCharacter.value, + addTag: ({required id, required name}) { + controller.addTag(id: id, name: name); + node?.requestFocus(); + }, + insertText: (text) { + final end = + controller.selection.baseOffset; + controller + ..dismissOverlay() + ..value = controller.value.replaced( + .new( + start: + end - query.value.length - 1, + end: end, + ), + "$text ", + ); + node?.requestFocus(); + }, + ), + controller: controller, + onSearch: (newQuery, newTriggerCharacter) { + triggerCharacter.value = + newTriggerCharacter; + query.value = newQuery; }, - child: TextField( - maxLines: 12, - minLines: 1, - textCapitalization: .sentences, - autofocus: - (Platform.isLinux || - Platform.isMacOS || - Platform.isWindows), - decoration: .new( - hintText: "Your message here...", - border: .none, - ), - controller: controller, - key: key, - focusNode: node, - // The toolbar's paste button doesn't use the shortcut's action, so replace it too - contextMenuBuilder: (_, editableText) => - AdaptiveTextSelectionToolbar.buttonItems( - anchors: - editableText.contextMenuAnchors, - buttonItems: editableText - .contextMenuButtonItems - .map( - (item) => item.type == .paste - ? item.copyWith( - onPressed: () async { - editableText - .hideToolbar(); - if (!await pasteFiles()) { - item.onPressed - ?.call(); - } - }, - ) - : item, - ) - .toList(), + triggerCharacterAndStyles: { + "@": style, + "#": style, + ":": style, + }, + builder: (context, key) => Focus( + onKeyEvent: onTextFieldKeyEvent, + // Overrides the keyboard shortcut for pasting + child: Actions( + actions: { + PasteTextIntent: PasteFilesAction( + pasteFiles, ), - // Images pasted from Android keyboards' clipboards are inserted as content - contentInsertionConfiguration: .new( - onContentInserted: (content) { - if (attachment != null) return; - - if (content.data case final data?) { - attachBytes( - data, - "image.${content.mimeType.split("/").last}", - ).onError(showError); - } }, + child: Row( + spacing: 4, + children: [ + ...textCommands.map( + (command) => InputChip( + label: Text(command.prefix), + tooltip: command.description, + visualDensity: .compact, + materialTapTargetSize: + .shrinkWrap, + onDeleted: () => + removeTextCommand(command), + ), + ), + Expanded( + child: TextField( + maxLines: 12, + minLines: 1, + textCapitalization: .sentences, + onChanged: pickTypedCommand, + autofocus: + (Platform.isLinux || + Platform.isMacOS || + Platform.isWindows), + decoration: .new( + hintText: + "Your message here...", + border: .none, + ), + controller: controller, + key: key, + focusNode: node, + // The toolbar's paste button doesn't use the shortcut's action, so replace it too + contextMenuBuilder: + ( + _, + editableText, + ) => AdaptiveTextSelectionToolbar.buttonItems( + anchors: editableText + .contextMenuAnchors, + buttonItems: editableText + .contextMenuButtonItems + .map( + (item) => + item.type == + .paste + ? item.copyWith( + onPressed: () async { + editableText + .hideToolbar(); + if (!await pasteFiles()) { + item.onPressed + ?.call(); + } + }, + ) + : item, + ) + .toList(), + ), + // Images pasted from Android keyboards' clipboards are inserted as content + contentInsertionConfiguration: .new( + onContentInserted: (content) { + if (attachment != null) { + return; + } + + if (content.data + case final data?) { + attachBytes( + data, + "image.${content.mimeType.split("/").last}", + ).onError(showError); + } + }, + ), + ), + ), + ], + ), ), ), ), - ), + }, ), ), IconButton( diff --git a/lib/widgets/composer/composer_replacement.dart b/lib/widgets/composer/composer_replacement.dart new file mode 100644 index 0000000..ef6ff9f --- /dev/null +++ b/lib/widgets/composer/composer_replacement.dart @@ -0,0 +1,30 @@ +import "package:material_ui/material_ui.dart"; + +/// Replaces the composer's text field with something to send, like a sticker. +class const ComposerReplacement( + final Widget child, { + required final String removeTooltip, + required final VoidCallback onRemove, + final FocusOnKeyEventCallback? onKeyEvent, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) => Focus( + autofocus: true, + onKeyEvent: onKeyEvent, + child: Padding( + padding: .symmetric(vertical: 8), + child: Row( + spacing: 12, + children: [ + Expanded(child: child), + IconButton( + tooltip: removeTooltip, + onPressed: onRemove, + icon: Icon(Icons.close), + ), + ], + ), + ), + ); +} diff --git a/lib/widgets/composer/create_poll_sheet.dart b/lib/widgets/composer/create_poll_sheet.dart new file mode 100644 index 0000000..48f849d --- /dev/null +++ b/lib/widgets/composer/create_poll_sheet.dart @@ -0,0 +1,109 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/models/content/poll_start.dart"; + +class const CreatePollSheet({ + required final void Function(PollStart poll) onCreate, + super.key, +}) extends HookWidget { + @override + Widget build(BuildContext context) { + final questionController = useTextEditingController(); + final question = useValueListenable(questionController).text.trim(); + + // Keyed by ID, so fields keep their text when one above is removed + final nextId = useRef(2); + final answers = useState>(.new({0: "", 1: ""})); + final filledAnswers = answers.value.entries + .map( + (answer) => + PollAnswer(id: "${answer.key}", text: answer.value.trim()), + ) + .where((answer) => answer.text.isNotEmpty) + .toIList(); + + final allowMultiple = useState(false); + + final canCreate = question.isNotEmpty && filledAnswers.length >= 2; + + void submit() => onCreate( + .new( + question: question, + answers: filledAnswers, + maxSelections: allowMultiple.value ? filledAnswers.length : 1, + ), + ); + + return SheetLayout( + title: const Text("Create a Poll"), + actions: [ + TextButton( + onPressed: Navigator.of(context).pop, + child: const Text("Cancel"), + ), + TextButton( + onPressed: canCreate ? submit : null, + child: const Text("Create"), + ), + ], + children: [ + TextField( + controller: questionController, + autofocus: true, + textCapitalization: .sentences, + decoration: const .new(labelText: "Question"), + ), + AnimatedSize( + duration: Durations.medium2, + curve: Curves.easeInOut, + alignment: .topCenter, + child: Column( + spacing: 12, + children: answers.value.entries + .mapIndexed( + (index, answer) => TextFormField( + key: ValueKey(answer.key), + initialValue: answer.value, + textCapitalization: .sentences, + onChanged: (text) => + answers.value = answers.value.add(answer.key, text), + decoration: .new( + labelText: "Answer ${index + 1}", + suffixIcon: answers.value.length > 2 + ? IconButton( + tooltip: "Remove answer", + icon: const Icon(Icons.close), + onPressed: () => answers.value = answers.value + .remove(answer.key), + ) + : null, + ), + ), + ) + .toList(), + ), + ), + Align( + alignment: .centerLeft, + child: TextButton.icon( + onPressed: answers.value.length < PollStart.maxAnswers + ? () => answers.value = answers.value.add(nextId.value++, "") + : null, + icon: const Icon(Icons.add), + label: const Text("Add Answer"), + ), + ), + SwitchListTile( + secondary: const Icon(Icons.checklist), + title: const Text("Allow multiple answers"), + subtitle: const Text("Voters can choose more than one"), + value: allowMultiple.value, + onChanged: (value) => allowMultiple.value = value, + ), + ], + ); + } +} diff --git a/lib/widgets/composer/overlays/emoji_overlay.dart b/lib/widgets/composer/overlays/emoji_overlay.dart index 0e762c0..6f9c15f 100644 --- a/lib/widgets/composer/overlays/emoji_overlay.dart +++ b/lib/widgets/composer/overlays/emoji_overlay.dart @@ -1,29 +1,35 @@ import "package:collection/collection.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; -import "package:material_emoji_picker/material_emoji_picker.dart"; import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/all_emoji.dart"; import "package:nexus/helpers/extensions/better_when.dart"; +import "package:nexus/helpers/extensions/weighted_search.dart"; +import "package:nexus/models/content/image_pack.dart"; +import "package:nexus/models/image_pack.dart"; class const EmojiOverlay( final String query, { required final String roomId, required final void Function({required String id, required String name}) addTag, + required final void Function(String text) insertText, super.key, }) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) => ref - .watch(EmojiController.provider) + .watch(AllEmojiController.provider(roomId)) .betterWhen( data: (emojis) => ListView( children: emojis .map((element) => element.emojis) .flattened - .where( - (emoji) => - emoji.aliases.join().contains(query) || - emoji.description.contains(query) || - emoji.tags.join().contains(query), + .search( + query, + (emoji) => [ + ...emoji.aliases.map((alias) => (alias, 3)), + ...emoji.tags.map((tag) => (tag, 2)), + (emoji.description, 1), + ], ) .map( (emoji) => ListTile( @@ -33,12 +39,19 @@ class const EmojiOverlay( ), title: Text(emoji.aliases.first), subtitle: Text(emoji.description), - onTap: () => addTag( - id: Uri.tryParse(emoji.value)?.scheme == "mxc" - ? "" // TODO: Handle custom emotes - : emoji.value, - name: emoji.aliases.first, - ), + onTap: () => emoji.value.startsWith("mxc://") + ? addTag( + id: ImagePack.emojiMarkdown( + emoji.aliases.first, + emoji.value, + description: switch (emoji.data) { + PackImage(:final body) => body, + _ => null, + }, + ), + name: emoji.aliases.first, + ) + : insertText(emoji.value), ), ) .toList(), diff --git a/lib/widgets/composer/overlays/room_overlay.dart b/lib/widgets/composer/overlays/room_overlay.dart index b5af177..c95db16 100644 --- a/lib/widgets/composer/overlays/room_overlay.dart +++ b/lib/widgets/composer/overlays/room_overlay.dart @@ -2,7 +2,8 @@ import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/via.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; +import "package:nexus/helpers/extensions/weighted_search.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; class const RoomOverlay( final String query, { @@ -14,45 +15,46 @@ class const RoomOverlay( Widget build(BuildContext context, WidgetRef ref) { final rooms = ref.watch(RoomsController.provider); return ListView( - children: - (query.isEmpty - ? rooms.values - : rooms.values.where( - (room) => (room.metadata?.name ?? room.metadata?.id ?? "") - .toLowerCase() - .contains(query.toLowerCase()), - )) - .map((room) { - final name = - room.metadata?.name ?? - room.metadata?.canonicalAlias ?? - room.metadata?.id ?? - "Unknown Room"; - return ListTile( - leading: AvatarOrHash( - room.metadata?.avatar, - name, - fallback: Icon(Icons.numbers), - ), - title: Text(name), - subtitle: room.metadata?.topic == null - ? null - : Text(room.metadata!.topic!, maxLines: 1), - onTap: () { - final vias = ref.watch(ViaController.provider(room)); - addTag( - id: "[#$name](matrix:roomid/${room.metadata?.id.substring(1)}$vias)", - name: - (room.metadata?.canonicalAlias ?? room.metadata?.id) - ?.substring(1) - .split(":") - .first ?? - "", - ); - }, + children: rooms.values + .search( + query, + (room) => [ + (room.metadata?.name, 3), + (room.metadata?.canonicalAlias, 2), + (room.metadata?.id, 1), + ], + ) + .map((room) { + final name = + room.metadata?.name ?? + room.metadata?.canonicalAlias ?? + room.metadata?.id ?? + "Unknown Room"; + return ListTile( + leading: AvatarOrHash( + room.metadata?.avatar, + name, + fallback: Icon(Icons.numbers), + ), + title: Text(name), + subtitle: room.metadata?.topic == null + ? null + : Text(room.metadata!.topic!, maxLines: 1), + onTap: () { + final vias = ref.watch(ViaController.provider(room)).viaQuery; + addTag( + id: "[#$name](matrix:roomid/${room.metadata?.id.substring(1)}$vias)", + name: + (room.metadata?.canonicalAlias ?? room.metadata?.id) + ?.substring(1) + .split(":") + .first ?? + "", ); - }) - .toList(), + }, + ); + }) + .toList(), ); } } diff --git a/lib/widgets/composer/overlays/tagger_overlay.dart b/lib/widgets/composer/overlays/tagger_overlay.dart index 7d973dc..e32a328 100644 --- a/lib/widgets/composer/overlays/tagger_overlay.dart +++ b/lib/widgets/composer/overlays/tagger_overlay.dart @@ -3,13 +3,14 @@ import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:nexus/widgets/composer/overlays/room_overlay.dart"; import "package:nexus/widgets/composer/overlays/user_overlay.dart"; import "package:nexus/widgets/composer/overlays/emoji_overlay.dart"; -import "package:nexus/widgets/loading.dart"; +import "package:nexus/widgets/common/loading.dart"; class const TaggerOverlay( final String query, { required final String roomId, required final void Function({required String id, required String name}) addTag, + required final void Function(String text) insertText, required final String? triggerCharacter, super.key, }) extends ConsumerWidget { @@ -27,7 +28,12 @@ class const TaggerOverlay( child: switch (triggerCharacter) { "@" => UserOverlay(query, roomId: roomId, addTag: addTag), "#" => RoomOverlay(query, addTag: addTag), - ":" => EmojiOverlay(query, roomId: roomId, addTag: addTag), + ":" => EmojiOverlay( + query, + roomId: roomId, + addTag: addTag, + insertText: insertText, + ), _ => Loading(), }, diff --git a/lib/widgets/composer/overlays/user_overlay.dart b/lib/widgets/composer/overlays/user_overlay.dart index fe4f70f..845fb3a 100644 --- a/lib/widgets/composer/overlays/user_overlay.dart +++ b/lib/widgets/composer/overlays/user_overlay.dart @@ -3,8 +3,9 @@ import "package:material_ui/material_ui.dart"; import "package:nexus/controllers/members_by_status.dart"; import "package:nexus/helpers/extensions/better_when.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/helpers/extensions/weighted_search.dart"; import "package:nexus/models/content/membership.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; class const UserOverlay( final String query, { @@ -20,45 +21,34 @@ class const UserOverlay( ) .betterWhen( data: (members) => ListView( - children: - (query.isEmpty - ? members - : members.where( - (member) => - member.stateKey?.toLowerCase().contains( - query.toLowerCase(), - ) == - true || - switch (member.content) { - MembershipContent(:final displayName) => - displayName?.toLowerCase().contains( - query.toLowerCase(), - ) == - true, - _ => false, - }, - )) - .map( - (member) => switch (member.content) { - MembershipContent(:final displayName, :final avatarUrl) => - ListTile( - leading: AvatarOrHash( - avatarUrl, - displayName ?? member.stateKey!.localpart, - ), - title: Text( - displayName ?? member.stateKey!.localpart, - ), - subtitle: Text(member.stateKey!), - onTap: () => addTag( - id: "[@$displayName](matrix:u/${member.stateKey!.substring(1)})", - name: member.stateKey!.localpart, - ), - ), - _ => SizedBox.shrink(), - }, - ) - .toList(), + children: members + .search( + query, + (member) => [ + if (member.content case MembershipContent(:final displayName)) + (displayName, 2), + (member.stateKey, 1), + ], + ) + .map( + (member) => switch (member.content) { + MembershipContent(:final displayName, :final avatarUrl) => + ListTile( + leading: AvatarOrHash( + avatarUrl, + displayName ?? member.stateKey!.localpart, + ), + title: Text(displayName ?? member.stateKey!.localpart), + subtitle: Text(member.stateKey!), + onTap: () => addTag( + id: "[@${displayName ?? member.stateKey!.localpart}](matrix:u/${member.stateKey!.substring(1)})", + name: member.stateKey!.localpart, + ), + ), + _ => SizedBox.shrink(), + }, + ) + .toList(), ), ); } diff --git a/lib/widgets/composer/relation_preview.dart b/lib/widgets/composer/relation_preview.dart index fca9de6..f319d74 100644 --- a/lib/widgets/composer/relation_preview.dart +++ b/lib/widgets/composer/relation_preview.dart @@ -2,7 +2,7 @@ import "package:material_ui/material_ui.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:nexus/models/event.dart"; import "package:nexus/models/relation_type.dart"; -import "package:nexus/widgets/event_preview.dart"; +import "package:nexus/widgets/renderers/event_preview.dart"; class const RelationPreview( final Event? relatedEvent, { @@ -29,7 +29,10 @@ class const RelationPreview( Expanded( child: Padding( padding: .symmetric(vertical: 8), - child: EventPreview(relatedEvent!), + child: EventPreview( + relatedEvent!.rowId, + roomId: relatedEvent!.roomId, + ), ), ), @@ -38,7 +41,7 @@ class const RelationPreview( onPressed: toggleShouldMention, child: Text( shouldMention ? "@On" : "@Off", - style: TextStyle( + style: .new( fontWeight: .w900, color: shouldMention ? null : Theme.of(context).disabledColor, ), diff --git a/lib/widgets/composer/typing_indicator.dart b/lib/widgets/composer/typing_indicator.dart index 2a30c4b..9cacb9c 100644 --- a/lib/widgets/composer/typing_indicator.dart +++ b/lib/widgets/composer/typing_indicator.dart @@ -4,11 +4,12 @@ import "package:material_ui/material_ui.dart"; import "package:nexus/controllers/room_typing.dart"; import "package:nexus/controllers/user.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; -import "package:nexus/helpers/extensions/show_user_popover.dart"; -import "package:nexus/widgets/bouncing_dots.dart"; +import "package:nexus/helpers/hooks/tap_recognizer.dart"; +import "package:nexus/widgets/common/bouncing_dots.dart"; +import "package:nexus/widgets/users/user_span.dart"; class const TypingIndicator(final String roomId, {super.key}) - extends ConsumerWidget { + extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); @@ -16,33 +17,31 @@ class const TypingIndicator(final String roomId, {super.key}) // Past three people, only the first two are named final named = typing.length > 3 ? 2 : typing.length; + // One for each person who can be named + final recognizers = [ + useTapRecognizer(), + useTapRecognizer(), + useTapRecognizer(), + ]; final subjects = [ ...typing .take(named) - .map( - (typingUserId) => WidgetSpan( - alignment: .baseline, - baseline: .alphabetic, - child: Builder( - builder: (context) => InkWell( - onTap: () => - context.showUserPopover(typingUserId, roomId: roomId), - child: Text( - ref - .watch( - UserController.provider( - .new(roomId: roomId, userId: typingUserId), - ), - ) - .value - ?.displayName ?? - typingUserId.localpart, - style: theme.textTheme.bodyMedium?.copyWith( - fontWeight: .bold, - ), - ), - ), - ), + .mapIndexed( + (index, typingUserId) => UserSpan( + context, + ref + .watch( + UserController.provider( + .new(roomId: roomId, userId: typingUserId), + ), + ) + .value + ?.displayName ?? + typingUserId.localpart, + userId: typingUserId, + roomId: roomId, + recognizer: recognizers[index], + style: TextStyle(fontWeight: .bold), ), ), if (typing.length > named) diff --git a/lib/widgets/emoji/emoji_picker.dart b/lib/widgets/emoji/emoji_picker.dart new file mode 100644 index 0000000..fb834c9 --- /dev/null +++ b/lib/widgets/emoji/emoji_picker.dart @@ -0,0 +1,84 @@ +import "dart:async"; + +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_emoji_picker/material_emoji_picker.dart" as upstream; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/all_emoji.dart"; +import "package:nexus/controllers/image_packs.dart"; +import "package:nexus/controllers/recent_emoji.dart"; +import "package:nexus/helpers/extensions/better_when.dart"; +import "package:nexus/helpers/extensions/image_pack_emoji.dart"; +import "package:nexus/main.dart"; +import "package:nexus/models/content/image_pack.dart"; + +class const EmojiPicker({ + required final String roomId, + + /// Has the [shortcode] and [description] of images from packs. + required final FutureOr Function( + String value, { + String? shortcode, + String? description, + }) + onSelection, + final bool allowFreeText = false, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final recentEmoji = ref.watch(RecentEmojiController.provider); + + return ref + .watch(AllEmojiController.provider(roomId)) + .betterWhen( + data: (categories) { + final allEmoji = categories.expand((category) => category.emojis); + final customCategories = + ref + .watch(ImagePacksController.provider(roomId)) + .value + ?.map((pack) => pack.emojiCategory) + .nonNulls + .toIList() ?? + const .empty(); + + return upstream.EmojiPicker( + onSelection: (emoji) async { + final image = switch (emoji.data) { + final PackImage image => image, + _ => null, + }; + await onSelection( + emoji.value, + shortcode: image == null ? null : emoji.aliases.first, + description: image?.body, + ); + + await ref + .read(RecentEmojiController.provider.notifier) + .add(emoji.value) + .onError(showError); + }, + onFreeText: allowFreeText ? (text) => onSelection(text) : null, + prependCategories: IList([ + .new( + icon: Icon(Icons.history), + name: "Recent", + emojis: .new( + recentEmoji + .map( + (recent) => allEmoji.firstWhereOrNull( + (element) => element.value == recent.emoji, + ), + ) + .nonNulls, + ), + ), + ]).addAll(customCategories), + ); + }, + ); + } +} diff --git a/lib/widgets/emoji/mxc_emoji.dart b/lib/widgets/emoji/mxc_emoji.dart new file mode 100644 index 0000000..e8c4916 --- /dev/null +++ b/lib/widgets/emoji/mxc_emoji.dart @@ -0,0 +1,16 @@ +import "package:material_ui/material_ui.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/helpers/mxc_image.dart"; + +/// A custom emoji or sticker from an image pack, scaled to fit its parent. +class const MxcEmoji(final Uri url, {final String? label, super.key}) + extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) => Image( + image: MxcImage(ref, .new(mxc: url)), + semanticLabel: label, + fit: .contain, + errorBuilder: (context, _, _) => + Icon(Icons.broken_image, color: Theme.of(context).colorScheme.error), + ); +} diff --git a/lib/widgets/emoji/sticker_picker.dart b/lib/widgets/emoji/sticker_picker.dart new file mode 100644 index 0000000..3222399 --- /dev/null +++ b/lib/widgets/emoji/sticker_picker.dart @@ -0,0 +1,47 @@ +import "dart:async"; + +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_emoji_picker/material_emoji_picker.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/image_packs.dart"; +import "package:nexus/helpers/extensions/better_when.dart"; +import "package:nexus/helpers/extensions/image_pack_emoji.dart"; +import "package:nexus/models/content/image_pack.dart"; + +/// Stickers from the image packs available in [roomId], grouped by pack. +class const StickerPicker({ + required final String roomId, + required final FutureOr Function(String shortcode, PackImage image) + onSelection, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) => ref + .watch(ImagePacksController.provider(roomId)) + .betterWhen( + data: (packs) { + final categories = packs + .map((pack) => pack.stickerCategory) + .nonNulls + .toIList(); + + return categories.isEmpty + ? Padding( + padding: .all(16), + child: Center(child: Text("No sticker packs available")), + ) + : EmojiPicker( + prependCategories: categories, + includeDefaultEmoji: false, + itemSize: 96, + searchHint: "Search stickers", + onSelection: (sticker) { + if (sticker.data case final PackImage image) { + return onSelection(sticker.aliases.first, image); + } + }, + ); + }, + ); +} diff --git a/lib/widgets/emoji_picker.dart b/lib/widgets/emoji_picker.dart deleted file mode 100644 index 7e49836..0000000 --- a/lib/widgets/emoji_picker.dart +++ /dev/null @@ -1,56 +0,0 @@ -import "dart:async"; - -import "package:collection/collection.dart"; -import "package:hooks_riverpod/hooks_riverpod.dart"; -import "package:material_emoji_picker/material_emoji_picker.dart" as upstream; -import "package:material_ui/material_ui.dart"; -import "package:nexus/controllers/recent_emoji.dart"; -import "package:nexus/helpers/extensions/better_when.dart"; -import "package:nexus/main.dart"; - -class const EmojiPicker({ - required final FutureOr Function(String value) onSelection, - final bool allowFreeText = false, - super.key, -}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final recentEmoji = ref.watch(RecentEmojiController.provider); - - return ref - .watch(upstream.EmojiController.provider) - .betterWhen( - data: (categories) => upstream.EmojiPicker( - onSelection: (emoji, isFreeText) async { - await onSelection(emoji); - - if (!isFreeText) { - await ref - .read(RecentEmojiController.provider.notifier) - .add(emoji) - .onError(showError); - } - }, - allowFreeText: allowFreeText, - prependCategories: .new([ - .new( - icon: Icon(Icons.history), - name: "Recent", - emojis: .new( - recentEmoji - .map( - (recent) => categories - .map((element) => element.emojis) - .flattened - .firstWhereOrNull( - (element) => element.value == recent.emoji, - ), - ) - .nonNulls, - ), - ), - ]), - ), - ); - } -} diff --git a/lib/widgets/recovery_key_sheet.dart b/lib/widgets/encryption/recovery_key_sheet.dart similarity index 98% rename from lib/widgets/recovery_key_sheet.dart rename to lib/widgets/encryption/recovery_key_sheet.dart index 68ec682..36e4e09 100644 --- a/lib/widgets/recovery_key_sheet.dart +++ b/lib/widgets/encryption/recovery_key_sheet.dart @@ -4,12 +4,12 @@ import "package:flutter/services.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/helpers/launch_helper.dart"; import "package:nexus/models/gomuks_exception.dart"; import "package:nexus/models/recovery_key.dart"; -import "package:nexus/widgets/sheet_layout.dart"; /// Shows a newly generated recovery key, and once the user confirms they've /// saved it, resets encryption with it. Pops with true if that succeeded. diff --git a/lib/widgets/reset_encryption_sheet.dart b/lib/widgets/encryption/reset_encryption_sheet.dart similarity index 97% rename from lib/widgets/reset_encryption_sheet.dart rename to lib/widgets/encryption/reset_encryption_sheet.dart index 8482a8f..40b0074 100644 --- a/lib/widgets/reset_encryption_sheet.dart +++ b/lib/widgets/encryption/reset_encryption_sheet.dart @@ -1,13 +1,12 @@ import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; import "package:nexus/main.dart"; import "package:nexus/models/client_state.dart"; -import "package:nexus/widgets/recovery_key_sheet.dart"; -import "package:nexus/widgets/sheet_layout.dart"; +import "package:nexus/widgets/encryption/recovery_key_sheet.dart"; class const ResetEncryptionSheet({ /// Whether this is shown as a page rather than in a sheet, in which case it diff --git a/lib/widgets/event_preview.dart b/lib/widgets/event_preview.dart deleted file mode 100644 index 1b88fa8..0000000 --- a/lib/widgets/event_preview.dart +++ /dev/null @@ -1,40 +0,0 @@ -import "package:material_ui/material_ui.dart"; -import "package:nexus/models/content/message.dart"; -import "package:nexus/models/event.dart"; -import "package:nexus/widgets/lazy_loading/message_avatar.dart"; -import "package:nexus/widgets/lazy_loading/message_displayname.dart"; -import "package:nexus/widgets/renderers/event.dart"; - -class const EventPreview(final Event event, {super.key}) - extends StatelessWidget { - @override - Widget build(BuildContext context) => IgnorePointer( - child: Padding( - padding: .symmetric(vertical: 4), - child: Row( - mainAxisSize: .min, - spacing: 8, - children: [ - if (event.content is MessageContent) MessageAvatar(event, height: 36), - - Flexible( - child: Column( - mainAxisAlignment: .center, - crossAxisAlignment: .start, - children: [ - if (event.content is MessageContent) - MessageDisplayname(event, shouldWrap: false), - EventRenderer( - event.rowId, - roomId: event.roomId, - textOnly: true, - maxLines: 1, - ), - ], - ), - ), - ], - ), - ), - ); -} diff --git a/lib/widgets/expandable_image.dart b/lib/widgets/expandable_image.dart deleted file mode 100644 index f10221e..0000000 --- a/lib/widgets/expandable_image.dart +++ /dev/null @@ -1,73 +0,0 @@ -import "package:material_ui/material_ui.dart"; -import "package:hooks_riverpod/hooks_riverpod.dart"; -import "package:m3e_buttons/m3e_buttons.dart"; -import "package:nexus/helpers/extensions/save_attachment.dart"; -import "package:nexus/helpers/mxc_image.dart"; -import "package:nexus/models/requests/download_media.dart"; -import "package:nexus/widgets/error_dialog.dart"; - -final class const ExpandableImage( - final DownloadMediaRequest? request, { - required final Widget child, - - /// If set, a download button is shown, suggesting this filename - final String? downloadFilename, - super.key, -}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) => InkWell( - onTap: request == null - ? null - : () => showDialog( - context: context, - builder: (_) => SafeArea( - child: Stack( - children: [ - Positioned.fill( - child: GestureDetector( - onTap: Navigator.of(context).pop, - child: InteractiveViewer( - maxScale: 10, - child: Image( - errorBuilder: (_, error, stackTrace) => ErrorDialog( - "Loading failed for ${request?.mxc}\nError: $error", - stackTrace, - ), - image: MxcImage(ref, request!), - ), - ), - ), - ), - Align( - alignment: .topRight, - child: Padding( - padding: .all(32), - child: Row( - mainAxisSize: .min, - spacing: 8, - children: [ - if (downloadFilename != null) - M3EButton( - onPressed: () => context.saveAttachment( - ref, - request!.mxc, - encrypted: request!.encrypted, - filename: downloadFilename, - ), - child: Icon(Icons.download), - ), - M3EButton( - onPressed: Navigator.of(context).pop, - child: Icon(Icons.close), - ), - ], - ), - ), - ), - ], - ), - ), - ), - child: child, - ); -} diff --git a/lib/widgets/html/html.dart b/lib/widgets/html/html.dart index 5ea584f..9236e9a 100644 --- a/lib/widgets/html/html.dart +++ b/lib/widgets/html/html.dart @@ -2,10 +2,11 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:material_ui/material_ui.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart"; +import "package:html/dom.dart" as dom; import "package:nexus/helpers/extensions/get_link_info.dart"; import "package:nexus/helpers/launch_helper.dart"; import "package:nexus/helpers/mxc_image.dart"; -import "package:nexus/widgets/expandable_image.dart"; +import "package:nexus/widgets/common/expandable_image.dart"; import "package:nexus/widgets/html/mention_chip.dart"; import "package:nexus/widgets/html/spoiler_text.dart"; import "package:nexus/widgets/html/code_block.dart"; @@ -65,6 +66,20 @@ class const Html( Html(element.innerHtml, textStyle: textStyle, roomId: roomId), ), + "font" => InlineCustomWidget( + child: Html( + (dom.Element.tag("span") + ..attributes.addAll({ + "data-mx-color": ?element.attributes["color"], + ...element.attributes, + }) + ..innerHtml = element.innerHtml) + .outerHtml, + textStyle: textStyle, + roomId: roomId, + ), + ), + "a" => element.attributes["href"]?.linkInfo == null ? null @@ -76,7 +91,7 @@ class const Html( src == null ? SizedBox.shrink() : InlineCustomWidget( - alignment: PlaceholderAlignment.middle, + alignment: .middle, child: ExpandableImage( .new(mxc: src), downloadFilename: src.pathSegments.last, diff --git a/lib/widgets/html/mention_chip.dart b/lib/widgets/html/mention_chip.dart index 6ae2221..d6c7c0d 100644 --- a/lib/widgets/html/mention_chip.dart +++ b/lib/widgets/html/mention_chip.dart @@ -1,15 +1,11 @@ import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:nexus/controllers/event.dart"; import "package:nexus/controllers/room_summary.dart"; import "package:nexus/controllers/user.dart"; -import "package:nexus/helpers/extensions/focus_room.dart"; import "package:nexus/helpers/extensions/get_link_info.dart"; -import "package:nexus/helpers/extensions/show_user_popover.dart"; +import "package:nexus/helpers/extensions/open_link_info.dart"; import "package:nexus/models/content/membership.dart"; import "package:nexus/models/room_summary.dart"; -import "package:nexus/widgets/room_summary_sheet.dart"; class const MentionChip(final String content, final String? roomId, {super.key}) extends ConsumerWidget { @@ -28,7 +24,9 @@ class const MentionChip(final String content, final String? roomId, {super.key}) "#" || "!" => ref .watch( - RoomSummaryController.provider(.new(roomIdOrAlias: mention!)), + RoomSummaryController.provider( + .new(roomIdOrAlias: mention!, via: linkInfo!.via), + ), ) .whenOrNull(data: (data) => data) ?? RoomSummary(roomId: mention), @@ -39,43 +37,7 @@ class const MentionChip(final String content, final String? roomId, {super.key}) return mention == null ? SizedBox.shrink() : InkWell( - onTap: () async { - if (data is MembershipContent) { - context.showUserPopover(mention, roomId: roomId); - } else if (data case RoomSummary summary) { - final eventRowId = linkInfo?.eventId == null - ? null - : await ref - .read( - EventController.provider( - .new( - roomId: summary.roomId, - eventId: linkInfo!.eventId!, - ), - ).selectAsync((data) => data?.rowId), - ) - .onError((_, _) => null); - - if (!await ref.focusRoom(summary.roomId, eventRowId) && - context.mounted) { - context.showAdaptiveSheet( - (context) => Consumer( - builder: (context, ref, _) => RoomSummarySheet( - ref - .watch( - RoomSummaryController.provider( - .new(roomIdOrAlias: mention), - ), - ) - .whenOrNull(data: (data) => data) ?? - summary, - via: linkInfo?.via, - ), - ), - ); - } - } - }, + onTap: () => ref.openLinkInfo(context, linkInfo!, roomId: roomId), child: Text( switch (data) { RoomSummary summary => diff --git a/lib/widgets/lazy_loading/message_avatar.dart b/lib/widgets/lazy_loading/message_avatar.dart index 0279eca..80a1101 100644 --- a/lib/widgets/lazy_loading/message_avatar.dart +++ b/lib/widgets/lazy_loading/message_avatar.dart @@ -4,7 +4,7 @@ import "package:nexus/controllers/author.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/show_user_popover.dart"; import "package:nexus/models/event.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; class const MessageAvatar( final Event event, { @@ -13,7 +13,7 @@ class const MessageAvatar( }) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) => - switch (ref.watch(AuthorController.provider(event))) { + switch (ref.watch(AuthorController.provider(.fromEvent(event)))) { AsyncData(:final value) || AsyncLoading(:final value?) => InkWell( onTap: () => context.showUserPopover(event.sender, roomId: event.roomId), diff --git a/lib/widgets/lazy_loading/message_displayname.dart b/lib/widgets/lazy_loading/message_displayname.dart index e8e4791..0f68ac5 100644 --- a/lib/widgets/lazy_loading/message_displayname.dart +++ b/lib/widgets/lazy_loading/message_displayname.dart @@ -3,7 +3,7 @@ import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/author.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/show_user_popover.dart"; -import "package:nexus/helpers/extensions/string_to_color.dart"; +import "package:nexus/helpers/extensions/displayname_color.dart"; import "package:nexus/models/event.dart"; import "package:nexus/models/content/membership.dart"; @@ -15,43 +15,44 @@ class const MessageDisplayname( super.key, }) extends ConsumerWidget { @override - Widget build(BuildContext context, WidgetRef ref) => switch (ref.watch( - AuthorController.provider(event), - )) { - AsyncData(:final MembershipContent? value) || - AsyncLoading(:final value) || - AsyncError(:final value) => InkWell( - onTap: clickable - ? () => context.showUserPopover(event.sender, roomId: event.roomId) - : null, - child: switch ([ - Text( - value?.displayName ?? event.sender.localpart, - style: - style ?? .new(color: event.sender.colorHash, fontWeight: .bold), - maxLines: 1, - overflow: .ellipsis, - ), - if (event.pmp != null) + Widget build(BuildContext context, WidgetRef ref) { + final color = ref.displaynameColor(event.roomId, event.sender); + + return switch (ref.watch(AuthorController.provider(.fromEvent(event)))) { + AsyncData(:final MembershipContent? value) || + AsyncLoading(:final value) || + AsyncError(:final value) => InkWell( + onTap: clickable + ? () => context.showUserPopover(event.sender, roomId: event.roomId) + : null, + child: switch ([ Text( - "(via ${event.sender})", - style: Theme.of(context).textTheme.labelSmall - ?.copyWith(color: event.sender.colorHash, fontWeight: .bold), + value?.displayName ?? event.sender.localpart, + style: style ?? .new(color: color, fontWeight: .bold), maxLines: 1, overflow: .ellipsis, ), - ]) { - final children when shouldWrap => Wrap( - spacing: 4, - crossAxisAlignment: .center, - children: children, - ), - final children => Row( - spacing: 4, - mainAxisSize: .min, - children: [for (final child in children) Flexible(child: child)], - ), - }, - ), - }; + if (event.pmp != null) + Text( + "(via ${event.sender})", + style: Theme.of(context).textTheme.labelSmall + ?.copyWith(color: color, fontWeight: .bold), + maxLines: 1, + overflow: .ellipsis, + ), + ]) { + final children when shouldWrap => Wrap( + spacing: 4, + crossAxisAlignment: .center, + children: children, + ), + final children => Row( + spacing: 4, + mainAxisSize: .min, + children: children.map((child) => Flexible(child: child)).toList(), + ), + }, + ), + }; + } } diff --git a/lib/widgets/linkified_text.dart b/lib/widgets/linkified_text.dart deleted file mode 100644 index 1c12d22..0000000 --- a/lib/widgets/linkified_text.dart +++ /dev/null @@ -1,26 +0,0 @@ -import "package:material_ui/material_ui.dart"; -import "package:flutter_linkify/flutter_linkify.dart"; -import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:nexus/helpers/launch_helper.dart"; - -final class const LinkifiedText( - final String text, { - final int? maxLines, - final TextStyle? style, - super.key, -}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) => - MaterialUiCompatibilityBridge( - child: Linkify( - text: text, - maxLines: maxLines, - style: style, - options: .new(humanize: false), - onOpen: (link) => - ref.read(LaunchHelper.provider).launchUrl(.parse(link.url)), - linkStyle: .new(color: Theme.of(context).colorScheme.primary), - overflow: maxLines == null ? null : .ellipsis, - ), - ); -} diff --git a/lib/widgets/location/location_map.dart b/lib/widgets/location/location_map.dart new file mode 100644 index 0000000..c9fb4b3 --- /dev/null +++ b/lib/widgets/location/location_map.dart @@ -0,0 +1,83 @@ +import "package:flutter_map/flutter_map.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:latlong2/latlong.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/helpers/launch_helper.dart"; + +class const LocationMap( + final LatLng center, { + final bool showMarker = true, + final bool interactive = false, + final double zoom = 15, + final MapController? controller, + final PositionCallback? onPositionChanged, + super.key, +}) extends ConsumerWidget { + /// The marker's icon, which points at the location from its bottom. + static Widget markerOf(BuildContext context) => Icon( + Icons.location_pin, + size: 40, + color: Theme.of(context).colorScheme.primary, + ); + + @override + Widget build(BuildContext context, WidgetRef ref) => FlutterMap( + mapController: controller, + options: MapOptions( + initialCenter: center, + initialZoom: zoom, + minZoom: 2, + maxZoom: 19, + onPositionChanged: onPositionChanged, + interactionOptions: InteractionOptions( + flags: interactive + ? InteractiveFlag.all & ~InteractiveFlag.rotate + : InteractiveFlag.none, + ), + ), + children: [ + TileLayer( + urlTemplate: "https://tile.openstreetmap.org/{z}/{x}/{y}.png", + // Required by OpenStreetMap's tile usage policy + userAgentPackageName: "nexus.federated.nexus", + ), + if (showMarker) + MarkerLayer( + markers: [ + Marker( + point: center, + width: 40, + height: 40, + alignment: .topCenter, + child: markerOf(context), + ), + ], + ), + // Required by OpenStreetMap + Align( + alignment: .bottomRight, + child: Material( + color: Theme.of(context).colorScheme.surface.withValues(alpha: 0.8), + child: InkWell( + onTap: interactive + ? () => ref + .read(LaunchHelper.provider) + .launchUrl( + Uri.https("www.openstreetmap.org", "/copyright"), + ) + : null, + child: Padding( + padding: const .symmetric(horizontal: 4, vertical: 2), + child: Text( + "© OpenStreetMap", + style: Theme.of(context).textTheme.labelSmall, + maxLines: 1, + overflow: .ellipsis, + ), + ), + ), + ), + ), + ], + ); +} diff --git a/lib/widgets/location/location_message.dart b/lib/widgets/location/location_message.dart new file mode 100644 index 0000000..661b7dd --- /dev/null +++ b/lib/widgets/location/location_message.dart @@ -0,0 +1,68 @@ +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/models/content/message.dart"; +import "package:nexus/models/location.dart"; +import "package:nexus/widgets/location/location_map.dart"; +import "package:nexus/widgets/location/location_viewer_sheet.dart"; + +class const LocationMessage(final LocationMessageContent content, {super.key}) + extends StatelessWidget { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final point = content.point; + final description = content.description; + + if (point == null) { + return Wrap( + spacing: 8, + children: [ + Text( + "Invalid location:", + style: TextStyle(color: theme.colorScheme.error), + ), + Text(content.body), + ], + ); + } + + return Column( + crossAxisAlignment: .start, + spacing: 8, + children: [ + if (description != null) + Text(description, style: theme.textTheme.titleSmall), + ConstrainedBox( + constraints: const .new(maxWidth: 400), + child: AspectRatio( + aspectRatio: 3 / 2, + child: ClipRRect( + borderRadius: .circular(12), + child: Stack( + children: [ + LocationMap(point), + Positioned.fill( + child: Material( + type: .transparency, + child: InkWell( + onTap: () => context.showAdaptiveSheet( + enableDrag: false, + (_) => LocationViewerSheet( + point, + type: content.assetType, + description: description, + ), + ), + ), + ), + ), + ], + ), + ), + ), + ), + Text(point.formatted, style: theme.textTheme.labelSmall), + ], + ); + } +} diff --git a/lib/widgets/location/location_picker_sheet.dart b/lib/widgets/location/location_picker_sheet.dart new file mode 100644 index 0000000..4fb61bf --- /dev/null +++ b/lib/widgets/location/location_picker_sheet.dart @@ -0,0 +1,157 @@ +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:flutter_map/flutter_map.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:latlong2/latlong.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/helpers/current_location_helper.dart"; +import "package:nexus/models/content/message.dart"; +import "package:nexus/models/location.dart"; +import "package:nexus/widgets/location/location_map.dart"; + +/// Chooses a location to share, either the user's own or a pin dropped on the +/// map. +class const LocationPickerSheet({ + required final void Function(LocationMessageContent location) onPick, + super.key, +}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final mapController = useMemoized(MapController.new); + useEffect(() => mapController.dispose, [mapController]); + + // Not state, as it changes every frame while the map moves + final center = useRef(const LatLng(0, 0)); + + // Until the map is moved or the user is located, it's an arbitrary spot + final placed = useState(false); + // Whether the map is on the user's location, and its accuracy in meters + final own = useState<({double? accuracy})?>(null); + final locating = useState(false); + final error = useState(null); + final descriptionController = useTextEditingController(); + + Future locate({bool askPermission = true}) async { + locating.value = true; + error.value = null; + try { + final found = await ref + .read(CurrentLocationHelper.provider) + .get(askPermission: askPermission); + // Doesn't move away from a spot the user chose while it was finding them + if (found == null || + !context.mounted || + (!askPermission && placed.value)) { + return; + } + + final (point, accuracy) = found; + center.value = point; + mapController.move(point, 16); + own.value = (accuracy: accuracy); + placed.value = true; + } catch (caught) { + if (context.mounted && askPermission) error.value = caught.toString(); + } finally { + if (context.mounted) locating.value = false; + } + } + + // Starts at the user's location if they've already allowed it, except on + // Linux, where checking would ask + useEffect(() { + locate(askPermission: false); + return null; + }, []); + + void share() { + final description = descriptionController.text.trim(); + final self = own.value != null; + final geoUri = GeoUri.fromLatLng( + center.value, + uncertainty: own.value?.accuracy, + ); + + onPick( + .new( + body: + "${description.isEmpty ? (self ? "My location" : "Location") : description}: $geoUri", + geoUri: geoUri, + location: .new( + uri: geoUri, + description: description.isEmpty ? null : description, + ), + asset: .new(type: self ? .self : .pin), + ), + ); + } + + return SheetLayout( + title: const Text("Share Location"), + actions: [ + TextButton( + onPressed: Navigator.of(context).pop, + child: const Text("Cancel"), + ), + TextButton( + onPressed: placed.value ? share : null, + child: const Text("Share"), + ), + ], + children: [ + SizedBox( + height: 300, + child: ClipRRect( + borderRadius: .circular(12), + child: Stack( + children: [ + LocationMap( + center.value, + zoom: 2, + interactive: true, + showMarker: false, + controller: mapController, + onPositionChanged: (camera, hasGesture) { + center.value = camera.center; + if (hasGesture) { + own.value = null; + placed.value = true; + } + }, + ), + IgnorePointer( + child: Center( + child: Transform.translate( + offset: const .new(0, -20), + child: LocationMap.markerOf(context), + ), + ), + ), + ], + ), + ), + ), + OutlinedButton.icon( + onPressed: locating.value ? null : locate, + icon: locating.value + ? const SizedBox.square( + dimension: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.my_location), + label: const Text("Use current location"), + ), + if (error.value case final error?) + Text( + error, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + TextField( + controller: descriptionController, + textCapitalization: .sentences, + decoration: const .new(labelText: "Description (optional)"), + ), + ], + ); + } +} diff --git a/lib/widgets/location/location_viewer_sheet.dart b/lib/widgets/location/location_viewer_sheet.dart new file mode 100644 index 0000000..ca74ab0 --- /dev/null +++ b/lib/widgets/location/location_viewer_sheet.dart @@ -0,0 +1,43 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:latlong2/latlong.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/helpers/launch_helper.dart"; +import "package:nexus/models/location.dart"; +import "package:nexus/widgets/location/location_map.dart"; + +class const LocationViewerSheet( + final LatLng point, { + final LocationAssetType type = .self, + final String? description, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) => SheetLayout( + title: Text( + description ?? (type == .self ? "Shared Location" : "Location"), + ), + actions: [ + TextButton( + onPressed: () => ref + .read(LaunchHelper.provider) + .launchUrl(GeoUri.openStreetMap(point)), + child: const Text("Open in OpenStreetMap"), + ), + TextButton( + onPressed: Navigator.of(context).pop, + child: const Text("Close"), + ), + ], + children: [ + SizedBox( + height: 400, + child: ClipRRect( + borderRadius: .circular(12), + child: LocationMap(point, interactive: true), + ), + ), + SelectableText(point.formatted), + ], + ); +} diff --git a/lib/widgets/pages/chat.dart b/lib/widgets/pages/chat.dart index 9e18da7..c5d704f 100644 --- a/lib/widgets/pages/chat.dart +++ b/lib/widgets/pages/chat.dart @@ -1,15 +1,18 @@ import "package:flutter_hooks/flutter_hooks.dart"; import "package:material_ui/material_ui.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/init_complete.dart"; +import "package:nexus/controllers/link_request.dart"; +import "package:nexus/helpers/extensions/open_link_info.dart"; +import "package:nexus/main.dart"; import "package:nexus/controllers/selected_room.dart"; import "package:nexus/controllers/notification_request.dart"; -import "package:nexus/helpers/extensions/is_desktop.dart"; -import "package:nexus/widgets/appbar.dart"; -import "package:nexus/widgets/sidebar.dart"; -import "package:nexus/widgets/sync_status_banner.dart"; +import "package:nexus/widgets/common/appbar.dart"; +import "package:nexus/widgets/sidebar/sidebar.dart"; +import "package:nexus/widgets/common/sync_status_banner.dart"; import "package:nexus/widgets/room_chat/room_chat.dart"; -import "package:nexus/widgets/loading.dart"; +import "package:nexus/widgets/common/loading.dart"; class const ChatPage({super.key}) extends HookConsumerWidget { @override @@ -33,6 +36,23 @@ class const ChatPage({super.key}) extends HookConsumerWidget { return null; }, [notificationRequest, initComplete]); + final linkRequest = ref.watch(LinkRequestController.provider); + + // Open Matrix links the OS launched Nexus with, once sync has completed + useEffect(() { + if (linkRequest == null || !initComplete) return null; + + WidgetsBinding.instance.addPostFrameCallback((_) { + ref.read(LinkRequestController.provider.notifier).consume(); + navigatorKey.currentState?.popUntil((route) => route.isFirst); + final scaffoldContext = scaffoldKey.currentContext; + if (scaffoldContext == null) return; + + ref.openLinkInfo(scaffoldContext, linkRequest).onError(showError); + }); + return null; + }, [linkRequest, initComplete]); + return LayoutBuilder( builder: (context, constraints) { final isDesktop = context.isDesktop; diff --git a/lib/widgets/pages/explore.dart b/lib/widgets/pages/explore.dart new file mode 100644 index 0000000..3cd77ea --- /dev/null +++ b/lib/widgets/pages/explore.dart @@ -0,0 +1,338 @@ +import "dart:math"; + +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:navigation_rail_m3e/navigation_rail_m3e.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/client_state.dart"; +import "package:nexus/controllers/room_directory.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/controllers/settings.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/main.dart"; +import "package:nexus/helpers/extensions/room_summary_display.dart"; +import "package:nexus/widgets/rooms/add_directory_server_sheet.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/rooms/room_summary_sheet.dart"; +import "package:nexus/widgets/common/divider_text.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/widgets/common/loading.dart"; +import "package:nexus/widgets/common/m3e_rail_theme.dart"; +import "package:nexus/widgets/rooms/room_directory_card.dart"; + +class const ExplorePage({super.key}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final ownServer = ref.watch( + ClientStateController.provider.select( + (state) => state?.userId?.serverName, + ), + ); + final savedServers = ref + .watch( + SettingsController.provider.select( + (settings) => settings.value?.directoryServers, + ), + ) + ?.where((server) => server != ownServer) + .toIList(); + + // Null is the user's own server + final selected = useState(null); + final servers = IList([null, ...?savedServers]); + String labelOf(String? server) => server ?? ownServer ?? "Home"; + IconData iconOf(String? server) => server == null ? Icons.home : Icons.dns; + + final current = servers[max(0, servers.indexOf(selected.value))]; + final provider = RoomDirectoryController.provider(current); + final loadMore = RoomDirectoryController.loadMoreMutation(current); + final loadingMore = ref.watch(loadMore).isPending; + final directory = ref.watch(provider); + final theme = Theme.of(context); + + final via = IList([?current ?? ownServer]); + + Future addServer() async { + final server = await context.showAdaptiveSheet( + (_) => AddDirectoryServerSheet( + existing: .new([?ownServer, ...servers.nonNulls]), + ), + ); + if (server == null) return; + + final settings = await ref.read(SettingsController.provider.future); + await ref + .read(SettingsController.provider.notifier) + .set( + settings.copyWith( + directoryServers: settings.directoryServers.add(server), + ), + ); + if (context.mounted) selected.value = server; + } + + Future removeServer(String server) async { + selected.value = null; + final settings = await ref.read(SettingsController.provider.future); + await ref + .read(SettingsController.provider.notifier) + .set( + settings.copyWith( + directoryServers: settings.directoryServers.remove(server), + ), + ); + } + + return LayoutBuilder( + builder: (context, constraints) { + final isWide = constraints.maxWidth >= 700; + + final searchBar = SearchAnchor.bar( + barHintText: "Search...", + isFullScreen: !isWide, + suggestionsBuilder: (suggestionsContext, controller) async { + final text = controller.text.trim(); + if (text.isEmpty) return const []; + + // Each search hits the server, so wait for the user to stop typing + await Future.delayed(Durations.long2); + if (controller.text.trim() != text) return const []; + + try { + final directory = await ref + .read(ClientController.provider.notifier) + .getRoomDirectory( + .new( + server: current, + limit: 20, + filter: .new(genericSearchTerm: text), + ), + ); + return directory.rooms.map( + (summary) => Consumer( + builder: (_, ref, _) { + final joined = ref.watch( + RoomsController.provider.select( + (rooms) => rooms.containsKey(summary.roomId), + ), + ); + + return ListTile( + onTap: () { + Navigator.of(suggestionsContext).pop(); + controller.text = ""; + + context.showAdaptiveSheet( + (_) => RoomSummarySheet( + summary, + via: joined ? null : via, + ), + ); + }, + leading: AvatarOrHash( + summary.avatarUrl, + summary.displayName, + fallback: Icon(summary.icon), + ), + title: Text(summary.displayName), + subtitle: Text( + [ + summary.details, + if (joined) "Joined", + ].where((part) => part.isNotEmpty).join(" · "), + ), + ); + }, + ), + ); + } catch (error) { + return [ + ListTile( + leading: const Icon(Icons.error_outline), + title: const Text("Couldn't search this server"), + subtitle: Text(error.toString()), + ), + ]; + } + }, + ); + + final results = CustomScrollView( + slivers: [ + SliverPadding( + padding: const .all(16), + sliver: SliverList.list( + children: [ + if (!isWide) + Padding( + padding: const .only(bottom: 12), + child: SingleChildScrollView( + scrollDirection: .horizontal, + child: Row( + spacing: 8, + children: [ + ...servers.map( + (server) => ChoiceChip( + avatar: Icon(iconOf(server)), + label: Text(labelOf(server)), + selected: current == server, + onSelected: (_) => selected.value = server, + ), + ), + ActionChip( + avatar: const Icon(Icons.add), + label: const Text("Add server"), + onPressed: () => addServer().onError(showError), + ), + ], + ), + ), + ), + searchBar, + const SizedBox(height: 16), + Text(switch (directory.value?.totalRoomCountEstimate) { + final count? when count > 0 => "Popular Rooms ($count)", + _ => "Popular Rooms", + }, style: theme.textTheme.titleLarge), + ], + ), + ), + ...switch (directory) { + AsyncData(:final value) when value.rooms.isEmpty => [ + SliverFillRemaining( + hasScrollBody: false, + child: Center( + child: Column( + mainAxisSize: .min, + children: [ + Icon( + Icons.search_off, + size: 48, + color: theme.colorScheme.onSurface, + ), + const SizedBox(height: 12), + Text( + "No rooms found", + style: theme.textTheme.headlineSmall, + ), + ], + ), + ), + ), + ], + AsyncData(:final value) || AsyncLoading(:final value?) => [ + SliverPadding( + padding: const .symmetric(horizontal: 16), + sliver: SliverLayoutBuilder( + builder: (_, constraints) => SliverGrid.builder( + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: max( + 1, + (constraints.crossAxisExtent + 12) ~/ (280 + 12), + ), + mainAxisExtent: 210, + crossAxisSpacing: 12, + mainAxisSpacing: 12, + ), + itemCount: value.rooms.length, + itemBuilder: (_, index) => + RoomDirectoryCard(value.rooms[index], via: via), + ), + ), + ), + SliverPadding( + padding: const .all(16), + sliver: SliverToBoxAdapter( + child: value.nextBatch == null + ? null + : Center( + child: TextButton( + onPressed: loadingMore + ? null + : () => loadMore + .run( + ref, + (transaction) => transaction + .get(provider.notifier) + .loadMore(), + ) + .onError(showError), + child: const Text("Load more"), + ), + ), + ), + ), + ], + AsyncError(:final error, :final stackTrace) => [ + SliverFillRemaining( + hasScrollBody: false, + child: ErrorDialog(error, stackTrace, provider: provider), + ), + ], + AsyncLoading() => [ + const SliverFillRemaining( + hasScrollBody: false, + child: Loading(), + ), + ], + }, + ], + ); + + return Scaffold( + appBar: AppBar( + title: const Text("Explore Rooms"), + actionsPadding: const .symmetric(horizontal: 12), + actions: [ + if (current case final server?) + IconButton( + tooltip: "Remove server", + onPressed: () => removeServer(server).onError(showError), + icon: const Icon(Icons.delete_outline), + ), + ], + ), + body: isWide + ? Row( + children: [ + M3ERailTheme( + builder: (_) => NavigationRailM3E( + type: .alwaysExpand, + scrollable: true, + fab: .new( + icon: const Icon(Icons.add), + label: "Add server", + tooltip: "Add a server to browse", + onPressed: () => addServer().onError(showError), + ), + sections: [ + .new( + header: const DividerText("Servers"), + destinations: servers + .map( + (server) => NavigationRailM3EDestination( + icon: Icon(iconOf(server)), + label: labelOf(server), + ), + ) + .toList(), + ), + ], + selectedIndex: servers.indexOf(current), + onDestinationSelected: (index) => + selected.value = servers[index], + ), + ), + const VerticalDivider(), + Expanded(child: results), + ], + ) + : results, + ); + }, + ); + } +} diff --git a/lib/widgets/pages/select_server.dart b/lib/widgets/pages/select_server.dart index 66c40a5..a3102e6 100644 --- a/lib/widgets/pages/select_server.dart +++ b/lib/widgets/pages/select_server.dart @@ -13,8 +13,9 @@ import "package:nexus/models/gomuks_exception.dart"; import "package:nexus/models/homeserver.dart"; import "package:nexus/models/oauth_auth_code_response.dart"; import "package:nexus/widgets/pages/settings.dart"; -import "package:nexus/widgets/appbar.dart"; -import "package:nexus/widgets/divider_text.dart"; +import "package:nexus/widgets/common/account_switcher.dart"; +import "package:nexus/widgets/common/appbar.dart"; +import "package:nexus/widgets/common/divider_text.dart"; class const SelectServerPage({super.key}) extends HookConsumerWidget { @override @@ -47,7 +48,7 @@ class const SelectServerPage({super.key}) extends HookConsumerWidget { Future tryLogin(Uri url) async { final OAuthAuthCodeResponse codeResponse; try { - codeResponse = await ref.watch( + codeResponse = await ref.read( AuthUrlController.provider(url).future, ); } on GomuksException catch (error) { @@ -60,6 +61,8 @@ class const SelectServerPage({super.key}) extends HookConsumerWidget { return; } + if (!context.mounted) return; + await ref.read(LaunchHelper.provider).launchUrl(codeResponse.url); AppLinks().uriLinkStream.listen((encodedUri) async { @@ -70,7 +73,7 @@ class const SelectServerPage({super.key}) extends HookConsumerWidget { try { final code = encodedUri.queryParameters["code"]; - if (code != null) { + if (code != null && context.mounted) { await ref .read(ClientController.provider.notifier) .exchangeToken( @@ -120,6 +123,7 @@ class const SelectServerPage({super.key}) extends HookConsumerWidget { return Scaffold( appBar: Appbar( actions: .new([ + const AccountSwitcher(onlyWithOthers: true), IconButton( onPressed: () => showDialog(context: context, builder: (_) => SettingsPage()), @@ -186,31 +190,34 @@ class const SelectServerPage({super.key}) extends HookConsumerWidget { name: "Matrix.org", description: "The Matrix.org Foundation offers the matrix.org homeserver as an easy entry point for anyone wanting to try out Matrix.", url: .https("matrix.org"), - iconUrl: - "https://raw.githubusercontent.com/element-hq/logos/refs/heads/master/matrix/matrix-favicon${Theme.brightnessOf(context) == Brightness.dark ? "-white" : ""}.png", + icon: SvgPicture.asset( + "assets/bundled/matrix.svg", + colorFilter: .mode(theme.colorScheme.onSurface, .srcIn), + ), ), .new( name: "Federated Nexus", description: "Federated Nexus is a community resource hosting multiple FOSS (especially federated) services, including Matrix and Forgejo. By the same developers who made Nexus client.", url: .https("federated.nexus"), - iconUrl: "https://federated.nexus/images/icon.png", + icon: SvgPicture.asset( + "assets/bundled/federated_nexus.svg", + ), ), // TODO: Add back unredacted when they have MAS, find where new favicon is // .new( // name: "Unredacted", // description: "Unredacted is a 501(c)(3) non-profit organization that builds Internet infrastructure and services to help people evade censorship and protect their right to privacy.", // url: .https("unredacted.org", "services/si/matrix"), - // iconUrl: "https://unredacted.org/favicon.ico", + // icon: Image.network("https://unredacted.org/favicon.ico"), // ), ].map( (homeserver) => Card( child: ListTile( enabled: !isLoading.value, title: Text(homeserver.name), - leading: Image.network( - homeserver.iconUrl, - errorBuilder: (_, _, _) => SizedBox.shrink(), - height: 32, + leading: SizedBox.square( + dimension: 32, + child: homeserver.icon, ), subtitle: Text(homeserver.description), onTap: isLoading.value diff --git a/lib/widgets/pages/settings_category.dart b/lib/widgets/pages/settings_category.dart index 69513b8..0efa68e 100644 --- a/lib/widgets/pages/settings_category.dart +++ b/lib/widgets/pages/settings_category.dart @@ -8,7 +8,7 @@ import "package:hooks_riverpod/misc.dart"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:nexus/models/settings_category.dart"; import "package:nexus/helpers/extensions/better_when.dart"; -import "package:nexus/widgets/highlight_wrapper.dart"; +import "package:nexus/widgets/common/highlight_wrapper.dart"; import "package:super_sliver_list/super_sliver_list.dart"; class const SettingsCategoryPage( diff --git a/lib/widgets/pages/verify.dart b/lib/widgets/pages/verify.dart index 76bd94d..aa342cd 100644 --- a/lib/widgets/pages/verify.dart +++ b/lib/widgets/pages/verify.dart @@ -1,15 +1,16 @@ import "package:material_ui/material_ui.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/models/client_state.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; -import "package:nexus/widgets/loading.dart"; +import "package:nexus/widgets/common/loading.dart"; import "package:nexus/widgets/pages/settings.dart"; -import "package:nexus/widgets/appbar.dart"; +import "package:nexus/widgets/common/account_switcher.dart"; +import "package:nexus/widgets/common/appbar.dart"; import "package:nexus/helpers/required_validator_helper.dart"; -import "package:nexus/widgets/reset_encryption_sheet.dart"; +import "package:nexus/widgets/encryption/reset_encryption_sheet.dart"; class const VerifyPage({super.key}) extends HookConsumerWidget { @override @@ -18,6 +19,7 @@ class const VerifyPage({super.key}) extends HookConsumerWidget { final isLoading = useState(false); final inputError = useState(null); final formKey = useRef(GlobalKey()); + final verificationState = ref.watch( ClientStateController.provider.select( (state) => state?.verificationState, @@ -25,24 +27,31 @@ class const VerifyPage({super.key}) extends HookConsumerWidget { ); Future verify() async { + if (isLoading.value) return; + + if (formKey.value.currentState?.validate() != true) { + return; + } + isLoading.value = true; try { - if (formKey.value.currentState?.validate() != true) { - return; - } - - inputError.value = await ref + await ref .read(ClientController.provider.notifier) .verify(passphraseController.text); + } catch (error) { + inputError.value = error.toString(); } finally { - isLoading.value = false; + if (context.mounted) { + isLoading.value = false; + } } } return Scaffold( appBar: Appbar( actions: .new([ + const AccountSwitcher(onlyWithOthers: true), IconButton( onPressed: () => showDialog(context: context, builder: (_) => SettingsPage()), @@ -52,7 +61,8 @@ class const VerifyPage({super.key}) extends HookConsumerWidget { ), body: switch (verificationState) { null || VerificationState(stateChecked: false) => const Loading(), - // Nothing to verify with yet, so go straight to setting it up. + + // Nothing to verify yet, so go straight to setup. VerificationState(hasSecretStorage: false) => Dialog( insetPadding: const .symmetric(vertical: 12, horizontal: 32), child: ConstrainedBox( @@ -60,6 +70,7 @@ class const VerifyPage({super.key}) extends HookConsumerWidget { child: const ResetEncryptionSheet(isPage: true), ), ), + _ => AlertDialog( insetPadding: .symmetric(vertical: 12, horizontal: 32), scrollable: true, @@ -71,7 +82,9 @@ class const VerifyPage({super.key}) extends HookConsumerWidget { crossAxisAlignment: .start, children: [ Text( - "Enter your recovery key or passphrase below to unlock encrypted events.\nYour passphrase is usually not the same as your password.", + "Enter your recovery key or passphrase below to " + "unlock encrypted events.\nYour passphrase is usually " + "not the same as your password.", ), SizedBox(height: 12), TextFormField( @@ -94,9 +107,13 @@ class const VerifyPage({super.key}) extends HookConsumerWidget { ), actions: [ TextButton( - onPressed: () => context.showAdaptiveSheet( - (_) => const ResetEncryptionSheet(), - ), + onPressed: isLoading.value + ? null + : () { + context.showAdaptiveSheet( + (_) => const ResetEncryptionSheet(), + ); + }, style: TextButton.styleFrom( foregroundColor: Theme.of(context).colorScheme.error, ), diff --git a/lib/widgets/players/audio.dart b/lib/widgets/players/audio.dart index 3e254b0..f29955b 100644 --- a/lib/widgets/players/audio.dart +++ b/lib/widgets/players/audio.dart @@ -1,9 +1,9 @@ import "dart:async"; +import "package:audioplayers/audioplayers.dart" as audioplayers; import "package:material_ui/material_ui.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; -import "package:media_kit/media_kit.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/helpers/extensions/save_attachment.dart"; import "package:nexus/models/info/audio.dart"; @@ -18,10 +18,9 @@ class const AudioPlayer( }) extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final player = useMemoized( - () => Player(configuration: .new(bufferSize: 128 * 1024 * 1024)), - ); + final player = useMemoized(audioplayers.AudioPlayer.new); final loaded = useState(false); + final unsupported = useState(false); useEffect(() { scheduleMicrotask(() async { @@ -29,37 +28,84 @@ class const AudioPlayer( .read(ClientController.provider.notifier) .downloadMedia(.new(mxc: uri, encrypted: encrypted)); if (!context.mounted) return; - await player.open(Media(audio.path), play: false); + // Keeps the audio loaded after it finishes, so it can be replayed + await player.setReleaseMode(.stop); + try { + // AVFoundation needs the format, since gomuks caches files without an extension + await player.setSource( + audioplayers.DeviceFileSource(audio.path, mimeType: info?.mimeType), + ); + } on Exception catch (_) { + // The platform can't play this format, like Ogg on Apple platforms or MIDI on Linux + if (context.mounted) unsupported.value = true; + return; + } if (context.mounted) loaded.value = true; }); return player.dispose; }, []); - return SizedBox( - height: 60, - child: Card( - color: Theme.of(context).colorScheme.surfaceContainer, - child: Padding( - padding: .symmetric(horizontal: 8), - child: PlayerControls( - player, - loading: !loaded.value, - actions: .new([ - SizedBox(width: 4), - IconButton( - onPressed: () => context.saveAttachment( - ref, - uri, - encrypted: encrypted, - filename: filename, - ), - tooltip: "Download", - icon: Icon(Icons.download), + final state = + useStream( + player.onPlayerStateChanged, + initialData: player.state, + ).data ?? + player.state; + final position = + useStream(player.onPositionChanged, initialData: Duration.zero).data ?? + Duration.zero; + final duration = + useStream(player.onDurationChanged, initialData: Duration.zero).data ?? + Duration.zero; + final playing = state == .playing; + + final downloadButton = IconButton( + onPressed: () => context.saveAttachment( + ref, + uri, + encrypted: encrypted, + filename: filename, + ), + tooltip: "Download", + icon: Icon(Icons.download), + ); + + return Card( + color: Theme.of(context).colorScheme.surfaceContainerHigh, + child: Padding( + padding: .symmetric(horizontal: 8), + child: unsupported.value + ? Row( + children: [ + Padding( + padding: .all(12), + child: Icon( + Icons.music_off, + color: Theme.of(context).colorScheme.error, + ), + ), + Expanded( + child: Text( + "Can't play this audio format", + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.error, + ), + ), + ), + downloadButton, + ], + ) + : PlayerControls( + playing: playing, + position: position, + duration: duration, + onPlayPause: playing ? player.pause : player.resume, + onSeek: player.seek, + loading: !loaded.value, + size: info?.size, + actions: .new([SizedBox(width: 4), downloadButton]), ), - ]), - ), - ), ), ); } diff --git a/lib/widgets/players/player_controls.dart b/lib/widgets/players/player_controls.dart index 6226260..53a8c5b 100644 --- a/lib/widgets/players/player_controls.dart +++ b/lib/widgets/players/player_controls.dart @@ -1,37 +1,25 @@ import "dart:math"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:flutter_hooks/flutter_hooks.dart"; import "package:material_ui/material_ui.dart"; -import "package:media_kit/media_kit.dart"; +import "package:nexus/helpers/extensions/size_to_string.dart"; -/// Play/pause, position and seeking controls for a media_kit [Player]. -class const PlayerControls( - final Player player, { +/// Play/pause, position and seeking controls, for any player. +class const PlayerControls({ + required final bool playing, + required final Duration position, + required final Duration duration, + required final VoidCallback onPlayPause, + required final ValueChanged onSeek, final bool loading = false, + final bool buffering = false, final Color? color, + final int? size, final IList actions = const .empty(), super.key, -}) extends HookWidget { +}) extends StatelessWidget { @override Widget build(BuildContext context) { - final playing = useStream( - player.stream.playing, - initialData: player.state.playing, - ).requireData; - final buffering = useStream( - player.stream.buffering, - initialData: player.state.buffering, - ).requireData; - final position = useStream( - player.stream.position, - initialData: player.state.position, - ).requireData; - final duration = useStream( - player.stream.duration, - initialData: player.state.duration, - ).requireData; - String format(Duration duration) { final minutes = duration.inMinutes .remainder(60) @@ -45,6 +33,8 @@ class const PlayerControls( return "$minutes:$seconds"; } + final sizeSuffix = size == null ? "" : " (${size!.sizeAsString})"; + final textStyle = Theme.of(context).textTheme.bodySmall ?.copyWith(color: color); final max = duration.inMilliseconds <= 0 @@ -57,19 +47,19 @@ class const PlayerControls( child: CircularProgressIndicator(padding: .all(12), color: color), ) : IconButton( - onPressed: player.playOrPause, + onPressed: onPlayPause, color: color, tooltip: playing ? "Pause" : "Play", icon: Icon(playing ? Icons.pause_circle : Icons.play_circle), ); - Slider slider({EdgeInsetsGeometry? padding}) => Slider( + Slider slider({EdgeInsetsGeometry? padding}) => .new( padding: padding, max: max, value: min(position.inMilliseconds.toDouble(), max), onChanged: loading ? null - : (value) => player.seek(.new(milliseconds: value.toInt())), + : (value) => onSeek(.new(milliseconds: value.toInt())), ); return LayoutBuilder( @@ -77,13 +67,14 @@ class const PlayerControls( ? Column( mainAxisSize: .min, children: [ - slider(padding: const .symmetric(horizontal: 12)), + SizedBox(height: 12), + slider(padding: const .symmetric(horizontal: 16)), Row( children: [ playButton, Expanded( child: Text( - "${format(position)} / ${format(duration)}", + "${format(position)} / ${format(duration)}$sizeSuffix", style: textStyle, maxLines: 1, overflow: .ellipsis, @@ -94,15 +85,17 @@ class const PlayerControls( ), ], ) - : Row( - children: [ - playButton, - SizedBox(width: 8), - Text(format(position), style: textStyle), - Expanded(child: slider()), - Text(format(duration), style: textStyle), - ...actions, - ], + : IntrinsicHeight( + child: Row( + children: [ + playButton, + SizedBox(width: 8), + Text(format(position), style: textStyle), + Expanded(child: slider()), + Text("${format(duration)}$sizeSuffix", style: textStyle), + ...actions, + ], + ), ), ); } diff --git a/lib/widgets/players/video.dart b/lib/widgets/players/video.dart index ef56024..053041a 100644 --- a/lib/widgets/players/video.dart +++ b/lib/widgets/players/video.dart @@ -1,13 +1,14 @@ import "dart:async"; +import "package:better_player/better_player.dart"; import "package:material_ui/material_ui.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/helpers/extensions/save_attachment.dart"; +import "package:mime/mime.dart"; import "package:nexus/models/info/video.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; import "package:flutter_hooks/flutter_hooks.dart"; -import "package:media_kit/media_kit.dart"; -import "package:media_kit_video/media_kit_video.dart"; import "package:nexus/widgets/players/player_controls.dart"; class const VideoPlayer( @@ -19,51 +20,91 @@ class const VideoPlayer( }) extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final player = useMemoized( - () => Player(configuration: .new(bufferSize: 128 * 1024 * 1024)), - ); - final controller = useMemoized(() => VideoController(player)); - final loaded = useState(false); - - useEffect(() { - scheduleMicrotask(() async { - final video = await ref - .read(ClientController.provider.notifier) - .downloadMedia(.new(mxc: uri, encrypted: encrypted)); - if (!context.mounted) return; - await player.open(Media(video.path), play: false); - if (context.mounted) loaded.value = true; - }); - - return player.dispose; - }, []); - final aspectRatio = switch (info) { VideoInfo(:final width?, :final height?) when width > 0 && height > 0 => width / height, _ => 16 / 9, }; - return ConstrainedBox( - constraints: const .new(maxHeight: 300), - child: AspectRatio( - aspectRatio: aspectRatio, - child: ClipRRect( - borderRadius: .circular(12), - child: Video( - controller: controller, - controls: (_) => - // Until media_kit moves to material_ui, this Material is needed. - Material( + final loaded = useState(false); + final controller = useMemoized( + () => BetterPlayerController( + PlayerConfiguration( + aspectRatio: aspectRatio, + fit: .contain, + controlsConfiguration: PlayerControlsConfiguration( + playerTheme: .custom, + customControlsBuilder: (controller, _) => HookBuilder( + builder: (context) { + final isLoaded = useValueListenable(loaded); + final value = useState(controller.videoPlayerValue); + useEffect(() { + void listener() => value.value = controller.videoPlayerValue; + controller.addVideoListener(listener); + return () => controller.removeVideoListener(listener); + }, [controller]); + + final playing = value.value?.isPlaying ?? false; + final ready = isLoaded && (value.value?.initialized ?? false); + final error = value.value?.errorDescription; + + // better_player doesn't use material_ui, so this Material is needed. + return Material( type: .transparency, child: Stack( children: [ Positioned.fill( child: GestureDetector( behavior: .opaque, - onTap: loaded.value ? player.playOrPause : null, + onTap: ready + ? playing + ? controller.pause + : controller.play + : null, ), ), + if (error != null) + Positioned.fill( + child: ColoredBox( + color: Colors.black54, + child: Center( + child: Column( + mainAxisSize: .min, + children: [ + Padding( + padding: .all(12), + child: Icon( + Icons.videocam_off, + color: Theme.of(context) + .colorScheme + .error, + ), + ), + Flexible( + child: Text( + "Can't play this video", + style: Theme.of(context) + .textTheme + .bodySmall + ?.copyWith( + color: Theme.of(context) + .colorScheme + .error, + ), + ), + ), + TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => ErrorDialog(error, null), + ), + child: Text("Show Error"), + ), + ], + ), + ), + ), + ), Positioned( top: 4, right: 4, @@ -82,55 +123,94 @@ class const VideoPlayer( icon: Icon(Icons.download), ), ), - Positioned( - left: 0, - right: 0, - bottom: 0, - child: DecoratedBox( - decoration: const BoxDecoration( - gradient: LinearGradient( - begin: .bottomCenter, - end: .topCenter, - colors: [Colors.black54, Colors.transparent], + if (error == null) + Positioned( + left: 0, + right: 0, + bottom: 0, + child: DecoratedBox( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: .bottomCenter, + end: .topCenter, + colors: [Colors.black54, Colors.transparent], + ), ), - ), - child: Padding( - padding: const .only(left: 4, right: 4, top: 16), - child: PlayerControls( - player, - loading: !loaded.value, - color: Colors.white, - actions: .new([ - Builder( - builder: (context) { - final fullscreen = isFullscreen(context); - - return IconButton( - onPressed: () => - toggleFullscreen(context), - color: Colors.white, - tooltip: fullscreen - ? "Exit fullscreen" - : "Fullscreen", - icon: Icon( - fullscreen - ? Icons.fullscreen_exit - : Icons.fullscreen, - ), - ); - }, - ), - ]), + child: Padding( + padding: const .only(left: 4, right: 4, top: 16), + child: PlayerControls( + playing: playing, + buffering: value.value?.isBuffering ?? false, + position: value.value?.position ?? .zero, + duration: value.value?.duration ?? .zero, + onPlayPause: playing + ? controller.pause + : controller.play, + onSeek: controller.seekTo, + loading: !ready, + size: info?.size, + color: Colors.white, + actions: .new([ + IconButton( + onPressed: controller.toggleFullScreen, + color: Colors.white, + tooltip: controller.isFullScreen + ? "Exit fullscreen" + : "Fullscreen", + icon: Icon( + controller.isFullScreen + ? Icons.fullscreen_exit + : Icons.fullscreen, + ), + ), + ]), + ), ), ), ), - ), ], ), - ), + ); + }, + ), ), ), ), ); + + useEffect(() { + scheduleMicrotask(() async { + final video = await ref + .read(ClientController.provider.notifier) + .downloadMedia(.new(mxc: uri, encrypted: encrypted)); + if (!context.mounted) return; + await controller.setupDataSource( + .file( + video.path, + videoExtension: switch (info?.mimeType) { + final mimeType? => extensionFromMime(mimeType), + null => null, + }, + ), + ); + // better_player's mpv backend (Linux and Windows) starts playing as + // soon as it loads a file, despite autoPlay being off + await controller.pause(); + if (context.mounted) loaded.value = true; + }); + + return null; + }, []); + + return ConstrainedBox( + constraints: const .new(maxHeight: 300), + child: AspectRatio( + aspectRatio: aspectRatio, + child: ClipRRect( + borderRadius: .circular(12), + child: BetterPlayer(controller: controller), + ), + ), + ); } } diff --git a/lib/widgets/popover_layout.dart b/lib/widgets/popover_layout.dart deleted file mode 100644 index 0ef8ebe..0000000 --- a/lib/widgets/popover_layout.dart +++ /dev/null @@ -1,33 +0,0 @@ -import "dart:math"; - -import "package:material_ui/material_ui.dart"; - -/// Positions a popover below [anchor], or above it if there isn't room below, -/// keeping it fully on screen. -class const PopoverLayout(final Rect anchor) extends SingleChildLayoutDelegate { - static const margin = 8.0; - - @override - BoxConstraints getConstraintsForChild(BoxConstraints constraints) => - constraints.loosen().deflate(const .all(margin)); - - @override - Offset getPositionForChild(Size size, Size childSize) { - final fitsBelow = anchor.bottom + childSize.height + margin <= size.height; - - return .new( - anchor.left.clamp( - margin, - max(margin, size.width - childSize.width - margin), - ), - (fitsBelow ? anchor.bottom : anchor.top - childSize.height).clamp( - margin, - max(margin, size.height - childSize.height - margin), - ), - ); - } - - @override - bool shouldRelayout(PopoverLayout oldDelegate) => - oldDelegate.anchor != anchor; -} diff --git a/lib/widgets/reaction_row.dart b/lib/widgets/reaction_row.dart deleted file mode 100644 index 0b90781..0000000 --- a/lib/widgets/reaction_row.dart +++ /dev/null @@ -1,112 +0,0 @@ -import "package:material_ui/material_ui.dart"; -import "package:flutter_hooks/flutter_hooks.dart"; -import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:nexus/controllers/client_state.dart"; -import "package:nexus/controllers/reactions.dart"; -import "package:nexus/controllers/room_chat.dart"; -import "package:nexus/helpers/mxc_image.dart"; -import "package:nexus/models/event.dart"; -import "package:nexus/widgets/error_dialog.dart"; -import "package:nexus/main.dart"; -import "package:fast_immutable_collections/fast_immutable_collections.dart"; - -class const ReactionRow(final Event event, {super.key}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final clientState = ref.watch(ClientStateController.provider); - - return Padding( - padding: .only(top: 4), - child: switch (ref.watch( - ReactionsController.provider( - .new(roomId: event.roomId, eventRowId: event.rowId), - ), - )) { - AsyncData(value: final IMap>? reactors) || - AsyncLoading(value: final reactors) => Wrap( - spacing: 4, - runSpacing: 4, - children: event.reactions - .where((_, value) => value != 0) - .mapTo( - (reaction, count) => HookBuilder( - builder: (context) { - final enabled = useState(true); - - final selected = - reactors?[reaction]?.contains(clientState!.userId) ?? - false; - return Tooltip( - message: reactors?[reaction]?.join(", ") ?? "", - child: ChoiceChip( - showCheckmark: false, - selected: selected, - label: Row( - mainAxisSize: .min, - spacing: 8, - children: [ - Flexible( - child: reaction.startsWith("mxc://") - ? Image( - height: 20, - image: MxcImage( - ref, - .new(mxc: Uri.parse(reaction)), - ), - errorBuilder: (context, _, _) => Icon( - Icons.broken_image, - color: Theme.of(context) - .colorScheme - .error, - ), - ) - : Text(reaction, overflow: .ellipsis), - ), - Text(count.toString(), overflow: .ellipsis), - ], - ), - onSelected: enabled.value - ? (value) async { - enabled.value = false; - try { - final controller = ref.watch( - RoomChatController.provider(( - roomId: event.roomId, - contextualEvent: null, - )).notifier, - ); - - if (selected) { - await controller - .removeReaction( - reaction, - event, - clientState!.userId!, - ) - .onError(showError); - } else { - await controller - .sendReaction(reaction, event) - .onError(showError); - } - } finally { - enabled.value = true; - } - } - : null, - ), - ); - }, - ), - ) - .toList(), - ), - - AsyncError(:final error, :final stackTrace) => ErrorDialog( - error, - stackTrace, - ), - }, - ); - } -} diff --git a/lib/widgets/reactions/reaction_key.dart b/lib/widgets/reactions/reaction_key.dart new file mode 100644 index 0000000..ca00602 --- /dev/null +++ b/lib/widgets/reactions/reaction_key.dart @@ -0,0 +1,25 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/helpers/mxc_image.dart"; + +/// A reaction's key, either an emoji or a custom (mxc) image. +class const ReactionKey( + final String reaction, { + required final double height, + final TextStyle? style, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) => + reaction.startsWith("mxc://") + ? Image( + height: height, + image: MxcImage(ref, .new(mxc: Uri.parse(reaction))), + errorBuilder: (context, _, _) => Icon( + Icons.broken_image, + size: height, + color: Theme.of(context).colorScheme.error, + ), + ) + : Text(reaction, style: style, overflow: .ellipsis); +} diff --git a/lib/widgets/reactions/reaction_row.dart b/lib/widgets/reactions/reaction_row.dart new file mode 100644 index 0000000..c8bae95 --- /dev/null +++ b/lib/widgets/reactions/reaction_row.dart @@ -0,0 +1,120 @@ +import "package:flutter/gestures.dart"; +import "package:material_ui/material_ui.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/client_state.dart"; +import "package:nexus/controllers/reactions.dart"; +import "package:nexus/controllers/room_chat.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/models/event.dart"; +import "package:nexus/models/reaction_group.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/widgets/reactions/reaction_key.dart"; +import "package:nexus/widgets/reactions/reactions_popover.dart"; +import "package:nexus/main.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; + +class const ReactionRow(final Event event, {super.key}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final clientState = ref.watch(ClientStateController.provider); + + return Padding( + padding: .only(top: 4), + child: switch (ref.watch( + ReactionsController.provider( + .new(roomId: event.roomId, eventRowId: event.rowId), + ), + )) { + AsyncData(value: final IMap? reactors) || + AsyncLoading(value: final reactors) => Wrap( + spacing: 4, + runSpacing: 4, + children: event.reactions + .where((_, value) => value != 0) + .mapTo( + (reaction, count) => HookBuilder( + builder: (context) { + final enabled = useState(true); + + final selected = + reactors?[reaction]?.senders.contains( + clientState!.userId, + ) ?? + false; + void showReactions(PositionedGestureDetails details) => + context.showAdaptivePopover( + (_) => ReactionsPopover( + event, + initialReaction: reaction, + ), + anchor: context.globalRectAt(details.globalPosition), + ); + + return GestureDetector( + onSecondaryTapUp: showReactions, + onLongPressStart: showReactions, + child: Tooltip( + // Long press opens the reactions popover instead + triggerMode: .manual, + message: reactors?[reaction]?.shortcode ?? reaction, + child: ChoiceChip( + showCheckmark: false, + selected: selected, + label: Row( + mainAxisSize: .min, + spacing: 8, + children: [ + Flexible( + child: ReactionKey(reaction, height: 20), + ), + Text(count.toString(), overflow: .ellipsis), + ], + ), + onSelected: enabled.value + ? (value) async { + enabled.value = false; + try { + final controller = ref.watch( + RoomChatController.provider(( + roomId: event.roomId, + contextualEvent: null, + threadRoot: null, + )).notifier, + ); + + if (selected) { + await controller + .removeReaction( + reaction, + event, + clientState!.userId!, + ) + .onError(showError); + } else { + await controller + .sendReaction(reaction, event) + .onError(showError); + } + } finally { + enabled.value = true; + } + } + : null, + ), + ), + ); + }, + ), + ) + .toList(), + ), + + AsyncError(:final error, :final stackTrace) => ErrorDialog( + error, + stackTrace, + ), + }, + ); + } +} diff --git a/lib/widgets/reactions/reactions_popover.dart b/lib/widgets/reactions/reactions_popover.dart new file mode 100644 index 0000000..44c455b --- /dev/null +++ b/lib/widgets/reactions/reactions_popover.dart @@ -0,0 +1,144 @@ +import "dart:math"; + +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/reactions.dart"; +import "package:nexus/controllers/user.dart"; +import "package:nexus/helpers/extensions/better_when.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/helpers/extensions/show_user_popover.dart"; +import "package:nexus/models/event.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/helpers/extensions/show_image_viewer.dart"; +import "package:nexus/widgets/reactions/reaction_key.dart"; + +/// Every reaction to an event in tabs, each listing who reacted with it. +class const ReactionsPopover( + final Event event, { + final String? initialReaction, + super.key, +}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final reactions = ref.watch( + ReactionsController.provider( + .new(roomId: event.roomId, eventRowId: event.rowId), + ), + ); + // Ordered like the reaction row on the timeline + final order = event.reactions.keys.toIList(); + final keys = + reactions.value?.keys.toIList().sortOrdered( + (a, b) => order.indexOf(a).compareTo(order.indexOf(b)), + ) ?? + const .empty(); + + final vsync = useSingleTickerProvider(keys: [keys.length]); + final tabController = useMemoized( + () => TabController( + length: keys.length, + initialIndex: keys + .indexOf(initialReaction ?? "") + .clamp(0, max(0, keys.length - 1)), + vsync: vsync, + ), + [keys.length], + ); + useEffect(() => tabController.dispose, [tabController]); + useListenable(tabController); + + return reactions.betterWhen( + skipLoadingOnReload: true, + data: (reactions) { + if (keys.isEmpty) return SizedBox.shrink(); + + final reaction = keys[tabController.index]; + + return Column( + mainAxisSize: .min, + crossAxisAlignment: .stretch, + children: [ + TabBar( + controller: tabController, + isScrollable: true, + tabAlignment: .start, + tabs: keys.map((reaction) { + void expand() => context.showImageViewer( + ref, + .new(mxc: Uri.parse(reaction)), + downloadFilename: reaction.split("/").last, + ); + final isImage = reaction.startsWith("mxc://"); + + return GestureDetector( + onSecondaryTap: isImage ? expand : null, + onLongPress: isImage ? expand : null, + child: Tab( + child: Row( + mainAxisSize: .min, + spacing: 8, + children: [ + ReactionKey(reaction, height: 20), + Text(reactions[reaction]!.senders.length.toString()), + ], + ), + ), + ); + }).toList(), + ), + Flexible( + child: AnimatedSize( + duration: Durations.medium2, + curve: Curves.easeInOutCubicEmphasized, + alignment: .topCenter, + child: SingleChildScrollView( + key: ValueKey(reaction), + padding: .symmetric(vertical: 8), + child: Column( + crossAxisAlignment: .stretch, + children: reactions[reaction]!.senders + .map( + (userId) => Consumer( + builder: (context, ref, _) { + final member = ref + .watch( + UserController.provider( + .new( + roomId: event.roomId, + userId: userId, + ), + ), + ) + .value; + final name = + member?.displayName ?? userId.localpart; + + return ListTile( + leading: AvatarOrHash( + member?.avatarUrl, + name, + dimension: 40, + ), + title: Text(name, overflow: .ellipsis), + subtitle: Text(userId, overflow: .ellipsis), + onTap: () => context.showUserPopover( + userId, + roomId: event.roomId, + ), + ); + }, + ), + ) + .toList(), + ), + ), + ), + ), + ], + ); + }, + ); + } +} diff --git a/lib/widgets/read_receipts_row.dart b/lib/widgets/read_receipts/read_receipts_row.dart similarity index 93% rename from lib/widgets/read_receipts_row.dart rename to lib/widgets/read_receipts/read_receipts_row.dart index e3f206f..156d3f8 100644 --- a/lib/widgets/read_receipts_row.dart +++ b/lib/widgets/read_receipts/read_receipts_row.dart @@ -1,14 +1,16 @@ +import "dart:math"; + import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/read_receipts.dart"; import "package:nexus/controllers/room_chat.dart"; import "package:nexus/controllers/user.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; import "package:nexus/helpers/extensions/show_user_popover.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; -import "package:nexus/widgets/avatar_ring.dart"; -import "package:nexus/widgets/read_receipts_sheet.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/avatars/avatar_ring.dart"; +import "package:nexus/widgets/read_receipts/read_receipts_sheet.dart"; class const ReadReceiptsRow( final String eventId, { @@ -44,7 +46,7 @@ class const ReadReceiptsRow( // If they don't all fit, the last spot shows how many more there are final shown = receipts.length <= fits ? receipts.length - : fits - 1; + : max(0, fits - 1); return Align( alignment: .centerRight, diff --git a/lib/widgets/read_receipts_sheet.dart b/lib/widgets/read_receipts/read_receipts_sheet.dart similarity index 93% rename from lib/widgets/read_receipts_sheet.dart rename to lib/widgets/read_receipts/read_receipts_sheet.dart index aabdfb3..3021102 100644 --- a/lib/widgets/read_receipts_sheet.dart +++ b/lib/widgets/read_receipts/read_receipts_sheet.dart @@ -1,12 +1,12 @@ import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/read_receipts.dart"; import "package:nexus/controllers/room_chat.dart"; import "package:nexus/controllers/user.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/show_user_popover.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; -import "package:nexus/widgets/sheet_layout.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; /// Everyone who has read up to an event, kept up to date while open. class const ReadReceiptsSheet( diff --git a/lib/widgets/renderers/diffs/change_line.dart b/lib/widgets/renderers/diffs/change_line.dart new file mode 100644 index 0000000..7195882 --- /dev/null +++ b/lib/widgets/renderers/diffs/change_line.dart @@ -0,0 +1,72 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:material_ui/material_ui.dart"; + +/// A line of what a state event changed, like a room's old name, struck +/// through, then its new one. +class const ChangeLine({ + /// What changed, e.g. `Denied`, in bold before the items. + final String? label, + final IList removed = const .empty(), + final IList added = const .empty(), + required final Color removedColor, + required final Color addedColor, + + /// Whether to quote the items, like server names, but not whole sentences. + final bool quoted = true, + + /// Shown after the items, like a change that isn't one of them. + final List trailing = const [], + + /// How many removed and how many added items to show, as some events, like + /// a room's first server ACL, can change hundreds. + final int maxShown = 5, + + /// The most lines each item can take, as some, like topics, can be long. + final int maxLines = 2, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final style = theme.textTheme.labelMedium; + + Iterable items( + IList items, { + required Color color, + required bool struck, + }) => [ + ...items + .take(maxShown) + .map( + (item) => Text( + quoted ? "\"$item\"" : item, + maxLines: maxLines, + overflow: .ellipsis, + style: style?.copyWith( + color: color, + decoration: struck ? .lineThrough : null, + decorationColor: color, + ), + ), + ), + if (items.length > maxShown) + Text( + "+${items.length - maxShown} more", + style: style?.copyWith(color: theme.colorScheme.onSurfaceVariant), + ), + ]; + + return Wrap( + spacing: 8, + runSpacing: 2, + crossAxisAlignment: .center, + children: [ + if (label case final label?) + Text(label, style: style?.copyWith(fontWeight: .bold)), + ...items(removed, color: removedColor, struck: true), + ...items(added, color: addedColor, struck: false), + ...trailing, + ], + ); + } +} diff --git a/lib/widgets/renderers/diffs/join_rules_diff.dart b/lib/widgets/renderers/diffs/join_rules_diff.dart new file mode 100644 index 0000000..1698aa0 --- /dev/null +++ b/lib/widgets/renderers/diffs/join_rules_diff.dart @@ -0,0 +1,72 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/join_rule_name.dart"; +import "package:nexus/helpers/extensions/success_scheme.dart"; +import "package:nexus/models/content/join_rules.dart"; +import "package:nexus/widgets/renderers/diffs/change_line.dart"; + +/// The join rule a join rules event changed to, and for restricted rooms, the +/// rooms whose members it let join, or stopped letting join. +class const JoinRulesDiff( + final JoinRulesContent content, { + final JoinRulesContent? previous, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final theme = Theme.of(context); + final removedColor = theme.colorScheme.error; + final addedColor = theme.successScheme.primary; + + ISet roomIdsOf(JoinRulesContent? content) => + (content?.allow ?? const ISet.empty()) + .map((condition) => condition.roomId) + .nonNulls + .toISet(); + final before = roomIdsOf(previous); + final after = roomIdsOf(content); + final removed = before.difference(after); + final added = after.difference(before); + + // Rooms the user isn't in are shown by ID + final names = ref.watch( + RoomsController.provider.select( + (rooms) => IMap.fromEntries( + removed + .addAll(added) + .map( + (roomId) => + MapEntry(roomId, rooms[roomId]?.metadata?.name ?? roomId), + ), + ), + ), + ); + IList named(ISet roomIds) => + roomIds.map((roomId) => names[roomId] ?? roomId).toIList(); + + return Column( + crossAxisAlignment: .start, + spacing: 2, + children: [ + if (previous?.joinRule != content.joinRule) + ChangeLine( + removed: [?previous?.joinRule.displayName].lock, + added: [content.joinRule.displayName].lock, + removedColor: removedColor, + addedColor: addedColor, + quoted: false, + ), + if (removed.isNotEmpty || added.isNotEmpty) + ChangeLine( + label: "Members of", + removed: named(removed), + added: named(added), + removedColor: removedColor, + addedColor: addedColor, + ), + ], + ); + } +} diff --git a/lib/widgets/renderers/diffs/pinned_events_diff.dart b/lib/widgets/renderers/diffs/pinned_events_diff.dart new file mode 100644 index 0000000..41bd3a1 --- /dev/null +++ b/lib/widgets/renderers/diffs/pinned_events_diff.dart @@ -0,0 +1,116 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/event.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/hooks/chat_scroll.dart"; +import "package:nexus/helpers/extensions/success_scheme.dart"; +import "package:nexus/models/content/message.dart"; +import "package:nexus/widgets/lazy_loading/message_displayname.dart"; +import "package:nexus/widgets/renderers/event.dart"; + +/// A line for each message a pinned events event pinned, in green, and each one +/// it unpinned, in red and struck through. +class const PinnedEventsDiff( + final String roomId, { + required final IList pinned, + required final IList unpinned, + + /// If set, tapping a message jumps to it. + final JumpToEvent? jumpToEvent, + super.key, +}) extends ConsumerWidget { + static const maxShown = 5; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final theme = Theme.of(context); + final style = theme.textTheme.labelMedium; + final changes = [ + ...pinned.map((eventId) => (eventId, unpinned: false)), + ...unpinned.map((eventId) => (eventId, unpinned: true)), + ]; + + return Column( + crossAxisAlignment: .start, + spacing: 2, + children: [ + ...changes.take(maxShown).map((change) { + final color = change.unpinned + ? theme.colorScheme.error + : theme.successScheme.primary; + final decoration = change.unpinned + ? TextDecoration.lineThrough + : null; + + return DefaultTextStyle.merge( + style: style?.copyWith( + color: color, + decoration: decoration, + decorationColor: color, + ), + child: switch (ref.watch( + EventController.provider( + .new(roomId: roomId, eventId: change.$1), + ), + )) { + // Keeps showing the event while it reloads + AsyncValue(value: final rowId?) => InkWell( + borderRadius: .circular(4), + hoverColor: color.withValues(alpha: 0.12), + onTap: jumpToEvent == null ? null : () => jumpToEvent!(rowId), + child: Row( + mainAxisSize: .min, + children: [ + // Other events already say who sent them + if (ref.watch( + RoomsController.provider.select( + (rooms) => rooms[roomId]?.events[rowId], + ), + ) + case final event? + when event.content is MessageContent) ...[ + MessageDisplayname( + event, + clickable: false, + shouldWrap: false, + style: .new( + color: color, + fontWeight: .bold, + decoration: decoration, + decorationColor: color, + ), + ), + Text(": "), + ], + Flexible( + child: IgnorePointer( + child: EventRenderer( + rowId, + roomId: roomId, + textOnly: true, + maxLines: 1, + ), + ), + ), + ], + ), + ), + AsyncLoading() => SizedBox.square( + dimension: 12, + child: CircularProgressIndicator(strokeWidth: 2, color: color), + ), + // Like if it was deleted, or the server won't share it + _ => Text("Message not found"), + }, + ); + }), + if (changes.length > maxShown) + Text( + "+${changes.length - maxShown} more", + style: style?.copyWith(color: theme.colorScheme.onSurfaceVariant), + ), + ], + ); + } +} diff --git a/lib/widgets/renderers/diffs/power_levels_diff.dart b/lib/widgets/renderers/diffs/power_levels_diff.dart new file mode 100644 index 0000000..f90c917 --- /dev/null +++ b/lib/widgets/renderers/diffs/power_levels_diff.dart @@ -0,0 +1,141 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/user.dart"; +import "package:nexus/helpers/extensions/displayname_color.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/helpers/extensions/success_scheme.dart"; +import "package:nexus/models/content/power_levels.dart"; +import "package:nexus/models/power_level_permission.dart"; + +/// Whose power levels, and which permissions' levels, a power levels event +/// changed, in green when raised, and red when lowered. +class const PowerLevelsDiff( + final String roomId, + final PowerLevelsContent content, { + final PowerLevelsContent? previous, + super.key, +}) extends ConsumerWidget { + static const maxShown = 5; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final theme = Theme.of(context); + final style = theme.textTheme.labelMedium; + final before = previous ?? PowerLevelsContent(); + + Text levels(int? from, int? to, {int? fromLevel, int? toLevel}) => Text( + "${from ?? "Default"} → ${to ?? "Default"}", + style: style?.copyWith( + color: switch ((fromLevel ?? from, toLevel ?? to)) { + (final from?, final to?) when to > from => + theme.successScheme.primary, + (final from?, final to?) when to < from => theme.colorScheme.error, + _ => theme.colorScheme.onSurfaceVariant, + }, + ), + ); + + Iterable capped(Iterable lines) { + final list = lines.toList(); + return [ + ...list.take(maxShown), + if (list.length > maxShown) + Text( + "+${list.length - maxShown} more", + style: style?.copyWith(color: theme.colorScheme.onSurfaceVariant), + ), + ]; + } + + final users = before.users.keys + .toISet() + .addAll(content.users.keys) + .map( + (userId) => ( + userId, + from: before.users[userId], + to: content.users[userId], + fromLevel: before.users[userId] ?? before.usersDefault, + toLevel: content.users[userId] ?? content.usersDefault, + ), + ) + .where((change) => change.from != change.to) + // The most powerful first + .toIList() + .sort((a, b) => b.toLevel.compareTo(a.toLevel)); + + final permissions = <(String, int?, int?)>[ + ...PowerLevelPermission.values.map( + (permission) => ( + permission.title, + permission.levelIn(before), + permission.levelIn(content), + ), + ), + ...before.events.keys + .toISet() + .addAll(content.events.keys) + .map( + (type) => ( + PowerLevelEvent.of(type)?.title ?? type, + before.events[type], + content.events[type], + ), + ), + ].where((permission) => permission.$2 != permission.$3); + + return Column( + crossAxisAlignment: .start, + spacing: 2, + children: [ + ...capped( + users.map( + (change) => Wrap( + spacing: 8, + crossAxisAlignment: .center, + children: [ + Text( + ref + .watch( + UserController.provider( + .new(roomId: roomId, userId: change.$1), + ), + ) + .value + ?.displayName ?? + change.$1.localpart, + style: style?.copyWith( + fontWeight: .bold, + color: ref.displaynameColorAt( + change.$1, + change.toLevel.toDouble(), + ), + ), + ), + levels( + change.from, + change.to, + fromLevel: change.fromLevel, + toLevel: change.toLevel, + ), + ], + ), + ), + ), + ...capped( + permissions.map( + (permission) => Wrap( + spacing: 8, + crossAxisAlignment: .center, + children: [ + Text(permission.$1, style: style?.copyWith(fontWeight: .bold)), + levels(permission.$2, permission.$3), + ], + ), + ), + ), + ], + ); + } +} diff --git a/lib/widgets/renderers/diffs/server_acl_diff.dart b/lib/widgets/renderers/diffs/server_acl_diff.dart new file mode 100644 index 0000000..9364c04 --- /dev/null +++ b/lib/widgets/renderers/diffs/server_acl_diff.dart @@ -0,0 +1,76 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/helpers/extensions/success_scheme.dart"; +import "package:nexus/models/content/server_acl.dart"; +import "package:nexus/widgets/renderers/diffs/change_line.dart"; + +/// The servers newly denied (in red) and allowed (in green) by a server ACL +/// event, and those no longer denied or allowed, struck through. +class const ServerAclDiff( + final ServerACLContent content, { + final ServerACLContent? previous, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + final ipLiteralsAllowed = switch (previous) { + final previous? + when previous.allowIpLiterals != content.allowIpLiterals => + content.allowIpLiterals == true, + _ => null, + }; + + Widget? listDiff( + String label, + Color color, + IList before, + IList after, { + required bool ipLiterals, + }) { + // Sets, as an ACL can list hundreds of servers + final beforeSet = before.toISet(); + final afterSet = after.toISet(); + final removed = before.where((server) => !afterSet.contains(server)); + final added = after.where((server) => !beforeSet.contains(server)); + if (removed.isEmpty && added.isEmpty && !ipLiterals) return null; + + return ChangeLine( + label: label, + removed: .new(removed), + added: .new(added), + removedColor: color, + addedColor: color, + trailing: [ + if (ipLiterals) + Text( + "servers using IP addresses", + style: theme.textTheme.labelMedium?.copyWith(color: color), + ), + ], + ); + } + + return Column( + crossAxisAlignment: .start, + spacing: 2, + children: [ + ?listDiff( + "Denied", + theme.colorScheme.error, + previous?.deny ?? const .empty(), + content.deny, + ipLiterals: ipLiteralsAllowed == false, + ), + ?listDiff( + "Allowed", + theme.successScheme.primary, + previous?.allow ?? const .empty(), + content.allow, + ipLiterals: ipLiteralsAllowed == true, + ), + ], + ); + } +} diff --git a/lib/widgets/renderers/event.dart b/lib/widgets/renderers/event.dart index 47750fa..228abf6 100644 --- a/lib/widgets/renderers/event.dart +++ b/lib/widgets/renderers/event.dart @@ -3,34 +3,50 @@ import "package:flutter/gestures.dart"; import "package:material_ui/material_ui.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/event.dart"; +import "package:nexus/controllers/poll_votes.dart"; import "package:nexus/controllers/room_chat.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/settings.dart"; import "package:nexus/helpers/extensions/is_shown_as_message.dart"; -import "package:nexus/helpers/extensions/show_adaptive_menu.dart"; +import "package:nexus/helpers/extensions/send_failed.dart"; +import "package:nexus/helpers/extensions/success_scheme.dart"; import "package:nexus/helpers/hooks/chat_scroll.dart"; +import "package:nexus/helpers/hooks/tap_recognizer.dart"; +import "package:nexus/helpers/extensions/open_link_info.dart"; +import "package:nexus/main.dart"; import "package:nexus/models/content/avatar.dart"; import "package:nexus/models/content/canonical_alias.dart"; import "package:nexus/models/content/content.dart"; import "package:nexus/models/content/create.dart"; +import "package:nexus/models/content/encryption.dart"; import "package:nexus/models/content/history_visibility.dart"; import "package:nexus/models/content/join_rules.dart"; import "package:nexus/models/content/membership.dart"; +import "package:nexus/models/content/name.dart"; import "package:nexus/models/content/pinned_events.dart"; +import "package:nexus/models/content/poll_end.dart"; import "package:nexus/models/content/power_levels.dart"; import "package:nexus/models/content/server_acl.dart"; +import "package:nexus/models/content/tombstone.dart"; import "package:nexus/models/content/topic.dart"; import "package:nexus/models/event.dart"; -import "package:nexus/widgets/error_dialog.dart"; -import "package:nexus/widgets/lazy_loading/message_displayname.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; import "package:nexus/widgets/renderers/message.dart"; -import "package:nexus/widgets/reaction_row.dart"; -import "package:nexus/widgets/read_receipts_row.dart"; +import "package:nexus/widgets/reactions/reaction_row.dart"; +import "package:nexus/widgets/read_receipts/read_receipts_row.dart"; import "package:nexus/widgets/renderers/membership.dart"; +import "package:nexus/widgets/renderers/diffs/change_line.dart"; import "package:nexus/widgets/renderers/generic_event.dart"; -import "package:nexus/widgets/swipe_to_reply.dart"; -import "package:nexus/widgets/timestamp.dart"; +import "package:nexus/widgets/renderers/diffs/join_rules_diff.dart"; +import "package:nexus/widgets/renderers/diffs/power_levels_diff.dart"; +import "package:nexus/widgets/renderers/diffs/pinned_events_diff.dart"; +import "package:nexus/widgets/renderers/diffs/server_acl_diff.dart"; +import "package:nexus/widgets/renderers/swipe_to_reply.dart"; +import "package:nexus/widgets/threads/thread_summary.dart"; +import "package:nexus/widgets/common/timestamp.dart"; +import "package:nexus/widgets/users/user_span.dart"; class const EventRenderer( final int eventRowId, { @@ -39,6 +55,7 @@ class const EventRenderer( final bool textOnly = false, final int? maxLines, final JumpToEvent? jumpToEvent, + final void Function(String threadRoot)? onOpenThread, final IList Function(Event event)? getEventOptions, /// If set, events can be swiped, calling this @@ -47,6 +64,10 @@ class const EventRenderer( /// If set, shows who in this chat has read up to this event, e.g. in the /// timeline. final ChatParams? readReceiptsChat, + + /// The root of the thread this is shown in, if any, to set it apart from the + /// replies. + final String? threadRoot, super.key, }) extends HookConsumerWidget { @override @@ -56,6 +77,7 @@ class const EventRenderer( final errorStyle = TextStyle(color: colorScheme.error); final focusNode = useFocusNode(); useListenable(focusNode); + final senderRecognizer = useTapRecognizer(); final (event, previousEvent) = ref.watch( RoomsController.provider.select((rooms) { @@ -82,51 +104,93 @@ class const EventRenderer( if (event == null) return SizedBox.shrink(); - final hideMembershipEvents = (ref + final (hideMembershipEvents, hideServerAclEvents) = ref .watch(SettingsController.provider) .maybeWhen( - orElse: () => false, - data: (settings) => settings.hideMembershipEvents, - )); + orElse: () => (false, true), + data: (settings) => + (settings.hideMembershipEvents, settings.hideServerAclEvents), + ); - // Knocks and their outcomes stay visible, as moderators need to act on them - if (hideMembershipEvents && - event.content is MembershipContent && - ![event.content, event.previousContent].any( - (content) => content is MembershipContent && content.status == .knock, - )) { - return SizedBox.shrink(); - } + final isHidden = + // Knocks and their outcomes stay visible, as moderators need to act + // on them + (hideMembershipEvents && + event.content is MembershipContent && + ![event.content, event.previousContent].any( + (content) => + content is MembershipContent && content.status == .knock, + )) || + (hideServerAclEvents && event.content is ServerACLContent); + if (isHidden && !textOnly) return SizedBox.shrink(); + + final isThreadRoot = threadRoot != null && event.eventId == threadRoot; final isGrouped = + (threadRoot == null || previousEvent?.eventId != threadRoot) && (previousEvent?.isShownAsMessage ?? false) && event.sender == previousEvent?.sender && event.pmp?.id == previousEvent?.pmp?.id; - GenericEventRenderer generic(IconData icon, String text) => - .new(icon, maxLines: maxLines, [ - WidgetSpan( - alignment: .middle, - child: MessageDisplayname(event, shouldWrap: maxLines == null), - ), - TextSpan(text: text), - ]); + // For what a state event changed, from and to + final removedColor = colorScheme.error; + final addedColor = theme.successScheme.primary; - final child = event.isShownAsMessage + GenericEventRenderer generic( + IconData icon, + String text, { + List details = const [], + }) => .new( + icon, + maxLines: maxLines, + details: details, + trailing: Timestamp(event.timestamp), + [ + UserSpan.sender(context, ref, event, recognizer: senderRecognizer), + TextSpan(text: text), + ], + ); + + // For rooms an upgrade links, i.e. the old and new rooms + Widget roomLink(String label, String linkedRoomId) => InkWell( + onTap: () => ref + .openLinkInfo(context, ( + identifier: linkedRoomId, + eventId: null, + // The sender is in both rooms, so their server can be joined + // through + via: [event.sender.substring(event.sender.indexOf(":") + 1)].lock, + )) + .onError(showError), + child: Text( + label, + style: theme.textTheme.labelMedium?.copyWith( + color: colorScheme.primary, + decoration: .underline, + decorationColor: colorScheme.primary, + ), + ), + ); + + final child = + event.isShownAsMessage || (isThreadRoot && event.redactedBy != null) ? MessageRenderer( event, onTapReply: jumpToEvent == null ? null : () async { - final replyEvent = await ref.read( + final replyRowId = await ref.read( EventController.provider( .new(roomId: roomId, eventId: event.replyTo!), ).future, ); - if (replyEvent != null) { - await jumpToEvent!(replyEvent.rowId); + if (replyRowId != null) { + await jumpToEvent!(replyRowId); } }, + onTapThread: onOpenThread == null + ? null + : () => onOpenThread!(event.eventId), isGrouped: isGrouped, maxLines: maxLines, textOnly: textOnly, @@ -136,9 +200,11 @@ class const EventRenderer( : switch (event.content) { Content(:final parseError?, :final stackTrace) => Row( children: [ - ErrorDialog( - "An error occurred while parsing event ${event.eventId}:\n$parseError", - stackTrace, + Flexible( + child: ErrorDialog( + "An error occurred while parsing event ${event.eventId}:\n$parseError", + stackTrace, + ), ), ], ), @@ -155,19 +221,99 @@ class const EventRenderer( Icons.interests, "changed the room avatar", ), - CreateContent() => generic(Icons.add, "created the room"), - PowerLevelsContent() => generic( + CreateContent(:final predecessor) => generic( + Icons.add, + predecessor == null + ? "created the room" + : "created the room, replacing an older one", + details: [ + if (predecessor case PreviousRoom(:final roomId)) + roomLink("Go to old room", roomId), + ], + ), + TombstoneContent(:final body, :final replacementRoom) => generic( + Icons.upgrade, + "replaced the room", + details: [ + if (body.isNotEmpty) + Text(body, style: theme.textTheme.labelMedium), + roomLink("Go to new room", replacementRoom), + ], + ), + PollEndContent() => switch (event.relatesTo) { + final pollId? => switch (ref + .watch( + EventController.provider( + .new(roomId: roomId, eventId: pollId), + ), + ) + .value) { + final pollRowId? + when ref + .watch( + PollVotesController.provider( + .new(roomId: roomId, eventRowId: pollRowId), + ), + ) + .value + ?.endEventId == + event.eventId => + generic(Icons.poll, "ended a poll"), + _ => null, + }, + null => null, + }, + final PowerLevelsContent content => generic( Icons.power, "changed the room's power levels", + details: [ + PowerLevelsDiff( + roomId, + content, + previous: switch (event.previousContent) { + final PowerLevelsContent previous => previous, + _ => null, + }, + ), + ], ), - JoinRulesContent() => generic( + final JoinRulesContent content => generic( Icons.rule, "changed the room's join rules", + details: [ + JoinRulesDiff( + content, + previous: switch (event.previousContent) { + final JoinRulesContent previous => previous, + _ => null, + }, + ), + ], ), - TopicContent() => generic( - Icons.description, - "updated the room topic", - ), + TopicContent(:final topic) => () { + final previous = switch (event.previousContent) { + TopicContent(:final topic) when topic.isNotEmpty => topic, + _ => null, + }; + + return generic( + Icons.description, + topic.isEmpty + ? "removed the room topic" + : previous == null + ? "set the room topic" + : "changed the room topic", + details: [ + ChangeLine( + removed: [?previous].lock, + added: [if (topic.isNotEmpty) topic].lock, + removedColor: removedColor, + addedColor: addedColor, + quoted: false, + ), + ], + ); + }(), HistoryVisibilityContent(:final historyVisibility) => generic( Icons.history, "changed the room's history visibility to ${switch (historyVisibility) { @@ -175,42 +321,116 @@ class const EventRenderer( .joined => "since joined", .shared => "all history visible (shared)", .worldReadable => "all history visible (world readable)", + .unknown => "something Nexus doesn't know about", }}", ), - PinnedEventsContent() => generic( - Icons.push_pin, - "pinned/unpinned some events", - ), - ServerACLContent() => generic( + PinnedEventsContent(:final pinnedEvents) => () { + final before = switch (event.previousContent) { + PinnedEventsContent(:final pinnedEvents) => pinnedEvents, + _ => const IList.empty(), + }; + final pinned = pinnedEvents + .where((id) => !before.contains(id)) + .toIList(); + final unpinned = before + .where((id) => !pinnedEvents.contains(id)) + .toIList(); + + return generic( + Icons.push_pin, + switch ((pinned.length, unpinned.length)) { + (1, 0) => "pinned a message", + (0, 1) => "unpinned a message", + _ => "changed the pinned messages", + }, + details: [ + PinnedEventsDiff( + roomId, + pinned: pinned, + unpinned: unpinned, + jumpToEvent: jumpToEvent, + ), + ], + ); + }(), + final ServerACLContent content => generic( Icons.list, "updated the server ban list", + details: [ + ServerAclDiff( + content, + previous: switch (event.previousContent) { + final ServerACLContent previous => previous, + _ => null, + }, + ), + ], ), - CanonicalAliasContent(:final alias, :final altAliases) => generic( - Icons.numbers, - switch ([ - if (event.previousContent case CanonicalAliasContent( - alias: final prevAlias, - altAliases: final prevAltAliases, - )) ...[ - if (prevAlias != alias) - if (alias == null) - "removed the room's canonical alias" - else - "changed the room's canonical alias to $alias", + CanonicalAliasContent(:final alias, :final altAliases) => () { + final previous = switch (event.previousContent) { + final CanonicalAliasContent previous => previous, + _ => null, + }; + final previousAltAliases = + previous?.altAliases ?? const ISet.empty(); - if (prevAltAliases - .remove(alias ?? "") - .remove(prevAlias ?? "") != - altAliases.remove(alias ?? "").remove(prevAlias ?? "")) - "changed the room's aliases", - ] else ...[ - if (alias != null) "set the room's canonical alias", - if (altAliases.isNotEmpty) "set the room's aliases", + return generic( + Icons.numbers, + previous == null + ? "set the room's aliases" + : "changed the room's aliases", + details: [ + if (previous?.alias != alias) + ChangeLine( + label: "Canonical alias", + removed: [?previous?.alias].lock, + added: [?alias].lock, + removedColor: removedColor, + addedColor: addedColor, + ), + if (previousAltAliases != altAliases) + ChangeLine( + label: "Aliases", + removed: previousAltAliases + .difference(altAliases) + .toIList(), + added: altAliases + .difference(previousAltAliases) + .toIList(), + removedColor: removedColor, + addedColor: addedColor, + ), ], - ]) { - [] => "did something related to room aliases", - List prev => prev.join(" and "), - }, + ); + }(), + NameContent(:final name) => () { + final previous = switch (event.previousContent) { + NameContent(:final name) when name.isNotEmpty => name, + _ => null, + }; + + return generic( + Icons.title, + name.isEmpty + ? "removed the room name" + : previous == null + ? "set the room name" + : "changed the room name", + details: [ + ChangeLine( + removed: [?previous].lock, + added: [if (name.isNotEmpty) name].lock, + removedColor: removedColor, + addedColor: addedColor, + ), + ], + ); + }(), + EncryptionContent() => generic( + Icons.lock, + event.previousContent is EncryptionContent + ? "changed the room's encryption settings" + : "enabled encryption", ), _ => null, }; @@ -222,6 +442,15 @@ class const EventRenderer( globalPosition: details.globalPosition, ); + final threadSummary = switch (onOpenThread) { + final onOpenThread? when !textOnly && child is! MessageRenderer => + ThreadSummary(event, onTap: () => onOpenThread(event.eventId)), + _ => null, + }; + final belowIndent = child is MessageRenderer + ? 4.0 + : 8 + GenericEventRenderer.textIndent(context); + return Column( crossAxisAlignment: .start, children: [ @@ -270,7 +499,8 @@ class const EventRenderer( crossAxisAlignment: .center, children: [ child, - if (child is! MessageRenderer) + if (child is! MessageRenderer && + child is! GenericEventRenderer) Timestamp(event.timestamp), ], ), @@ -283,21 +513,24 @@ class const EventRenderer( ...[ if (child is! MessageRenderer) ReactionRow(event), + ?threadSummary, // Outside the message itself, so it doesn't move when swiped if (readReceiptsChat case final chat? when event.isShownAsMessage) ReadReceiptsRow(event.eventId, chat: chat), - if (event.sendError != null && event.sendError != "not sent") + if (event.sendFailed) Padding( padding: .only(bottom: 4), child: Row( spacing: 4, children: [ - Text( - event.sendError!, - style: theme.textTheme.labelSmall?.copyWith( - color: theme.colorScheme.error, + Flexible( + child: Text( + event.sendError!, + style: theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.error, + ), ), ), InkWell( @@ -314,6 +547,7 @@ class const EventRenderer( RoomChatController.provider(( roomId: roomId, contextualEvent: null, + threadRoot: null, )).notifier, ) .hideClientSticky(event.rowId), @@ -321,10 +555,22 @@ class const EventRenderer( ], ), ), - ].map((child) => Padding(padding: .only(left: 4), child: child)), + ].map( + (child) => Padding( + padding: .only(left: belowIndent), + child: child, + ), + ), ] else if (textOnly) - Text("Unknown event type", style: errorStyle), + Text( + event.redactedBy == null ? "Unknown event type" : "Redacted event", + style: errorStyle, + ) + else if (threadSummary != null) + Padding(padding: .only(left: 4), child: threadSummary), + + if (isThreadRoot && !textOnly) Divider(height: 16), ], ); } diff --git a/lib/widgets/renderers/event_preview.dart b/lib/widgets/renderers/event_preview.dart new file mode 100644 index 0000000..53e10ac --- /dev/null +++ b/lib/widgets/renderers/event_preview.dart @@ -0,0 +1,52 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/is_shown_as_message.dart"; +import "package:nexus/widgets/lazy_loading/message_avatar.dart"; +import "package:nexus/widgets/lazy_loading/message_displayname.dart"; +import "package:nexus/widgets/renderers/event.dart"; + +class const EventPreview( + final int rowId, { + required final String roomId, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final event = ref.watch( + RoomsController.provider.select((rooms) => rooms[roomId]?.events[rowId]), + ); + if (event == null) return SizedBox.shrink(); + + final showSender = event.hasMessageContent; + + return IgnorePointer( + child: Padding( + padding: .symmetric(vertical: 4), + child: Row( + mainAxisSize: .min, + spacing: 8, + children: [ + if (showSender) MessageAvatar(event, height: 36), + + Flexible( + child: Column( + mainAxisAlignment: .center, + crossAxisAlignment: .start, + children: [ + if (showSender) MessageDisplayname(event, shouldWrap: false), + EventRenderer( + rowId, + roomId: roomId, + textOnly: true, + maxLines: 1, + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/file_card.dart b/lib/widgets/renderers/file_card.dart similarity index 100% rename from lib/widgets/file_card.dart rename to lib/widgets/renderers/file_card.dart diff --git a/lib/widgets/renderers/generic_event.dart b/lib/widgets/renderers/generic_event.dart index 101913c..100643b 100644 --- a/lib/widgets/renderers/generic_event.dart +++ b/lib/widgets/renderers/generic_event.dart @@ -5,33 +5,79 @@ class const GenericEventRenderer( final IconData icon, final List children, { final int? maxLines, + + /// Shown at the end of the text, like the event's timestamp. + final Widget? trailing, + + /// Shown under the text, like what changed in a state event. + final List details = const [], super.key, }) extends StatelessWidget { + static const _iconPadding = 4.0; + static const _spacing = 8.0; + + /// How far the text is from the start, past the icon, so what's shown under + /// the event can line up with it. + static double textIndent(BuildContext context) => + (IconTheme.of(context).size ?? 24) + _iconPadding * 2 + _spacing; + @override - Widget build(BuildContext context) => Padding( - padding: .symmetric(vertical: 4), - child: Row( - spacing: 8, - mainAxisSize: .min, - children: [ - Padding(padding: .symmetric(horizontal: 4), child: Icon(icon)), - Flexible( - child: Text.rich( - TextSpan( - children: children - .expandIndexed( - (index, child) => [ - if (index > 0) TextSpan(text: " "), - child, - ], - ) - .toList(), - ), - maxLines: maxLines ?? 999, - overflow: .ellipsis, + Widget build(BuildContext context) { + // Only previewing the event, so it should stay short + final previewing = maxLines != null; + final iconSize = IconTheme.of(context).size ?? 24; + + return Padding( + padding: .symmetric(vertical: 4), + child: Row( + spacing: _spacing, + mainAxisSize: .min, + // At the top, by the text, rather than the middle of any details + crossAxisAlignment: .start, + children: [ + Padding( + padding: .symmetric(horizontal: _iconPadding), + child: Icon(icon), ), - ), - ], - ), - ); + Flexible( + child: Column( + mainAxisSize: .min, + crossAxisAlignment: .start, + spacing: 4, + children: [ + // At least as tall as the icon, so they're centered together + ConstrainedBox( + constraints: .new(minHeight: iconSize), + child: Row( + spacing: 8, + mainAxisSize: .min, + children: [ + Flexible( + child: Text.rich( + TextSpan( + children: children + .expandIndexed( + (index, child) => [ + if (index > 0) TextSpan(text: " "), + child, + ], + ) + .toList(), + ), + maxLines: maxLines ?? 999, + overflow: .ellipsis, + ), + ), + if (!previewing) ?trailing, + ], + ), + ), + if (!previewing) ...details, + ], + ), + ), + ], + ), + ); + } } diff --git a/lib/widgets/renderers/membership.dart b/lib/widgets/renderers/membership.dart index b1811f0..125ea64 100644 --- a/lib/widgets/renderers/membership.dart +++ b/lib/widgets/renderers/membership.dart @@ -1,24 +1,27 @@ +import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:nexus/helpers/extensions/displayname_color.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; -import "package:nexus/helpers/extensions/show_user_popover.dart"; -import "package:nexus/helpers/extensions/string_to_color.dart"; +import "package:nexus/helpers/hooks/tap_recognizer.dart"; import "package:nexus/models/content/membership.dart"; import "package:nexus/models/event.dart"; -import "package:nexus/widgets/lazy_loading/message_displayname.dart"; import "package:nexus/widgets/renderers/generic_event.dart"; +import "package:nexus/widgets/users/user_span.dart"; class const MembershipRenderer( final Event event, { final int? maxLines, super.key, -}) extends StatelessWidget { +}) extends HookConsumerWidget { @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { assert( event.content is MembershipContent, "Make sure to only pass membership events to MembershipRenderer", ); + final targetRecognizer = useTapRecognizer(); + final senderRecognizer = useTapRecognizer(); final previous = switch (event.previousContent) { MembershipContent(:final status) => status, _ => null, @@ -29,19 +32,15 @@ class const MembershipRenderer( Icons.people, maxLines: maxLines, [ - WidgetSpan( - alignment: .middle, - child: InkWell( - onTap: () => context.showUserPopover( - event.stateKey!, - roomId: event.roomId, - ), - child: Text( - overflow: .ellipsis, - content.displayName ?? event.stateKey!.localpart, - maxLines: 1, - style: .new(color: event.sender.colorHash, fontWeight: .bold), - ), + UserSpan( + context, + content.displayName ?? event.stateKey!.localpart, + userId: event.stateKey!, + roomId: event.roomId, + recognizer: targetRecognizer, + style: .new( + color: ref.displaynameColor(event.roomId, event.stateKey!), + fontWeight: .bold, ), ), TextSpan( @@ -53,13 +52,11 @@ class const MembershipRenderer( .leave => event.sender == event.stateKey ? "left" : (previous == .ban ? "was unbanned from" : "was kicked from"), .ban => "was banned from", .knock => "asked to join", + .unknown => "changed their membership in", }} the room${event.sender == event.stateKey ? "" : " by"}", ), if (event.sender != event.stateKey) - WidgetSpan( - alignment: .middle, - child: MessageDisplayname(event, shouldWrap: maxLines == null), - ), + UserSpan.sender(context, ref, event, recognizer: senderRecognizer), if (content.reason != null) TextSpan(text: "for \"${content.reason}\""), ], diff --git a/lib/widgets/renderers/message.dart b/lib/widgets/renderers/message.dart index 598e9f9..655fc0d 100644 --- a/lib/widgets/renderers/message.dart +++ b/lib/widgets/renderers/message.dart @@ -5,27 +5,36 @@ import "package:linkify/linkify.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/controllers/event.dart"; import "package:nexus/helpers/extensions/get_filename.dart"; +import "package:nexus/helpers/extensions/linkify_html.dart"; import "package:nexus/models/content/encrypted.dart"; import "package:nexus/models/content/message.dart"; +import "package:nexus/models/location.dart"; +import "package:nexus/models/content/poll_start.dart"; import "package:nexus/models/content/sticker.dart"; import "package:nexus/models/event.dart"; -import "package:nexus/widgets/file_card.dart"; import "package:nexus/widgets/html/html.dart"; import "package:nexus/widgets/lazy_loading/message_avatar.dart"; import "package:nexus/widgets/lazy_loading/message_displayname.dart"; -import "package:nexus/widgets/linkified_text.dart"; -import "package:nexus/widgets/loading.dart"; -import "package:nexus/widgets/message_image.dart"; -import "package:nexus/widgets/reaction_row.dart"; -import "package:nexus/widgets/timestamp.dart"; -import "package:nexus/widgets/url_preview.dart"; -import "package:nexus/widgets/event_preview.dart"; -import "package:nexus/widgets/players/video.dart"; -import "package:nexus/widgets/players/audio.dart"; +import "package:nexus/widgets/common/linkified_text.dart"; +import "package:nexus/widgets/location/location_message.dart"; +import "package:nexus/widgets/common/loading.dart"; +import "package:nexus/widgets/renderers/message_image.dart"; +import "package:nexus/widgets/reactions/reaction_row.dart"; +import "package:nexus/widgets/common/timestamp.dart"; +import "package:nexus/widgets/renderers/url_preview.dart"; +import "package:nexus/widgets/renderers/event_preview.dart"; +import "package:nexus/widgets/renderers/message_media.dart"; +import "package:nexus/helpers/extensions/is_media.dart"; +import "package:nexus/widgets/renderers/poll.dart"; +import "package:nexus/widgets/threads/thread_summary.dart"; class const MessageRenderer( final Event event, { final VoidCallback? onTapReply, + + /// If set, thread roots show a summary of their thread, calling this when + /// tapped. + final VoidCallback? onTapThread, final bool textOnly = false, final bool isGrouped = false, final int? maxLines, @@ -45,6 +54,10 @@ class const MessageRenderer( ); final rendered = switch (event.content) { + _ when event.redactedBy != null => Text( + "Redacted event", + style: errorStyle, + ), EncryptedContent() => Text("Unable to decrypt event", style: errorStyle), StickerContent(:final body, :final url, :final info) => textOnly @@ -53,9 +66,26 @@ class const MessageRenderer( constraints: .loose(.square(200)), child: MessageImage(url, info: info, encrypted: false), ), - // TODO: Handle locations - // LocationMessageContent(:final body , :final geoUri) => + PollStartContent(:final poll) => + textOnly + ? Text( + "Poll: ${poll.question}", + maxLines: maxLines, + overflow: .ellipsis, + ) + : PollRenderer(event, poll), MessageContent content => switch (content) { + final LocationMessageContent location => + textOnly + ? Text( + switch (location.description) { + final description? => "Location: $description", + null => "Location", + }, + maxLines: maxLines, + overflow: .ellipsis, + ) + : LocationMessage(location), TextMessageContent(:final body, :final formattedBody, :final format) || NoticeMessageContent( :final body, @@ -73,92 +103,31 @@ class const MessageRenderer( ) => Column( crossAxisAlignment: .start, children: [ - format == .html && !textOnly + textOnly + ? Text( + body.isEmpty ? content.filename ?? "" : body, + style: textStyle, + maxLines: maxLines, + overflow: maxLines == null ? null : .ellipsis, + ) + : format == .html && formattedBody != null ? Html( roomId: event.roomId, textStyle: textStyle, - formattedBody!.replaceAllMapped( - RegExp( - r"(]*>.*?<\/a>)|(\bhttps?:\/\/[^\s<]+)", - caseSensitive: false, - dotAll: true, - ), - (m) { - // If it's already an tag, leave it unchanged - if (m.group(1) != null) { - return m.group(1)!; - } - - // Otherwise, wrap the bare URL - final url = m.group(2)!; - return "$url"; - }, - ), + formattedBody.linkifiedHtml, ) : LinkifiedText( body.isEmpty ? content.filename ?? "" : body, + roomId: event.roomId, style: textStyle, maxLines: maxLines, ), if (!textOnly) ...[ - if (event.content - case ImageMessageContent(:final url) || - FileMessageContent(:final url) || - VideoMessageContent(:final url) || - AudioMessageContent(:final url)) + if (content.isMedia) ConstrainedBox( constraints: .loose(.square(500)), - child: switch (event.content) { - VideoMessageContent( - :final info, - :final file, - :final filename, - :final body, - ) => - VideoPlayer( - url, - info, - encrypted: file != null, - filename: filename ?? body, - ), - AudioMessageContent( - :final info, - :final file, - :final filename, - :final body, - ) => - AudioPlayer( - url, - info, - encrypted: file != null, - filename: filename ?? body, - ), - FileMessageContent( - :final info, - :final filename, - :final file, - ) => - FileCard( - url, - info, - filename: filename, - encrypted: file != null, - ), - ImageMessageContent( - :final info, - :final file, - :final filename, - :final body, - ) => - MessageImage( - url, - info: info, - encrypted: file != null, - filename: filename ?? body, - ), - _ => SizedBox.shrink(), - }, + child: MessageMedia(content), ), if (event.lastEditRowId != 0) @@ -171,16 +140,21 @@ class const MessageRenderer( ], ], ), - LocationMessageContent(:final String? body) || UnknownMessageContent(:final body) => body == null ? Text("This message is redacted", style: errorStyle) - : Wrap( - spacing: 8, - children: [ - Text("Unknown message type:", style: errorStyle), - Text(body), - ], + : Text.rich( + TextSpan( + children: [ + TextSpan( + text: "Unknown message type: ", + style: errorStyle, + ), + TextSpan(text: body), + ], + ), + maxLines: maxLines, + overflow: maxLines == null ? null : .ellipsis, ), }, _ => throw Exception("This is impossible"), @@ -239,7 +213,10 @@ class const MessageRenderer( child: Padding( padding: .symmetric(vertical: 8, horizontal: 12), child: SizedBox( - height: 48, + // Two lines of text, plus EventPreview's padding + height: + MediaQuery.textScalerOf(context).scale(40) + + 8, child: switch (ref.watch( EventController.provider( .new( @@ -249,9 +226,10 @@ class const MessageRenderer( ), )) { AsyncData(:final value?) || - AsyncLoading( - :final value?, - ) => EventPreview(value), + AsyncLoading(:final value?) => EventPreview( + value, + roomId: event.roomId, + ), AsyncError _ => Text( "An error occurred while fetching the reply", style: errorStyle, @@ -264,6 +242,8 @@ class const MessageRenderer( ), rendered, if (!textOnly) ReactionRow(event), + if (onTapThread case final onTapThread? when !textOnly) + ThreadSummary(event, onTap: onTapThread), ], ), ), diff --git a/lib/widgets/message_image.dart b/lib/widgets/renderers/message_image.dart similarity index 92% rename from lib/widgets/message_image.dart rename to lib/widgets/renderers/message_image.dart index 969dcd3..a8c44e3 100644 --- a/lib/widgets/message_image.dart +++ b/lib/widgets/renderers/message_image.dart @@ -4,8 +4,8 @@ import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/helpers/mxc_image.dart"; import "package:nexus/models/info/image.dart" as i; import "package:nexus/models/requests/download_media.dart"; -import "package:nexus/widgets/expandable_image.dart"; -import "package:nexus/widgets/loading.dart"; +import "package:nexus/widgets/common/expandable_image.dart"; +import "package:nexus/widgets/common/loading.dart"; final class const MessageImage( final Uri url, { @@ -20,6 +20,7 @@ final class const MessageImage( return ExpandableImage( request, downloadFilename: filename, + size: info?.size, child: ClipRRect( borderRadius: .all(.circular(8)), child: AspectRatio( @@ -27,7 +28,7 @@ final class const MessageImage( child: Image( image: MxcImage(ref, request), width: info?.width?.toDouble(), - fit: BoxFit.fitWidth, + fit: .fitWidth, loadingBuilder: (_, child, loadingProgress) => loadingProgress == null ? child diff --git a/lib/widgets/renderers/message_media.dart b/lib/widgets/renderers/message_media.dart new file mode 100644 index 0000000..1f7e6b9 --- /dev/null +++ b/lib/widgets/renderers/message_media.dart @@ -0,0 +1,55 @@ +import "package:material_ui/material_ui.dart"; +import "package:nexus/models/content/message.dart"; +import "package:nexus/widgets/players/audio.dart"; +import "package:nexus/widgets/players/video.dart"; +import "package:nexus/widgets/renderers/file_card.dart"; +import "package:nexus/widgets/renderers/message_image.dart"; + +final class const MessageMedia(final MessageContent content, {super.key}) + extends StatelessWidget { + @override + Widget build(BuildContext context) => switch (content) { + VideoMessageContent( + :final url, + :final info, + :final file, + :final filename, + :final body, + ) => + VideoPlayer( + url, + info, + encrypted: file != null, + filename: filename ?? body, + ), + AudioMessageContent( + :final url, + :final info, + :final file, + :final filename, + :final body, + ) => + AudioPlayer( + url, + info, + encrypted: file != null, + filename: filename ?? body, + ), + FileMessageContent(:final url, :final info, :final filename, :final file) => + FileCard(url, info, filename: filename, encrypted: file != null), + ImageMessageContent( + :final url, + :final info, + :final file, + :final filename, + :final body, + ) => + MessageImage( + url, + info: info, + encrypted: file != null, + filename: filename ?? body, + ), + _ => SizedBox.shrink(), + }; +} diff --git a/lib/widgets/renderers/poll.dart b/lib/widgets/renderers/poll.dart new file mode 100644 index 0000000..1f738b5 --- /dev/null +++ b/lib/widgets/renderers/poll.dart @@ -0,0 +1,221 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:m3e_buttons/m3e_buttons.dart"; +import "package:m3e_card_list/m3e_card_list.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/client_state.dart"; +import "package:nexus/controllers/poll_votes.dart"; +import "package:nexus/controllers/power_level.dart"; +import "package:nexus/controllers/room_chat.dart"; +import "package:nexus/controllers/room_power_levels.dart"; +import "package:nexus/helpers/extensions/event_id_is_fake.dart"; +import "package:nexus/main.dart"; +import "package:nexus/models/content/poll_start.dart"; +import "package:nexus/models/event.dart"; +import "package:nexus/widgets/renderers/poll_option.dart"; + +class const PollRenderer(final Event event, final PollStart poll, {super.key}) + extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + + /// The answer being voted for, or no answer while ending the poll + final pending = useState<({String? answerId})?>(null); + final isEnding = switch (pending.value) { + (answerId: null) => true, + _ => false, + }; + + final votesProvider = PollVotesController.provider( + .new(roomId: event.roomId, eventRowId: event.rowId), + ); + final votesState = ref.watch(votesProvider); + final votes = votesState.value ?? const .new(); + final userId = ref.watch( + ClientStateController.provider.select((value) => value?.userId), + ); + final powerLevels = ref.watch( + RoomPowerLevelsController.provider(event.roomId), + ); + + final isOpen = !event.eventId.isFake && !votes.hasEnded; + final canVote = + isOpen && + votesState.hasValue && + ref.watch( + PowerLevelController.provider( + .new(eventType: .pollResponse, roomId: event.roomId), + ), + ); + final canEnd = + isOpen && + userId != null && + powerLevels.canEndPoll(userId, pollSender: event.sender); + final ownVote = + (userId == null ? null : votes.votes[userId]) ?? const .empty(); + final votersByAnswer = votes.votersByAnswer; + final mostVotes = + votersByAnswer.values.map((voters) => voters.length).maxOrNull ?? 0; + final isSingleChoice = poll.selectionLimit == 1; + + final notifier = RoomChatController.provider(( + roomId: event.roomId, + contextualEvent: null, + threadRoot: null, + )).notifier; + + Future run( + ({String? answerId}) action, + Future Function() send, + ) async { + pending.value = action; + await send().onError(showError); + if (!context.mounted) return; + // Otherwise the old votes show until they're refetched + await ref.read(votesProvider.future).onError((_, _) => const .new()); + if (context.mounted) pending.value = null; + } + + Future toggle(String answerId) { + final picked = ownVote.contains(answerId) + ? ownVote.remove(answerId) + : isSingleChoice + ? IList([answerId]) + : ownVote.add(answerId); + + return run( + (answerId: answerId), + () => ref + .read(notifier) + .votePoll( + event, + // Past the limit, the oldest pick is replaced + picked.length > poll.selectionLimit ? picked.removeAt(0) : picked, + ), + ); + } + + void confirmEnd() => context.showAdaptiveSheet( + (sheetContext) => SheetLayout( + title: const Text("End Poll"), + actions: [ + TextButton( + onPressed: Navigator.of(sheetContext).pop, + child: const Text("Cancel"), + ), + TextButton( + onPressed: () { + Navigator.of(sheetContext).pop(); + run((answerId: null), () => ref.read(notifier).endPoll(event)); + }, + child: const Text("End"), + ), + ], + children: const [ + Text( + "Are you sure you want to end this poll? " + "No one will be able to vote after it ends.", + ), + ], + ), + ); + + final voterCount = votes.voterCount; + + return ConstrainedBox( + constraints: const .new(maxWidth: 400), + child: Column( + crossAxisAlignment: .stretch, + mainAxisSize: .min, + spacing: 12, + children: [ + Column( + crossAxisAlignment: .start, + spacing: 2, + children: [ + Text( + poll.question.isEmpty ? "Untitled poll" : poll.question, + style: theme.textTheme.titleMedium, + ), + Text( + [ + votes.hasEnded + ? "Ended" + : isSingleChoice + ? "Choose one" + : "Choose up to ${poll.selectionLimit}", + "$voterCount ${voterCount == 1 ? "vote" : "votes"}", + ].join(" · "), + style: theme.textTheme.labelMedium?.copyWith( + color: colorScheme.onSurfaceVariant, + ), + ), + ], + ), + if (votesState case AsyncError(:final error)) + Text( + "Failed to load votes: $error", + style: .new(color: colorScheme.error), + ), + if (votes.undecryptable case final count when count > 0) + Row( + spacing: 8, + children: [ + Icon(Icons.lock, size: 16, color: colorScheme.error), + Flexible( + child: Text( + "$count ${count == 1 ? "response" : "responses"} couldn't " + "be decrypted, so the results may be incomplete", + style: theme.textTheme.labelMedium?.copyWith( + color: colorScheme.error, + ), + ), + ), + ], + ), + M3ECardColumn( + color: colorScheme.surface, + outerRadius: 16, + padding: const .symmetric(horizontal: 16, vertical: 12), + onTap: canVote && pending.value == null + ? (index) => toggle(poll.answers[index].id) + : null, + children: poll.answers.map((answer) { + final count = votersByAnswer[answer.id]?.length ?? 0; + + return PollOption( + answer.text, + picked: ownVote.contains(answer.id), + isSingleChoice: isSingleChoice, + share: voterCount == 0 ? 0 : count / voterCount, + isWinner: votes.hasEnded && count > 0 && count == mostVotes, + loading: pending.value?.answerId == answer.id, + ); + }).toList(), + ), + if (canEnd) + Align( + alignment: .centerRight, + child: M3EButton.icon( + style: .tonal, + size: .xs, + onPressed: pending.value == null ? confirmEnd : null, + icon: isEnding + ? const SizedBox.square( + dimension: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.stop_circle), + label: const Text("End Poll"), + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/renderers/poll_option.dart b/lib/widgets/renderers/poll_option.dart new file mode 100644 index 0000000..ff01d4e --- /dev/null +++ b/lib/widgets/renderers/poll_option.dart @@ -0,0 +1,67 @@ +import "package:material_ui/material_ui.dart"; + +class const PollOption( + final String text, { + required final bool picked, + required final bool isSingleChoice, + + /// From 0 to 1 + required final double share, + final bool isWinner = false, + final bool loading = false, + super.key, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final emphasis = isWinner ? const TextStyle(fontWeight: .bold) : null; + + return Column( + crossAxisAlignment: .stretch, + spacing: 10, + children: [ + Row( + spacing: 12, + children: [ + SizedBox.square( + dimension: 20, + child: loading + ? const CircularProgressIndicator(strokeWidth: 2.5) + : Icon( + switch ((isSingleChoice, picked)) { + (true, true) => Icons.radio_button_checked, + (true, false) => Icons.radio_button_unchecked, + (false, true) => Icons.check_box, + (false, false) => Icons.check_box_outline_blank, + }, + size: 20, + color: picked + ? colorScheme.primary + : colorScheme.onSurfaceVariant, + ), + ), + Expanded( + child: Text( + text, + style: theme.textTheme.bodyLarge?.merge(emphasis), + ), + ), + Text( + "${(share * 100).round()}%", + style: theme.textTheme.labelLarge + ?.copyWith(color: colorScheme.onSurfaceVariant) + .merge(emphasis), + ), + ], + ), + TweenAnimationBuilder( + tween: Tween(end: share), + duration: Durations.medium2, + curve: Curves.easeInOut, + builder: (context, value, _) => LinearProgressIndicator(value: value), + ), + ], + ); + } +} diff --git a/lib/widgets/swipe_to_reply.dart b/lib/widgets/renderers/swipe_to_reply.dart similarity index 100% rename from lib/widgets/swipe_to_reply.dart rename to lib/widgets/renderers/swipe_to_reply.dart diff --git a/lib/widgets/url_preview.dart b/lib/widgets/renderers/url_preview.dart similarity index 100% rename from lib/widgets/url_preview.dart rename to lib/widgets/renderers/url_preview.dart diff --git a/lib/widgets/room_chat/banned_warning_dialog.dart b/lib/widgets/room_chat/banned_warning_dialog.dart new file mode 100644 index 0000000..5beeaae --- /dev/null +++ b/lib/widgets/room_chat/banned_warning_dialog.dart @@ -0,0 +1,21 @@ +import "package:material_ui/material_ui.dart"; + +class const BannedWarningDialog({super.key}) extends StatelessWidget { + @override + Widget build(BuildContext context) => AlertDialog( + title: Text("View Banned Members?"), + content: Text( + "Banned members may have offensive or abusive display names and avatars.", + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text("Cancel"), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text("Continue and don't show again"), + ), + ], + ); +} diff --git a/lib/widgets/room_chat/chat_body.dart b/lib/widgets/room_chat/chat_body.dart new file mode 100644 index 0000000..3b5f752 --- /dev/null +++ b/lib/widgets/room_chat/chat_body.dart @@ -0,0 +1,163 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:measure_size/measure_size.dart"; +import "package:nexus/controllers/power_level.dart"; +import "package:nexus/controllers/room_chat.dart"; +import "package:nexus/controllers/settings.dart"; +import "package:nexus/controllers/tombstone.dart"; +import "package:nexus/helpers/hooks/chat_composer.dart"; +import "package:nexus/helpers/hooks/chat_scroll.dart"; +import "package:nexus/main.dart"; +import "package:nexus/models/event.dart"; +import "package:nexus/widgets/composer/composer.dart"; +import "package:nexus/widgets/composer/typing_indicator.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/widgets/common/loading.dart"; +import "package:nexus/widgets/room_chat/chat_timeline.dart"; +import "package:nexus/widgets/room_chat/tombstone_banner.dart"; + +final class const ChatBody({ + required final ChatParams chat, + required final ChatScroll scroll, + required final JumpToEvent jumpToEvent, + required final IList Function(Event event) getEventOptions, + required final ChatComposer composer, + final void Function(String threadRoot)? onOpenThread, + super.key, +}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final roomId = chat.roomId; + final repliedEventRowId = composer.repliedEventRowId; + + final composerSize = useState(64); + final typingIndicatorSize = useState(0); + + final controllerProvider = RoomChatController.provider(chat); + final notifier = ref.watch(controllerProvider.notifier); + final controllerData = ref.watch(controllerProvider); + + final swipeToReply = ref.watch( + SettingsController.provider.select( + (settings) => settings.value?.swipeToReply ?? false, + ), + ); + final tombstone = ref.watch(TombstoneController.provider(roomId)); + final canReply = + tombstone == null && + ref.watch( + PowerLevelController.provider( + .new(eventType: .message, roomId: roomId), + ), + ); + + return Stack( + children: [ + Positioned.fill( + child: Padding( + padding: .symmetric(horizontal: 4), + child: switch (controllerData) { + AsyncLoading(value: _?) || AsyncData(value: _) => ChatTimeline( + scroll: scroll, + jumpToEvent: jumpToEvent, + chat: chat, + getEventOptions: getEventOptions, + onSwipe: swipeToReply && canReply + ? (rowId) => composer.relate(rowId, .reply) + : null, + onOpenThread: onOpenThread, + composerHeight: composerSize.value, + typingIndicatorHeight: typingIndicatorSize.value, + ), + AsyncLoading _ => Loading(), + AsyncError(:final error, :final stackTrace) => ErrorDialog( + error, + stackTrace, + ), + }, + ), + ), + AnimatedPositioned( + duration: Durations.short4, + bottom: composerSize.value, + left: 12, + // Leaves room for the jump to bottom button when it's shown + right: scroll.atBottom ? 12 : 72, + child: MeasureSize( + onChange: (size) => typingIndicatorSize.value = size.height, + child: TypingIndicator(roomId), + ), + ), + Positioned( + right: 16, + bottom: composerSize.value, + child: IgnorePointer( + ignoring: scroll.atBottom, + child: AnimatedOpacity( + opacity: scroll.atBottom ? 0 : 1, + duration: Durations.short4, + child: FloatingActionButton.small( + onPressed: scroll.jumpToBottom, + child: const Icon(Icons.keyboard_arrow_down), + ), + ), + ), + ), + Positioned( + bottom: 0, + left: 0, + right: 0, + child: MeasureSize( + onChange: (size) => composerSize.value = size.height, + child: switch (tombstone) { + final tombstone? => TombstoneBanner(tombstone), + null => Composer( + roomId, + threadRoot: chat.threadRoot, + node: composer.node, + onSend: (text, {required shouldMention, required tags}) => + notifier + .send( + text, + tags: tags, + relationType: composer.relationType, + shouldMention: shouldMention, + relatedEventRowId: composer.relatedEvent, + ) + .onError(showError), + onSendSticker: (shortcode, image, {required shouldMention}) => + notifier + .sendSticker( + shortcode, + image, + shouldMention: shouldMention, + repliedEventRowId: repliedEventRowId, + ) + .onError(showError), + onSendPoll: (poll, {required shouldMention}) => notifier + .sendPoll( + poll, + shouldMention: shouldMention, + repliedEventRowId: repliedEventRowId, + ) + .onError(showError), + onSendLocation: (location, {required shouldMention}) => notifier + .sendLocation( + location, + shouldMention: shouldMention, + repliedEventRowId: repliedEventRowId, + ) + .onError(showError), + onSendBotCommand: (draft) => notifier + .sendBotCommand(draft, repliedEventRowId: repliedEventRowId) + .onError(showError), + ), + }, + ), + ), + ], + ); + } +} diff --git a/lib/widgets/room_chat/chat_timeline.dart b/lib/widgets/room_chat/chat_timeline.dart index c949344..d6aaef7 100644 --- a/lib/widgets/room_chat/chat_timeline.dart +++ b/lib/widgets/room_chat/chat_timeline.dart @@ -4,7 +4,7 @@ import "package:nexus/controllers/room_chat.dart"; import "package:nexus/helpers/hooks/chat_scroll.dart"; import "package:nexus/models/event.dart"; import "package:nexus/widgets/renderers/event.dart"; -import "package:nexus/widgets/highlight_wrapper.dart"; +import "package:nexus/widgets/common/highlight_wrapper.dart"; import "package:super_sliver_list/super_sliver_list.dart"; class const ChatTimeline({ @@ -12,12 +12,12 @@ class const ChatTimeline({ required final ChatScroll scroll, required final JumpToEvent jumpToEvent, required final IList Function(Event) getEventOptions, - required final int? highlightedEvent, required final double composerHeight, /// The typing indicator's height, or zero while it's hidden. required final double typingIndicatorHeight, final void Function(int rowId)? onSwipe, + final void Function(String threadRoot)? onOpenThread, super.key, }) extends StatelessWidget { Widget eventRow( @@ -25,63 +25,72 @@ class const ChatTimeline({ int? previousEventRowId, { required Key key, }) => HighlightWrapper( - EventRenderer( - eventRowId, - previousEventRowId: previousEventRowId, - roomId: chat.roomId, - jumpToEvent: jumpToEvent, - getEventOptions: getEventOptions, - onSwipe: onSwipe == null ? null : () => onSwipe!(eventRowId), - readReceiptsChat: chat, + // To work around an AWFUL SuperSliverList bug + ConstrainedBox( + constraints: const BoxConstraints(minHeight: 0.01), + child: EventRenderer( + eventRowId, + previousEventRowId: previousEventRowId, + roomId: chat.roomId, + jumpToEvent: jumpToEvent, + onOpenThread: onOpenThread, + getEventOptions: getEventOptions, + onSwipe: onSwipe == null ? null : () => onSwipe!(eventRowId), + readReceiptsChat: chat, + threadRoot: chat.threadRoot, + ), ), key: key, - isHighlighted: highlightedEvent == eventRowId, + isHighlighted: scroll.highlightedEvent == eventRowId, ); @override - Widget build(BuildContext context) => CustomScrollView( - reverse: true, - center: scroll.centerKey, - keyboardDismissBehavior: .onDrag, - controller: scroll.scrollController, - slivers: [ - SliverToBoxAdapter( - child: Column( - children: [ - // Makes room for the typing indicator, with a small gap above it, - // so it doesn't cover messages - AnimatedContainer( - duration: Durations.medium2, - curve: Curves.easeInOutCubicEmphasized, - height: typingIndicatorHeight == 0 - ? 0 - : typingIndicatorHeight + 4, + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) => TweenAnimationBuilder( + // Makes room for the typing indicator, with a small gap above it, so it + // doesn't cover messages + tween: Tween( + end: typingIndicatorHeight == 0 ? 0.0 : typingIndicatorHeight + 4, + ), + duration: Durations.medium2, + curve: Curves.easeInOutCubicEmphasized, + builder: (context, typingIndicatorGap, _) { + final bottomPadding = composerHeight + typingIndicatorGap; + + return CustomScrollView( + reverse: true, + center: scroll.centerKey, + // Offset 0 is the newest event above the padding, so short + // timelines can't be scrolled past either end + anchor: (bottomPadding / constraints.maxHeight).clamp(0, 1), + keyboardDismissBehavior: .onDrag, + controller: scroll.scrollController, + slivers: [ + SliverToBoxAdapter(child: SizedBox(height: bottomPadding)), + + SuperSliverList.builder( + itemCount: scroll.liveRows.length, + itemBuilder: (_, index) => eventRow( + scroll.liveRows[index], + index > 0 + ? scroll.liveRows.getOrNull(index - 1) + : scroll.historyRows.firstOrNull, + key: scroll.keyFor(scroll.liveRows[index]), + ), + ), + + SuperSliverList.builder( + key: scroll.centerKey, + itemCount: scroll.historyRows.length, + itemBuilder: (_, index) => eventRow( + scroll.historyRows[index], + scroll.historyRows.getOrNull(index + 1), + key: scroll.keyFor(scroll.historyRows[index]), + ), ), - SizedBox(height: composerHeight), ], - ), - ), - - SuperSliverList.builder( - itemCount: scroll.liveRows.length, - itemBuilder: (_, index) => eventRow( - scroll.liveRows[index], - index > 0 - ? scroll.liveRows.getOrNull(index - 1) - : scroll.historyRows.firstOrNull, - key: scroll.keyFor(scroll.liveRows[index]), - ), - ), - - SuperSliverList.builder( - key: scroll.centerKey, - itemCount: scroll.historyRows.length, - itemBuilder: (_, index) => eventRow( - scroll.historyRows[index], - scroll.historyRows.getOrNull(index + 1), - key: scroll.keyFor(scroll.historyRows[index]), - ), - ), - ], + ); + }, + ), ); } diff --git a/lib/widgets/member_list.dart b/lib/widgets/room_chat/member_list.dart similarity index 61% rename from lib/widgets/member_list.dart rename to lib/widgets/room_chat/member_list.dart index 731270d..a967075 100644 --- a/lib/widgets/member_list.dart +++ b/lib/widgets/room_chat/member_list.dart @@ -4,17 +4,19 @@ import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:m3e_buttons/m3e_buttons.dart"; import "package:m3e_card_list/m3e_card_list.dart"; +import "package:nexus/controllers/banned_warning_dismissed.dart"; import "package:nexus/controllers/members_by_status.dart"; import "package:nexus/controllers/members_grouped.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/show_user_popover.dart"; -import "package:nexus/helpers/extensions/string_to_color.dart"; +import "package:nexus/helpers/extensions/displayname_color.dart"; import "package:nexus/models/content/membership.dart"; import "package:nexus/models/membership_status.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; -import "package:nexus/widgets/divider_text.dart"; -import "package:nexus/widgets/error_dialog.dart"; -import "package:nexus/widgets/loading.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/common/divider_text.dart"; +import "package:nexus/widgets/room_chat/banned_warning_dialog.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/widgets/common/loading.dart"; class const MemberList(final String roomId, {super.key}) extends HookConsumerWidget { @@ -40,8 +42,26 @@ class const MemberList(final String roomId, {super.key}) padding: .all(8), child: M3EToggleButtonGroup( selectedIndex: statusIndex.value, - onSelectedIndexChanged: (index) => - statusIndex.value = index ?? statusIndex.value, + onSelectedIndexChanged: (index) async { + if (index == null) return; + if (options.values.toIList()[index] == .ban && + !await ref.read( + BannedWarningDismissedController.provider.future, + )) { + if (!context.mounted) return; + final confirmed = await showDialog( + context: context, + builder: (_) => BannedWarningDialog(), + ); + if (confirmed != true) return; + await ref + .read( + BannedWarningDismissedController.provider.notifier, + ) + .set(true); + } + statusIndex.value = index; + }, actions: options .mapTo( (name, value) => M3EToggleButtonGroupAction( @@ -108,42 +128,44 @@ class const MemberList(final String roomId, {super.key}) :final avatarUrl, :final displayName, ) => - Builder( - builder: (context) => ListTile( - onTap: () => - context.showUserPopover( + Consumer( + builder: (context, ref, _) => + ListTile( + onTap: () => + context.showUserPopover( + members[index].stateKey!, + roomId: roomId, + ), + title: Text( + displayName ?? + members[index] + .stateKey! + .localpart, + overflow: .ellipsis, + style: .new( + color: ref.displaynameColor( + roomId, + members[index].stateKey!, + ), + fontWeight: .bold, + ), + ), + subtitle: Text( members[index].stateKey!, - roomId: roomId, + overflow: .ellipsis, + ), + leading: Transform.translate( + offset: .new(0, 2), + child: AvatarOrHash( + avatarUrl, + dimension: 40, + displayName ?? + members[index] + .stateKey! + .localpart, + ), ), - title: Text( - displayName ?? - members[index] - .stateKey! - .localpart, - overflow: .ellipsis, - style: .new( - color: members[index] - .stateKey! - .colorHash, - fontWeight: .bold, ), - ), - subtitle: Text( - members[index].stateKey!, - overflow: .ellipsis, - ), - leading: Transform.translate( - offset: .new(0, 2), - child: AvatarOrHash( - avatarUrl, - dimension: 40, - displayName ?? - members[index] - .stateKey! - .localpart, - ), - ), - ), ), _ => throw Exception( "Member content was not MembershipContent", diff --git a/lib/widgets/pinned_events_drawer.dart b/lib/widgets/room_chat/pinned_events_drawer.dart similarity index 96% rename from lib/widgets/pinned_events_drawer.dart rename to lib/widgets/room_chat/pinned_events_drawer.dart index cff6ad6..1e0ab6a 100644 --- a/lib/widgets/pinned_events_drawer.dart +++ b/lib/widgets/room_chat/pinned_events_drawer.dart @@ -4,8 +4,8 @@ import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:nexus/controllers/pinned_events.dart"; import "package:nexus/helpers/hooks/chat_scroll.dart"; import "package:nexus/models/event.dart"; -import "package:nexus/widgets/error_dialog.dart"; -import "package:nexus/widgets/loading.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/widgets/common/loading.dart"; import "package:nexus/widgets/renderers/event.dart"; final class const PinnedEventsDrawer( diff --git a/lib/widgets/room_appbar.dart b/lib/widgets/room_chat/room_appbar.dart similarity index 77% rename from lib/widgets/room_appbar.dart rename to lib/widgets/room_chat/room_appbar.dart index 248661e..14b9df5 100644 --- a/lib/widgets/room_appbar.dart +++ b/lib/widgets/room_chat/room_appbar.dart @@ -1,14 +1,14 @@ import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/rooms.dart"; -import "package:nexus/widgets/appbar.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; -import "package:nexus/widgets/count_badge.dart"; -import "package:nexus/widgets/room_menu_button.dart"; -import "package:nexus/widgets/room_summary_sheet.dart"; -import "package:nexus/widgets/room_title.dart"; -import "package:nexus/widgets/sidebar.dart"; +import "package:nexus/widgets/common/appbar.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/common/count_badge.dart"; +import "package:nexus/widgets/rooms/room_menu_button.dart"; +import "package:nexus/widgets/rooms/room_summary_sheet.dart"; +import "package:nexus/widgets/rooms/room_title.dart"; +import "package:nexus/widgets/sidebar/sidebar.dart"; final class const RoomAppbar({ required final String? roomId, @@ -17,6 +17,7 @@ final class const RoomAppbar({ final void Function(BuildContext context)? onOpenMemberList, final void Function()? onOpenPinnedMessagesList, final void Function()? onOpenSearch, + final void Function()? onOpenThreads, super.key, }) extends ConsumerWidget implements PreferredSizeWidget { @override @@ -63,9 +64,9 @@ final class const RoomAppbar({ ? [] : [ IconButton( - onPressed: onOpenSearch?.call, - icon: Icon(Icons.search), - tooltip: "Search this room", + onPressed: onOpenThreads?.call, + icon: Icon(Icons.forum), + tooltip: "Open threads", ), IconButton( onPressed: onOpenPinnedMessagesList?.call, @@ -77,7 +78,7 @@ final class const RoomAppbar({ tooltip: "Open member list", icon: Icon(Icons.people), ), - RoomMenuButton(room), + RoomMenuButton(room, onOpenSearch: onOpenSearch), ], ), ); diff --git a/lib/widgets/room_chat/room_chat.dart b/lib/widgets/room_chat/room_chat.dart index e7fd6e0..8a29c38 100644 --- a/lib/widgets/room_chat/room_chat.dart +++ b/lib/widgets/room_chat/room_chat.dart @@ -1,32 +1,26 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:material_ui/material_ui.dart"; -import "package:flutter/services.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; -import "package:measure_size/measure_size.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/controllers/member_list_opened.dart"; -import "package:nexus/controllers/power_level.dart"; -import "package:nexus/controllers/settings.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/room_chat.dart"; +import "package:nexus/helpers/hooks/chat_composer.dart"; import "package:nexus/helpers/hooks/chat_scroll.dart"; import "package:nexus/models/event.dart"; -import "package:nexus/models/relation_type.dart"; -import "package:nexus/widgets/composer/composer.dart"; -import "package:nexus/widgets/composer/typing_indicator.dart"; -import "package:nexus/widgets/error_dialog.dart"; -import "package:nexus/widgets/loading.dart"; -import "package:nexus/widgets/pinned_events_drawer.dart"; -import "package:nexus/widgets/member_list.dart"; -import "package:nexus/widgets/room_appbar.dart"; -import "package:nexus/widgets/search_drawer.dart"; -import "package:nexus/widgets/sync_status_banner.dart"; -import "package:nexus/main.dart"; -import "package:nexus/widgets/room_chat/chat_timeline.dart"; +import "package:nexus/widgets/room_chat/pinned_events_drawer.dart"; +import "package:nexus/widgets/room_chat/member_list.dart"; +import "package:nexus/widgets/room_chat/room_appbar.dart"; +import "package:nexus/widgets/room_chat/search_drawer.dart"; +import "package:nexus/widgets/common/sync_status_banner.dart"; +import "package:nexus/widgets/threads/thread_drawer.dart"; +import "package:nexus/widgets/threads/threads_drawer.dart"; +import "package:nexus/widgets/room_chat/chat_body.dart"; import "package:nexus/helpers/extensions/build_event_options.dart"; import "package:nexus/controllers/jump_request.dart"; +import "package:nexus/main.dart"; final class const RoomChat({ required final String? roomId, @@ -36,18 +30,22 @@ final class const RoomChat({ }) extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final relatedEvent = useState(null); - final relationType = useState(RelationType.reply); final pendingJump = ref.read(JumpRequestController.provider); - final contextualEvent = useState( - pendingJump != null && pendingJump.roomId == this.roomId - ? pendingJump.rowId - : null, - ); - final highlightedEvent = useState(null); + final contextualEvent = useState(switch (pendingJump) { + // Threaded events open their thread instead, leaving the timeline + (:final roomId, :final rowId) + when roomId == this.roomId && + ref + .read(RoomsController.provider)[roomId] + ?.events[rowId] + ?.threadRoot == + null => + rowId, + _ => null, + }); - final composerSize = useState(64); - final typingIndicatorSize = useState(0); + final thread = useState<({String root, int? event})?>(null); + final threadScaffold = useMemoized(GlobalKey.new); final userId = ref.watch(ClientStateController.provider)?.userId; final memberListOpened = ref @@ -78,6 +76,7 @@ final class const RoomChat({ } final roomId = this.roomId!; + final composer = ChatComposer.use(ref, (roomId: roomId, threadRoot: null)); final jumpRowId = ref.watch( JumpRequestController.provider.select( @@ -88,6 +87,7 @@ final class const RoomChat({ final ChatParams chat = ( roomId: roomId, contextualEvent: contextualEvent.value, + threadRoot: null, ); final controllerProvider = RoomChatController.provider(chat); final notifier = ref.watch(controllerProvider.notifier); @@ -111,49 +111,24 @@ final class const RoomChat({ }, ); - final lastComposerHeight = useRef(composerSize.value); + void openThread(String root, {int? event}) { + thread.value = (root: root, event: event); - useEffect(() { - final delta = composerSize.value - lastComposerHeight.value; - lastComposerHeight.value = composerSize.value; - - if (delta != 0) { - final wasAtBottom = scroll.atBottom; - - WidgetsBinding.instance.addPostFrameCallback((_) { - final controller = scroll.scrollController; - if (!controller.hasClients) return; - - final position = controller.position; - controller.jumpTo( - wasAtBottom ? position.minScrollExtent : position.pixels - delta, - ); - }); - } - - return null; - }, [composerSize.value]); - - final composerNode = useFocusNode( - onKeyEvent: (_, event) { - if (event is KeyDownEvent && event.logicalKey == .escape) { - relatedEvent.value = null; - return .handled; - } - - return .ignored; - }, - ); + // The drawer is only there once rebuilt with the thread + WidgetsBinding.instance.addPostFrameCallback( + (_) => threadScaffold.currentState?.openEndDrawer(), + ); + } + // Threaded events aren't in the timeline, only their thread Future jumpToEvent(int rowId) async { - highlightedEvent.value = rowId; + final threadRoot = ref + .read(RoomsController.provider)[roomId] + ?.events[rowId] + ?.threadRoot; - await scroll.jumpToEvent(rowId); - await Future.delayed(Durations.extralong1, () { - if (highlightedEvent.value == rowId) { - highlightedEvent.value = null; - } - }); + if (threadRoot == null) return scroll.jumpToEvent(rowId); + openThread(threadRoot, event: rowId); } useEffect(() { @@ -177,171 +152,97 @@ final class const RoomChat({ return null; }, [jumpRowId]); - void onRelation(int rowId, RelationType type) { - relatedEvent.value = rowId; - relationType.value = type; - composerNode.requestFocus(); - } - IList getEventOptions(Event event) => event.buildEventOptions( context: context, ref: ref, roomId: roomId, userId: userId, - onRelation: onRelation, + onRelation: composer.relate, + onStartThread: openThread, ); - final swipeToReply = ref.watch( - SettingsController.provider.select( - (settings) => settings.value?.swipeToReply ?? false, - ), - ); - final canReply = ref.watch( - PowerLevelController.provider(.new(eventType: .message, roomId: roomId)), - ); - return Scaffold( + key: threadScaffold, endDrawerEnableOpenDragGesture: false, - endDrawer: SearchDrawer( - roomId, - getEventOptions: getEventOptions, - jumpToEvent: jumpToEvent, - ), - body: Builder( - builder: (searchContext) => Scaffold( - endDrawerEnableOpenDragGesture: false, - endDrawer: PinnedEventsDrawer( - roomId, - getEventOptions: getEventOptions, - jumpToEvent: jumpToEvent, - ), - body: Builder( - builder: (middleContext) => Scaffold( - endDrawer: showMembersByDefault ? null : MemberList(roomId), - appBar: RoomAppbar( - roomId: roomId, - isDesktop: isDesktop, - onOpenDrawer: Scaffold.of(context).openDrawer, - onOpenMemberList: (thisContext) { - ref - .read(MemberListOpenedController.provider.notifier) - .set(!memberListOpened); - Scaffold.of(thisContext).openEndDrawer(); - }, - onOpenPinnedMessagesList: Scaffold.of(middleContext) - .openEndDrawer, - onOpenSearch: Scaffold.of(searchContext).openEndDrawer, - ), - body: Column( - children: [ - const SyncStatusBanner(), - Expanded( - child: Row( + endDrawer: switch (thread.value) { + (:final root, :final event) => ThreadDrawer( + roomId, + threadRoot: root, + initialEvent: event, + jumpToRoomEvent: jumpToEvent, + userId: userId, + key: ValueKey((roomId, root, event)), + ), + null => null, + }, + body: Scaffold( + endDrawerEnableOpenDragGesture: false, + endDrawer: SearchDrawer( + roomId, + getEventOptions: getEventOptions, + jumpToEvent: jumpToEvent, + ), + body: Builder( + builder: (searchContext) => Scaffold( + endDrawerEnableOpenDragGesture: false, + endDrawer: ThreadsDrawer(roomId, onOpenThread: openThread), + body: Builder( + builder: (threadsContext) => Scaffold( + endDrawerEnableOpenDragGesture: false, + endDrawer: PinnedEventsDrawer( + roomId, + getEventOptions: getEventOptions, + jumpToEvent: jumpToEvent, + ), + body: Builder( + builder: (middleContext) => Scaffold( + endDrawer: showMembersByDefault ? null : MemberList(roomId), + appBar: RoomAppbar( + roomId: roomId, + isDesktop: isDesktop, + onOpenDrawer: Scaffold.of(context).openDrawer, + onOpenMemberList: (thisContext) { + if (!showMembersByDefault) { + return Scaffold.of(thisContext).openEndDrawer(); + } + + ref + .read(MemberListOpenedController.provider.notifier) + .set(!memberListOpened) + .onError(showError); + }, + onOpenPinnedMessagesList: Scaffold.of(middleContext) + .openEndDrawer, + onOpenSearch: Scaffold.of(searchContext).openEndDrawer, + onOpenThreads: Scaffold.of(threadsContext).openEndDrawer, + ), + body: Column( children: [ + const SyncStatusBanner(), Expanded( - child: Stack( + child: Row( children: [ - Positioned.fill( - child: Padding( - padding: .symmetric(horizontal: 4), - child: switch (controllerData) { - AsyncLoading(value: _?) || - AsyncData(value: _) => ChatTimeline( - scroll: scroll, - chat: chat, - jumpToEvent: jumpToEvent, - getEventOptions: getEventOptions, - onSwipe: swipeToReply && canReply - ? (rowId) => onRelation(rowId, .reply) - : null, - highlightedEvent: highlightedEvent.value, - composerHeight: composerSize.value, - typingIndicatorHeight: - typingIndicatorSize.value, - ), - AsyncLoading _ => Loading(), - AsyncError( - :final error, - :final stackTrace, - ) => - ErrorDialog(error, stackTrace), - }, - ), - ), - AnimatedPositioned( - duration: Durations.short4, - bottom: composerSize.value, - left: 12, - // Leaves room for the jump to bottom button when it's shown - right: scroll.atBottom ? 12 : 72, - child: MeasureSize( - onChange: (size) => - typingIndicatorSize.value = size.height, - child: TypingIndicator(roomId), - ), - ), - Positioned( - right: 16, - bottom: composerSize.value, - child: IgnorePointer( - ignoring: scroll.atBottom, - child: AnimatedOpacity( - opacity: scroll.atBottom ? 0 : 1, - duration: Durations.short4, - child: FloatingActionButton.small( - onPressed: scroll.jumpToBottom, - child: const Icon( - Icons.keyboard_arrow_down, - ), - ), - ), - ), - ), - Positioned( - bottom: 0, - left: 0, - right: 0, - child: MeasureSize( - onChange: (size) => - composerSize.value = size.height, - child: Composer( - roomId, - node: composerNode, - onSend: - ( - text, { - required shouldMention, - required tags, - }) => notifier - .send( - text, - tags: tags, - relationType: relationType.value, - shouldMention: shouldMention, - relatedEventRowId: - relatedEvent.value, - ) - .onError(showError), - relationType: relationType.value, - relatedEvent: relatedEvent.value, - onDismiss: () { - relatedEvent.value = null; - composerNode.requestFocus(); - }, - ), + Expanded( + child: ChatBody( + chat: chat, + scroll: scroll, + jumpToEvent: jumpToEvent, + getEventOptions: getEventOptions, + composer: composer, + onOpenThread: openThread, ), ), + + if (memberListOpened && showMembersByDefault) + MemberList(roomId), ], ), ), - - if (memberListOpened && showMembersByDefault) - MemberList(roomId), ], ), ), - ], + ), ), ), ), diff --git a/lib/widgets/search_drawer.dart b/lib/widgets/room_chat/search_drawer.dart similarity index 98% rename from lib/widgets/search_drawer.dart rename to lib/widgets/room_chat/search_drawer.dart index 03418df..2905789 100644 --- a/lib/widgets/search_drawer.dart +++ b/lib/widgets/room_chat/search_drawer.dart @@ -6,8 +6,8 @@ import "package:nexus/controllers/event_search.dart"; import "package:nexus/helpers/hooks/chat_scroll.dart"; import "package:nexus/main.dart"; import "package:nexus/models/event.dart"; -import "package:nexus/widgets/error_dialog.dart"; -import "package:nexus/widgets/loading.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/widgets/common/loading.dart"; import "package:nexus/widgets/renderers/event.dart"; final class const SearchDrawer( diff --git a/lib/widgets/room_chat/tombstone_banner.dart b/lib/widgets/room_chat/tombstone_banner.dart new file mode 100644 index 0000000..8227ba7 --- /dev/null +++ b/lib/widgets/room_chat/tombstone_banner.dart @@ -0,0 +1,56 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/helpers/extensions/open_link_info.dart"; +import "package:nexus/main.dart"; +import "package:nexus/models/content/tombstone.dart"; +import "package:nexus/models/event.dart"; + +class const TombstoneBanner(final Event tombstone, {super.key}) + extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final theme = Theme.of(context); + final content = tombstone.content; + final sender = tombstone.sender; + + return Container( + color: theme.colorScheme.surfaceContainerHighest, + padding: .symmetric(horizontal: 16, vertical: 8), + margin: .only(top: 4), + child: Row( + spacing: 12, + children: [ + Icon(Icons.upgrade), + Expanded( + child: Column( + mainAxisSize: .min, + crossAxisAlignment: .start, + children: [ + Text( + "This room has been replaced and is no longer active.", + style: .new(fontWeight: .bold), + ), + if (content case TombstoneContent(:final body) + when body.isNotEmpty) + Text(body, style: theme.textTheme.bodySmall), + ], + ), + ), + if (content case TombstoneContent(:final replacementRoom)) + FilledButton.icon( + onPressed: () => ref + .openLinkInfo(context, ( + identifier: replacementRoom, + eventId: null, + via: [sender.substring(sender.indexOf(":") + 1)].lock, + )) + .onError(showError), + label: Text("New room"), + icon: Icon(Icons.open_in_new), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/room_list.dart b/lib/widgets/room_list.dart deleted file mode 100644 index f8d366e..0000000 --- a/lib/widgets/room_list.dart +++ /dev/null @@ -1,355 +0,0 @@ -import "dart:math"; - -import "package:hooks_riverpod/hooks_riverpod.dart"; -import "package:material_ui/material_ui.dart"; -import "package:m3e_design/m3e_design.dart"; -import "package:navigation_rail_m3e/navigation_rail_m3e.dart"; -import "package:nexus/helpers/extensions/get_all_child_rooms.dart"; -import "package:nexus/helpers/extensions/room_destinations.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; -import "package:nexus/widgets/adaptive_menu_button.dart"; -import "package:nexus/models/nav_page.dart"; -import "package:nexus/widgets/appbar.dart"; -import "package:nexus/widgets/room_title.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; -import "package:nexus/widgets/create_room_sheet.dart"; -import "package:nexus/widgets/start_dm_sheet.dart"; -import "package:nexus/widgets/divider_widget.dart"; -import "package:nexus/widgets/error_dialog.dart"; -import "package:nexus/widgets/pages/settings.dart"; -import "package:nexus/widgets/join_sheet.dart"; -import "package:nexus/widgets/room_summary_sheet.dart"; -import "package:nexus/widgets/room_menu_button.dart"; -import "package:nexus/widgets/space_hierarchy_sheet.dart"; -import "package:nexus/controllers/key.dart"; -import "package:nexus/controllers/selected_room.dart"; -import "package:nexus/controllers/selected_space.dart"; -import "package:nexus/controllers/rooms.dart"; -import "package:nexus/controllers/spaces.dart"; - -// Needed for navigation_rail_m3e (#65). -import "package:flutter/material.dart" as old_mat; - -class const RoomList({super.key}) extends ConsumerWidget implements NavPage { - @override - String get title => "Rooms"; - - @override - IconData get icon => Icons.list; - - @override - int? badgeCount(WidgetRef ref) { - final (notifications, hasUnread) = ref.watch( - RoomsController.provider.select( - (rooms) => rooms.values.fold( - (0, false), - (total, room) => ( - total.$1 + (room.metadata?.unreadNotifications ?? 0), - total.$2 || (room.metadata?.unreadMessages ?? 0) > 0, - ), - ), - ), - ); - - return notifications > 0 - ? notifications - : hasUnread - ? 0 - : null; - } - - @override - Widget build(BuildContext context, WidgetRef ref) { - final spacesAsync = ref.watch(SpacesController.provider); - if (spacesAsync.value == null) { - return switch (spacesAsync) { - AsyncError(:final error, :final stackTrace) => ErrorDialog( - error, - stackTrace, - ), - _ => const Center(child: CircularProgressIndicator()), - }; - } - - return const Row( - children: [ - SpacesRail(), - Expanded(child: RoomsPane()), - ], - ); - } -} - -class const SpacesRail({super.key}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final spaces = ref.watch( - SpacesController.provider.select((async) => async.requireValue), - ); - final selectedSpaceId = ref.watch( - KeyController.provider(KeyController.spaceKey) - .select((async) => async.requireValue), - ); - - return MaterialUiCompatibilityBridge( - child: Builder( - builder: (context) => old_mat.Theme( - data: old_mat.Theme.of(context).copyWith( - extensions: [ - NavigationRailM3ETheme( - itemCollapsedHeight: 48, - itemVerticalGap: 0, - ), - ], - ), - child: Container( - color: NavigationRailTokensAdapter(context).containerColor, - padding: .only(top: 16), - child: NavigationRailM3E( - type: .alwaysCollapse, - labelBehavior: .alwaysHide, - scrollable: true, - onDestinationSelected: (value) { - ref - .read( - KeyController.provider(KeyController.spaceKey).notifier, - ) - .set(spaces[value].id); - ref - .read( - KeyController.provider(KeyController.roomKey).notifier, - ) - .set(spaces[value].children.firstOrNull?.metadata?.id); - }, - sections: [ - .new( - destinations: spaces.map((space) { - final notifications = space.allChildRooms.fold( - 0, - (sum, room) => - sum + (room.metadata?.unreadNotifications ?? 0), - ); - - return NavigationRailM3EDestination( - badgeCount: notifications > 0 - ? notifications - : space.allChildRooms.any( - (room) => room.metadata?.unreadMessages != 0, - ) - ? 0 - : null, - short: true, - icon: AvatarOrHash( - dimension: 28, - space.room?.metadata?.avatar, - fallback: space.icon == null ? null : Icon(space.icon), - space.title, - ), - label: space.title, - ); - }).toList(), - ), - ], - selectedIndex: max( - 0, - spaces.indexWhere((space) => space.id == selectedSpaceId), - ), - trailingAtBottom: true, - trailing: Padding( - padding: .only(top: 8), - child: Column( - children: [ - AdaptiveMenuButton( - tooltip: "Add a room", - itemBuilder: (_) => [ - PopupMenuItem( - onTap: () => - context.showAdaptiveSheet((_) => JoinSheet(ref)), - child: const ListTile( - title: Text("Join an existing room (or space)"), - leading: Icon(Icons.numbers), - ), - ), - PopupMenuItem( - onTap: () => context.showAdaptiveSheet( - (_) => const CreateRoomSheet(), - ), - child: const ListTile( - title: Text("Create a new room (or space)"), - leading: Icon(Icons.add), - ), - ), - PopupMenuItem( - onTap: () => context.showAdaptiveSheet( - (_) => const StartDmSheet(), - ), - child: const ListTile( - title: Text("Start a direct message"), - leading: Icon(Icons.person_add), - ), - ), - ], - icon: const Icon(Icons.add), - ), - const IconButton( - tooltip: "Explore other rooms (Not yet implemented)", - onPressed: null, - icon: Icon(Icons.explore), - ), - IconButton( - tooltip: "Open settings", - onPressed: () => showDialog( - context: context, - builder: (_) => SettingsPage(), - ), - icon: const Icon(Icons.settings), - ), - ], - ), - ), - ), - ), - ), - ), - ); - } -} - -class const RoomsPane({super.key}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final selectedRoomId = ref.watch(SelectedRoomController.provider); - final selectedSpace = ref.watch(SelectedSpaceController.provider)!; - final isDm = selectedSpace.id == "dms"; - final spaceMetadata = selectedSpace.room?.metadata; - - return Scaffold( - backgroundColor: Colors.transparent, - appBar: Appbar( - // Home and DMs aren't real spaces, so they don't have a summary. - onTap: spaceMetadata == null - ? null - : () => context.showAdaptiveSheet( - (_) => RoomSummarySheet(.fromMetadata(spaceMetadata)), - ), - windowControls: false, - leading: AvatarOrHash( - spaceMetadata?.avatar, - fallback: selectedSpace.icon == null - ? null - : Icon(selectedSpace.icon), - selectedSpace.title, - ), - title: RoomTitle(selectedSpace.title, topic: spaceMetadata?.topic), - backgroundColor: Colors.transparent, - actions: .new([ - RoomMenuButton( - selectedSpace.room, - children: selectedSpace.allChildRooms, - ), - ]), - ), - body: MaterialUiCompatibilityBridge( - child: Builder( - builder: (context) { - final theme = old_mat.Theme.of(context); - return old_mat.Theme( - data: theme.copyWith( - extensions: [ - NavigationRailM3ETheme( - itemExpandedHeight: 48, - iconLabelGap: 16, - sectionHeaderSpacingTop: 0, - ), - // Otherwise the FAB label falls back to Roboto - M3ETheme.defaults(theme.colorScheme).copyWith( - typography: .defaultFor( - theme.brightness, - baseOverride: theme.textTheme, - ), - ), - ], - ), - child: Padding( - padding: const .only(top: 4), - child: NavigationRailM3E( - fab: selectedSpace.room == null - ? null - : .new( - icon: const Icon(Icons.explore), - label: "Browse space", - tooltip: "Browse and join rooms in this space", - onPressed: () => context.showAdaptiveSheet( - (_) => SpaceHierarchySheet(selectedSpace.id), - ), - ), - expandedWidth: double.infinity, - scrollable: true, - background: Colors.transparent, - type: .alwaysExpand, - selectedIndex: max( - 0, - selectedSpace.allChildRooms.indexWhere( - (room) => room.metadata?.id == selectedRoomId, - ), - ), - sections: [ - .new( - header: selectedSpace.room == null - ? null - : const DividerWidget(Text("Rooms")), - destinations: selectedSpace.children.toDestinations( - isDm: isDm, - ), - ), - ...selectedSpace.subSpaces.map( - (subSpace) => NavigationRailM3ESection( - header: DividerWidget( - Row( - mainAxisSize: .min, - spacing: 8, - children: [ - if (subSpace.room.metadata?.avatar != null) - AvatarOrHash( - subSpace.room.metadata?.avatar, - subSpace.room.metadata?.name ?? - "Unnamed Room", - dimension: 16, - ), - Flexible( - child: Text( - subSpace.room.metadata?.name ?? - "Unnamed Space", - maxLines: 1, - overflow: .ellipsis, - ), - ), - ], - ), - ), - destinations: subSpace.children.toDestinations( - isDm: isDm, - ), - ), - ), - ], - onDestinationSelected: (value) { - ref - .read( - KeyController.provider(KeyController.roomKey) - .notifier, - ) - .set(selectedSpace.allChildRooms[value].metadata?.id); - if (Navigator.of(context).canPop()) { - Navigator.of(context).pop(); - } - }, - ), - ), - ); - }, - ), - ), - ); - } -} diff --git a/lib/widgets/rooms/add_directory_server_sheet.dart b/lib/widgets/rooms/add_directory_server_sheet.dart new file mode 100644 index 0000000..2fefe3b --- /dev/null +++ b/lib/widgets/rooms/add_directory_server_sheet.dart @@ -0,0 +1,54 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; + +class const AddDirectoryServerSheet({ + required final ISet existing, + super.key, +}) extends HookWidget { + @override + Widget build(BuildContext context) { + final controller = useTextEditingController(); + final text = useValueListenable(controller).text; + final server = text.trim().toLowerCase(); + final error = server.isEmpty + ? null + : !server.isValidServerName + ? "Enter a server name, without https:// or a path" + : existing.contains(server) + ? "This server has already been added" + : null; + final valid = server.isNotEmpty && error == null; + + void submit() { + if (valid) Navigator.of(context).pop(server); + } + + return SheetLayout( + title: const Text("Add Server"), + actions: [ + TextButton( + onPressed: Navigator.of(context).pop, + child: const Text("Cancel"), + ), + TextButton(onPressed: valid ? submit : null, child: const Text("Add")), + ], + children: [ + const Text("Enter a server to browse the public rooms of."), + TextField( + controller: controller, + autofocus: true, + keyboardType: .url, + onSubmitted: (_) => submit(), + decoration: .new( + labelText: "Server name", + hintText: "matrix.org", + errorText: error, + ), + ), + ], + ); + } +} diff --git a/lib/widgets/rooms/add_space_rooms_sheet.dart b/lib/widgets/rooms/add_space_rooms_sheet.dart new file mode 100644 index 0000000..e78ba7a --- /dev/null +++ b/lib/widgets/rooms/add_space_rooms_sheet.dart @@ -0,0 +1,181 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/client_state.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/controllers/space_hierarchy.dart"; +import "package:nexus/controllers/via.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/helpers/extensions/with_progress_snackbar.dart"; +import "package:nexus/main.dart"; +import "package:nexus/models/content/content.dart"; +import "package:nexus/models/content/space_child.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/settings/search_chooser.dart"; + +/// Chooses rooms to add to the space [spaceId], then adds them. +class const AddSpaceRoomsSheet( + final String spaceId, { + required final String spaceName, + + /// The rooms already in the space, which aren't offered. + required final ISet existing, + super.key, +}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final chosen = useState(const ISet.empty()); + final error = useState(null); + final resolving = useState(false); + final controller = useTextEditingController(); + final rooms = ref.watch( + RoomsController.provider.select( + (rooms) => IMap.fromEntries( + rooms.values + .map((room) => room.metadata) + .nonNulls + .map( + (metadata) => MapEntry(metadata.id, ( + name: metadata.name, + avatar: metadata.avatar, + )), + ), + ), + ), + ); + + String nameOf(String id) => rooms[id]?.name ?? id; + + final suggestions = rooms.entries + .where((entry) => entry.key != spaceId && !existing.contains(entry.key)) + .sortedBy((entry) => entry.value.name?.toLowerCase() ?? "") + .map((entry) => entry.key) + .toIList(); + + void add(String id) { + if (id == spaceId) { + error.value = "A space can't contain itself"; + return; + } + if (existing.contains(id)) { + error.value = "This room is already in the space"; + return; + } + if (!chosen.value.contains(id)) chosen.value = chosen.value.add(id); + controller.clear(); + } + + Future addRoom(String text) async { + if (text.startsWith("!")) return add(text); + + resolving.value = true; + try { + final id = await ref + .read(ClientController.provider.notifier) + .resolveAlias(text); + + if (!context.mounted) return; + + if (id == null) { + error.value = "No room has this alias"; + } else { + add(id); + } + } finally { + if (context.mounted) resolving.value = false; + } + } + + // Runs after the sheet closes, so it can't use [ref] + Future save(ProviderContainer container, ISet roomIds) async { + final client = container.read(ClientController.provider.notifier); + final joined = container.read(RoomsController.provider); + final ownServer = container + .read(ClientStateController.provider) + ?.userId + ?.serverName; + + await Future.wait( + roomIds.map( + (roomId) => client.setState( + .new( + roomId: spaceId, + type: EventType.spaceChild.type, + stateKey: roomId, + content: SpaceChildContent( + via: switch (joined[roomId]) { + final room? => container.read(ViaController.provider(room)), + // Rooms the user isn't in can only be routed through their + // own server + null => ISet([?ownServer]), + }.toIList(), + ), + ), + ), + ), + ); + container.invalidate(SpaceHierarchyController.provider(spaceId)); + } + + return SheetLayout( + title: Text("Add Rooms"), + actions: [ + TextButton(onPressed: Navigator.of(context).pop, child: Text("Cancel")), + TextButton( + onPressed: chosen.value.isEmpty + ? null + : () { + final container = ProviderScope.containerOf(context); + final roomIds = chosen.value; + SpaceHierarchyController.addChildrenMutation(spaceId).run( + container, + (_) => context.withProgressSnackbar( + "Adding ${roomIds.length == 1 ? nameOf(roomIds.single) : "${roomIds.length} rooms"} to $spaceName...", + () => save(container, roomIds), + ), + ); + Navigator.of(context).pop(); + }, + child: Text("Add"), + ), + ], + children: [ + Text("Choose rooms to add to \"$spaceName\"."), + SearchChooser( + controller: controller, + chosen: chosen.value, + options: suggestions, + nameOf: nameOf, + avatarOf: (id) => AvatarOrHash( + rooms[id]?.avatar, + nameOf(id), + fallback: Icon(Icons.numbers), + ), + subtitleOf: (id) => rooms[id]?.name == null ? null : id, + onAdded: add, + onRemoved: (id) => chosen.value = chosen.value.remove(id), + onSubmitted: (text, topMatch) { + if (text.startsWith(RegExp("[!#]"))) { + addRoom(text).onError(showError); + } else if (topMatch != null) { + add(topMatch); + } else { + error.value = "Enter a room ID or alias"; + } + }, + onChanged: (_) => error.value = null, + label: "Add room", + hint: "Search, or enter a room ID or alias", + removeTooltip: "Remove room", + error: error.value, + loading: resolving.value, + autofocus: true, + ), + ], + ); + } +} diff --git a/lib/widgets/create_room_sheet.dart b/lib/widgets/rooms/create_room_sheet.dart similarity index 98% rename from lib/widgets/create_room_sheet.dart rename to lib/widgets/rooms/create_room_sheet.dart index 423b909..d91c2f4 100644 --- a/lib/widgets/create_room_sheet.dart +++ b/lib/widgets/rooms/create_room_sheet.dart @@ -1,10 +1,10 @@ import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/helpers/extensions/create_room.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; -import "package:nexus/widgets/sheet_layout.dart"; class const CreateRoomSheet({super.key}) extends HookConsumerWidget { @override diff --git a/lib/widgets/join_sheet.dart b/lib/widgets/rooms/join_sheet.dart similarity index 91% rename from lib/widgets/join_sheet.dart rename to lib/widgets/rooms/join_sheet.dart index b690e9c..e9ee719 100644 --- a/lib/widgets/join_sheet.dart +++ b/lib/widgets/rooms/join_sheet.dart @@ -1,11 +1,10 @@ import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; -import "package:nexus/widgets/sheet_layout.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/room_summary.dart"; import "package:nexus/helpers/extensions/get_link_info.dart"; -import "package:nexus/widgets/room_summary_sheet.dart"; +import "package:nexus/widgets/rooms/room_summary_sheet.dart"; class const JoinSheet(final WidgetRef ref, {super.key}) extends HookWidget { @override diff --git a/lib/widgets/knock_sheet.dart b/lib/widgets/rooms/knock_sheet.dart similarity index 95% rename from lib/widgets/knock_sheet.dart rename to lib/widgets/rooms/knock_sheet.dart index 9c6bdcb..524856c 100644 --- a/lib/widgets/knock_sheet.dart +++ b/lib/widgets/rooms/knock_sheet.dart @@ -1,8 +1,8 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/helpers/extensions/join_room.dart"; -import "package:nexus/widgets/sheet_layout.dart"; /// Asks the moderators of a room to let the user in, with an optional reason. /// diff --git a/lib/widgets/rooms/room_directory_card.dart b/lib/widgets/rooms/room_directory_card.dart new file mode 100644 index 0000000..10cc071 --- /dev/null +++ b/lib/widgets/rooms/room_directory_card.dart @@ -0,0 +1,130 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/controllers/sidebar_page.dart"; +import "package:nexus/helpers/extensions/focus_room.dart"; +import "package:nexus/helpers/extensions/join_room.dart"; +import "package:nexus/helpers/extensions/room_summary_display.dart"; +import "package:nexus/models/room_summary.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/rooms/knock_sheet.dart"; +import "package:nexus/widgets/rooms/room_summary_sheet.dart"; + +class const RoomDirectoryCard( + final RoomSummary summary, { + required final IList via, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final joined = ref.watch( + RoomsController.provider.select( + (rooms) => rooms.containsKey(summary.roomId), + ), + ); + final mustKnock = ref.watch( + RoomsController.provider.select( + (rooms) => summary.mustKnock( + summary.allowedRoomIds.where(rooms.containsKey).toISet(), + ), + ), + ); + final theme = Theme.of(context); + final name = summary.displayName; + + return Card.filled( + clipBehavior: .antiAlias, + margin: .zero, + child: InkWell( + onTap: () => context.showAdaptiveSheet( + (_) => RoomSummarySheet(summary, via: joined ? null : via), + ), + child: Padding( + padding: const .all(16), + child: Column( + crossAxisAlignment: .stretch, + spacing: 12, + children: [ + Row( + spacing: 12, + children: [ + AvatarOrHash( + summary.avatarUrl, + name, + dimension: 48, + fallback: Icon(summary.icon), + ), + Expanded( + child: Column( + crossAxisAlignment: .start, + children: [ + Text( + name, + maxLines: 1, + overflow: .ellipsis, + style: theme.textTheme.titleMedium, + ), + if (summary.details case final details + when details.isNotEmpty) + Text( + details, + maxLines: 1, + overflow: .ellipsis, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), + Expanded( + child: Text( + summary.topic ?? summary.canonicalAlias ?? "", + maxLines: 3, + overflow: .ellipsis, + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + Align( + alignment: .centerRight, + child: joined + ? FilledButton.tonal( + onPressed: () async { + final container = ProviderScope.containerOf(context); + Navigator.of(context).pop(); + await container.focusRoom(summary.roomId); + container + .read(SidebarPageController.provider.notifier) + .set(.rooms); + }, + child: const Text("Open"), + ) + : mustKnock + ? FilledButton( + onPressed: () => context.showAdaptiveSheet( + (_) => + KnockSheet(summary.roomId, name: name, via: via), + ), + child: const Text("Knock"), + ) + : FilledButton( + onPressed: () => context.joinRoom( + .new(roomIdOrAlias: summary.roomId, via: via), + name: name, + ), + child: const Text("Join"), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/widgets/room_menu_button.dart b/lib/widgets/rooms/room_menu_button.dart similarity index 73% rename from lib/widgets/room_menu_button.dart rename to lib/widgets/rooms/room_menu_button.dart index 38ad847..22d94f9 100644 --- a/lib/widgets/room_menu_button.dart +++ b/lib/widgets/rooms/room_menu_button.dart @@ -1,14 +1,14 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/show_leave_room_sheet.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; -import "package:nexus/widgets/sheet_layout.dart"; import "package:flutter/services.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/account_data.dart"; import "package:nexus/controllers/client.dart"; +import "package:nexus/models/room_notification_level.dart"; import "package:nexus/controllers/room_settings_sections.dart"; -import "package:nexus/widgets/adaptive_menu_button.dart"; import "package:nexus/widgets/settings/settings_layout.dart"; import "package:nexus/controllers/via.dart"; import "package:nexus/models/room.dart"; @@ -18,6 +18,7 @@ import "package:nexus/main.dart"; final class const RoomMenuButton( final Room? room, { final IList children = const .empty(), + final VoidCallback? onOpenSearch, super.key, }) extends ConsumerWidget { @override @@ -29,6 +30,11 @@ final class const RoomMenuButton( icon: const Icon(Icons.more_vert), tooltip: "Room options", itemBuilder: (_) => [ + if (onOpenSearch != null) + PopupMenuItem( + onTap: onOpenSearch, + child: ListTile(leading: Icon(Icons.search), title: Text("Search")), + ), PopupMenuItem( onTap: () async { if (room != null) await client.markRead(room!); @@ -42,7 +48,45 @@ final class const RoomMenuButton( if (room != null) ...[ PopupMenuItem( onTap: () async { - final vias = ref.read(ViaController.provider(room!)); + final roomId = room!.metadata!.id; + final accountData = ref.read( + AccountDataController.provider.notifier, + ); + final current = RoomNotificationLevel.of( + ref.read(AccountDataController.provider).pushRules.global, + roomId, + ); + + final level = await context.showAdaptiveMenu( + RoomNotificationLevel.values + .map( + (level) => PopupMenuItem( + value: level, + child: ListTile( + selected: level == current, + leading: Icon(level.icon), + title: Text(level.title), + subtitle: Text(level.description), + trailing: level == current ? Icon(Icons.check) : null, + ), + ), + ) + .toList(), + ); + if (level == null) return; + await accountData + .setRoomNotificationLevel(roomId, level) + .onError(showError); + }, + child: ListTile( + leading: Icon(Icons.notifications), + title: Text("Notifications"), + trailing: Icon(Icons.expand_more), + ), + ), + PopupMenuItem( + onTap: () async { + final vias = ref.read(ViaController.provider(room!)).viaQuery; await Clipboard.setData( .new( @@ -146,7 +190,7 @@ final class const RoomMenuButton( ), child: ListTile( leading: Icon(Icons.logout, color: danger), - title: Text("Leave", style: TextStyle(color: danger)), + title: Text("Leave", style: .new(color: danger)), ), ), ], diff --git a/lib/widgets/room_summary_sheet.dart b/lib/widgets/rooms/room_summary_sheet.dart similarity index 77% rename from lib/widgets/room_summary_sheet.dart rename to lib/widgets/rooms/room_summary_sheet.dart index dd7bc9b..2195101 100644 --- a/lib/widgets/room_summary_sheet.dart +++ b/lib/widgets/rooms/room_summary_sheet.dart @@ -1,18 +1,18 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:material_ui/material_ui.dart"; -import "package:nexus/widgets/sheet_layout.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/invites.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/join_room.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; +import "package:nexus/helpers/extensions/room_summary_display.dart"; import "package:nexus/main.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; -import "package:nexus/widgets/expandable_image.dart"; -import "package:nexus/widgets/knock_sheet.dart"; -import "package:nexus/widgets/linkified_text.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/common/expandable_image.dart"; +import "package:nexus/widgets/rooms/knock_sheet.dart"; +import "package:nexus/widgets/common/linkified_text.dart"; import "package:nexus/models/room_summary.dart"; class const RoomSummarySheet( @@ -45,15 +45,11 @@ class const RoomSummarySheet( summary.avatarUrl, "", dimension: 64, - fallback: Icon(Icons.numbers), + fallback: Icon(summary.icon), ), ), Expanded( - child: Text( - summary.name ?? summary.canonicalAlias ?? "Unnamed Room", - overflow: .ellipsis, - maxLines: 3, - ), + child: Text(summary.displayName, overflow: .ellipsis, maxLines: 3), ), ], ), @@ -65,9 +61,13 @@ class const RoomSummarySheet( final container = ProviderScope.containerOf(context); Navigator.of(context).pop(); - container - .read(InvitesController.provider.notifier) - .decline(summary.roomId) + InvitesController.respondMutation(summary.roomId) + .run( + container, + (_) => container + .read(InvitesController.provider.notifier) + .decline(summary.roomId), + ) .onError(showError); }, style: TextButton.styleFrom(foregroundColor: colorScheme.error), @@ -77,18 +77,19 @@ class const RoomSummarySheet( onPressed: () { final container = ProviderScope.containerOf(context); - context - .joinRoom( - .new(roomIdOrAlias: summary.roomId, fromInvite: true), - name: name, - ) - .then((roomId) { + InvitesController.respondMutation(summary.roomId) + .run(container, (_) async { + final roomId = await context.joinRoom( + .new(roomIdOrAlias: summary.roomId, fromInvite: true), + name: name, + ); if (roomId != null) { container .read(InvitesController.provider.notifier) .remove(summary.roomId); } - }); + }) + .onError(showError); Navigator.of(context).pop(); }, child: Text("Accept"), @@ -154,27 +155,32 @@ class const RoomSummarySheet( title: const Text("Invite reason"), subtitle: SelectableText(reason), ), - // Invite state never includes the member count - if (summary.joinedMembers != null || !isInvite) + + if (summary.joinedMembers != null) ListTile( title: Text( "${summary.joinedMembers ?? "Unknown number of"} members", ), leading: Icon(Icons.people), ), + + if (summary.canonicalAlias case final canonicalAlias?) + ListTile( + title: Text("Canonical Alias"), + subtitle: SelectableText(canonicalAlias), + leading: Icon(Icons.numbers), + ), + ListTile( - title: Text( - summary.canonicalAlias == null ? "Room ID" : "Canonical Alias", - ), - subtitle: SelectableText( - summary.canonicalAlias ?? summary.roomId, - ), - leading: Icon(Icons.numbers), + title: Text("Room ID"), + subtitle: SelectableText(summary.roomId), + leading: Icon(Icons.badge), ), - if (summary.topic != null) + + if (summary.topic case final topic?) ListTile( title: Text("Topic"), - subtitle: LinkifiedText(summary.topic!), + subtitle: LinkifiedText(topic, roomId: summary.roomId), leading: Icon(Icons.info), ), if (isKnocking) diff --git a/lib/widgets/room_title.dart b/lib/widgets/rooms/room_title.dart similarity index 100% rename from lib/widgets/room_title.dart rename to lib/widgets/rooms/room_title.dart diff --git a/lib/widgets/space_hierarchy_sheet.dart b/lib/widgets/rooms/space_hierarchy_sheet.dart similarity index 56% rename from lib/widgets/space_hierarchy_sheet.dart rename to lib/widgets/rooms/space_hierarchy_sheet.dart index 33a891d..65fb5da 100644 --- a/lib/widgets/space_hierarchy_sheet.dart +++ b/lib/widgets/rooms/space_hierarchy_sheet.dart @@ -3,21 +3,26 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/power_level.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/space_hierarchy.dart"; import "package:nexus/helpers/extensions/better_when.dart"; import "package:nexus/helpers/extensions/join_room.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; +import "package:nexus/helpers/extensions/room_summary_display.dart"; import "package:nexus/helpers/extensions/show_leave_room_sheet.dart"; +import "package:nexus/helpers/extensions/with_progress_snackbar.dart"; import "package:nexus/main.dart"; +import "package:nexus/models/content/content.dart"; import "package:nexus/models/content/create.dart"; import "package:nexus/models/space_hierarchy.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; -import "package:nexus/widgets/expandable_image.dart"; -import "package:nexus/widgets/knock_sheet.dart"; -import "package:nexus/widgets/loading.dart"; -import "package:nexus/widgets/room_summary_sheet.dart"; -import "package:nexus/widgets/sheet_layout.dart"; +import "package:nexus/widgets/rooms/add_space_rooms_sheet.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/common/expandable_image.dart"; +import "package:nexus/widgets/rooms/knock_sheet.dart"; +import "package:nexus/widgets/common/loading.dart"; +import "package:nexus/widgets/rooms/room_summary_sheet.dart"; class const SpaceHierarchySheet(final String spaceId, {super.key}) extends ConsumerWidget { @@ -64,6 +69,81 @@ class const SpaceHierarchySheet(final String spaceId, {super.key}) child: const Text("Join"), ); + Widget removeButton( + String spaceId, + String roomId, { + required String name, + required String spaceName, + }) => Consumer( + builder: (context, ref, _) { + final mutation = SpaceHierarchyController.removeChildMutation(( + spaceId, + roomId, + )); + if (ref.watch(mutation).isPending) { + return const Padding( + padding: .all(12), + child: SizedBox.square( + dimension: 24, + child: CircularProgressIndicator(), + ), + ); + } + + return IconButton( + tooltip: "Remove from space", + icon: const Icon(Icons.remove_circle_outline), + onPressed: () => context.showAdaptiveSheet( + (context) => SheetLayout( + title: const Text("Remove Room"), + actions: [ + TextButton( + onPressed: Navigator.of(context).pop, + child: const Text("Cancel"), + ), + TextButton( + onPressed: () { + final container = ProviderScope.containerOf(context); + mutation.run( + container, + (_) => context.withProgressSnackbar( + "Removing $name from $spaceName...", + () async { + await container + .read(ClientController.provider.notifier) + .setState( + .new( + roomId: spaceId, + type: EventType.spaceChild.type, + stateKey: roomId, + content: const Content(), + ), + ); + container.invalidate( + SpaceHierarchyController.provider(spaceId), + ); + }, + ), + ); + Navigator.of(context).pop(); + }, + style: TextButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.error, + ), + child: const Text("Remove"), + ), + ], + children: [ + Text( + "Are you sure you want to remove \"$name\" from \"$spaceName\"? Its members will stay in it.", + ), + ], + ), + ), + ); + }, + ); + Widget level( String spaceId, SpaceHierarchy hierarchy, @@ -71,11 +151,20 @@ class const SpaceHierarchySheet(final String spaceId, {super.key}) ) => HookConsumer( builder: (context, ref, _) { final loadingMore = useState(false); + final adding = ref + .watch(SpaceHierarchyController.addChildrenMutation(spaceId)) + .isPending; + final canManage = ref.watch( + PowerLevelController.provider( + .state(eventType: .spaceChild, roomId: spaceId), + ), + ); final byId = IMap.fromValues( keyMapper: (room) => room.summary.roomId, values: hierarchy.rooms, ); + final spaceName = byId[spaceId]?.summary.displayName ?? "Unnamed Space"; final children = (byId[spaceId]?.children ?? const .empty()) .map( (child) => switch (byId[child.roomId]) { @@ -106,16 +195,13 @@ class const SpaceHierarchySheet(final String spaceId, {super.key}) Builder( builder: (context) { final summary = room.summary; - final name = - summary.name ?? - summary.canonicalAlias ?? - "Unnamed Room"; + final name = summary.displayName; return ListTile( leading: AvatarOrHash( summary.avatarUrl, name, - fallback: const Icon(Icons.numbers), + fallback: Icon(summary.icon), ), title: Text(name, maxLines: 1, overflow: .ellipsis), subtitle: summary.topic == null @@ -126,7 +212,19 @@ class const SpaceHierarchySheet(final String spaceId, {super.key}) overflow: .ellipsis, ), onTap: () => showSummary(room, child), - trailing: membershipButton(room, child, name: name), + trailing: Row( + mainAxisSize: .min, + children: [ + membershipButton(room, child, name: name), + if (canManage) + removeButton( + spaceId, + summary.roomId, + name: name, + spaceName: spaceName, + ), + ], + ), ); }, ), @@ -136,10 +234,7 @@ class const SpaceHierarchySheet(final String spaceId, {super.key}) builder: (context, ref, _) { final expanded = useState(false); final summary = room.summary; - final name = - summary.name ?? - summary.canonicalAlias ?? - "Unnamed Space"; + final name = summary.displayName; final joined = joinedIds.contains(summary.roomId); return Column( @@ -152,7 +247,7 @@ class const SpaceHierarchySheet(final String spaceId, {super.key}) leading: AvatarOrHash( summary.avatarUrl, name, - fallback: const Icon(Icons.workspaces), + fallback: Icon(summary.icon), ), title: Text(name, maxLines: 1, overflow: .ellipsis), subtitle: summary.topic == null @@ -172,6 +267,13 @@ class const SpaceHierarchySheet(final String spaceId, {super.key}) child: const Icon(Icons.expand_more), ), membershipButton(room, child, name: name), + if (canManage) + removeButton( + spaceId, + summary.roomId, + name: name, + spaceName: spaceName, + ), ], ), ), @@ -190,6 +292,7 @@ class const SpaceHierarchySheet(final String spaceId, {super.key}) ), ) .betterWhen( + skipLoadingOnRefresh: true, loading: () => const Loading(dimension: 24), data: (hierarchy) => level( @@ -205,24 +308,51 @@ class const SpaceHierarchySheet(final String spaceId, {super.key}) ); }, ), - if (hierarchy.nextBatch != null) - Center( - child: TextButton( - onPressed: loadingMore.value - ? null - : () async { - loadingMore.value = true; - await ref - .read( - SpaceHierarchyController.provider(spaceId) - .notifier, - ) - .loadMore() - .onError(showError); - if (context.mounted) loadingMore.value = false; - }, - child: const Text("Load more"), - ), + if (hierarchy.nextBatch != null || canManage) + Row( + mainAxisAlignment: .center, + spacing: 8, + children: [ + if (hierarchy.nextBatch != null) + TextButton( + onPressed: loadingMore.value + ? null + : () async { + loadingMore.value = true; + await ref + .read( + SpaceHierarchyController.provider(spaceId) + .notifier, + ) + .loadMore() + .onError(showError); + if (context.mounted) loadingMore.value = false; + }, + child: const Text("Load more"), + ), + if (canManage) + TextButton.icon( + onPressed: adding + ? null + : () => context.showAdaptiveSheet( + (_) => AddSpaceRoomsSheet( + spaceId, + spaceName: spaceName, + existing: + (byId[spaceId]?.children ?? const .empty()) + .map((child) => child.roomId) + .toISet(), + ), + ), + icon: adding + ? const SizedBox.square( + dimension: 18, + child: CircularProgressIndicator(), + ) + : const Icon(Icons.add), + label: const Text("Add rooms"), + ), + ], ), ], ); @@ -232,6 +362,7 @@ class const SpaceHierarchySheet(final String spaceId, {super.key}) return ref .watch(SpaceHierarchyController.provider(spaceId)) .betterWhen( + skipLoadingOnRefresh: true, data: (hierarchy) { final space = hierarchy.rooms .where((room) => room.summary.roomId == spaceId) @@ -251,7 +382,7 @@ class const SpaceHierarchySheet(final String spaceId, {super.key}) ), Expanded( child: Text( - space?.name ?? space?.canonicalAlias ?? "Unnamed Space", + space?.displayName ?? "Unnamed Space", overflow: .ellipsis, maxLines: 3, ), diff --git a/lib/widgets/settings/add_users_power_level_sheet.dart b/lib/widgets/settings/add_users_power_level_sheet.dart index 2603fd5..b406414 100644 --- a/lib/widgets/settings/add_users_power_level_sheet.dart +++ b/lib/widgets/settings/add_users_power_level_sheet.dart @@ -1,15 +1,9 @@ -import "package:collection/collection.dart"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_hooks/flutter_hooks.dart"; -import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; -import "package:nexus/controllers/members.dart"; -import "package:nexus/helpers/extensions/get_localpart.dart"; -import "package:nexus/models/content/membership.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/widgets/settings/member_chooser.dart"; import "package:nexus/widgets/settings/power_level_field.dart"; -import "package:nexus/widgets/settings/search_chooser.dart"; -import "package:nexus/widgets/sheet_layout.dart"; /// Chooses users of [roomId] to give a power level of their own. class const AddUsersPowerLevelSheet({ @@ -22,43 +16,16 @@ class const AddUsersPowerLevelSheet({ required final double ownLevel, required final void Function(ISet users, int level) onSave, super.key, -}) extends HookConsumerWidget { +}) extends HookWidget { @override - Widget build(BuildContext context, WidgetRef ref) { + Widget build(BuildContext context) { final chosen = useState(const ISet.empty()); - final error = useState(null); - final searchController = useTextEditingController(); final levelController = useTextEditingController(text: "0"); final level = PowerLevelField.levelFrom( useValueListenable(levelController).text, ownLevel, ); - final members = IMap.fromEntries( - (ref.watch(MembersController.provider(roomId)).value ?? - const ISet.empty()) - .map( - (event) => switch ((event.stateKey, event.content)) { - (final userId?, final MembershipContent content) - when content.status == .join || content.status == .invite => - MapEntry(userId, content), - _ => null, - }, - ) - .nonNulls, - ); - - String nameOf(String id) => members[id]?.displayName ?? id.localpart; - - void add(String id) { - if (existing.contains(id)) { - error.value = "Already has a power level"; - return; - } - chosen.value = chosen.value.add(id); - searchController.clear(); - } - final valid = chosen.value.isNotEmpty && level != null; void save() { Navigator.of(context).pop(); @@ -72,33 +39,15 @@ class const AddUsersPowerLevelSheet({ TextButton(onPressed: valid ? save : null, child: Text("Save")), ], children: [ - SearchChooser( - controller: searchController, + MemberChooser( + roomId: roomId, chosen: chosen.value, - options: members.keys - .where((id) => !existing.contains(id)) - .sortedBy((id) => nameOf(id).toLowerCase()) - .toIList(), - nameOf: nameOf, - avatarOf: (id) => - AvatarOrHash(members[id]?.avatarUrl, nameOf(id), dimension: 40), - subtitleOf: (id) => id, - onAdded: add, + excluded: existing, + excludedError: "Already has a power level", + onAdded: (id) => chosen.value = chosen.value.add(id), onRemoved: (id) => chosen.value = chosen.value.remove(id), - onSubmitted: (text, topMatch) { - if (RegExp(r"^@[^:]+:.+$").hasMatch(text)) { - add(text); - } else if (topMatch != null) { - add(topMatch); - } else { - error.value = "Enter a user ID"; - } - }, - onChanged: (_) => error.value = null, label: "Add user", - hint: "Search members, or enter a user ID", removeTooltip: "Remove user", - error: error.value, autofocus: true, ), PowerLevelField( diff --git a/lib/widgets/settings/aliases_sheet.dart b/lib/widgets/settings/aliases_sheet.dart index d517f98..2eec533 100644 --- a/lib/widgets/settings/aliases_sheet.dart +++ b/lib/widgets/settings/aliases_sheet.dart @@ -1,7 +1,7 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:material_ui/material_ui.dart"; -import "package:nexus/widgets/sheet_layout.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; /// Chooses which of a room's [aliases] it publishes, and which one of those is canonical. class const AliasesSheet({ diff --git a/lib/widgets/settings/allowed_rooms_sheet.dart b/lib/widgets/settings/allowed_rooms_sheet.dart index 6ba42fb..63aac8b 100644 --- a/lib/widgets/settings/allowed_rooms_sheet.dart +++ b/lib/widgets/settings/allowed_rooms_sheet.dart @@ -3,12 +3,12 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/main.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; import "package:nexus/widgets/settings/search_chooser.dart"; -import "package:nexus/widgets/sheet_layout.dart"; /// Chooses the rooms whose members can join [roomId] without an invite. class const AllowedRoomsSheet({ diff --git a/lib/widgets/settings/block_user_field.dart b/lib/widgets/settings/block_user_field.dart new file mode 100644 index 0000000..ad0a829 --- /dev/null +++ b/lib/widgets/settings/block_user_field.dart @@ -0,0 +1,66 @@ +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/account_data.dart"; +import "package:nexus/controllers/client_state.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/helpers/hooks/saving.dart"; +import "package:nexus/main.dart"; + +/// Blocks a user by their ID, hiding their messages and invites. +class const BlockUserField({super.key}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final saving = Saving.use(); + final controller = useTextEditingController(); + final userId = useValueListenable(controller).text.trim(); + final blocked = ref.watch( + AccountDataController.provider.select( + (data) => data.ignoredUserList.contains(userId), + ), + ); + final ownId = ref.watch( + ClientStateController.provider.select((state) => state?.userId), + ); + + final error = userId.isEmpty || userId.isValidUserId + ? userId == ownId + ? "You can't block yourself" + : blocked + ? "Already blocked" + : null + : "Enter a user ID, like @user:example.com"; + final canBlock = userId.isNotEmpty && error == null && !saving.active; + + void block() { + if (!canBlock) return; + saving + .run(() async { + await ref + .read(AccountDataController.provider.notifier) + .setIgnored(userId, ignored: true); + if (context.mounted) controller.clear(); + }) + .onError(showError); + } + + return Padding( + padding: EdgeInsets.symmetric(horizontal: 8).copyWith(top: 8), + child: TextField( + controller: controller, + enabled: !saving.active, + onSubmitted: (_) => block(), + decoration: .new( + labelText: "User ID", + hintText: "@user:example.com", + errorText: error, + suffixIcon: IconButton( + tooltip: "Block user", + icon: Icon(Icons.block), + onPressed: canBlock ? block : null, + ), + ), + ), + ); + } +} diff --git a/lib/widgets/settings/dialog_list_tile.dart b/lib/widgets/settings/dialog_list_tile.dart index b31182f..2c9e5de 100644 --- a/lib/widgets/settings/dialog_list_tile.dart +++ b/lib/widgets/settings/dialog_list_tile.dart @@ -2,7 +2,7 @@ import "dart:async"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/helpers/hooks/saving.dart"; import "package:nexus/widgets/settings/radio_sheet.dart"; @@ -42,7 +42,7 @@ final class const DialogListTile({ child: Chip( label: Text( value is T ? getName(value as T) : "None", - overflow: TextOverflow.ellipsis, + overflow: .ellipsis, style: onChanged == null || saving.active ? .new(color: Colors.grey) : null, diff --git a/lib/widgets/settings/enable_image_packs_sheet.dart b/lib/widgets/settings/enable_image_packs_sheet.dart new file mode 100644 index 0000000..427f7d8 --- /dev/null +++ b/lib/widgets/settings/enable_image_packs_sheet.dart @@ -0,0 +1,118 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/room_image_packs.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/better_when.dart"; +import "package:nexus/models/account_data.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/avatars/image_pack_avatar.dart"; + +/// Chooses a room, then which of its image packs to use in every room. +class const EnableImagePacksSheet({ + required final ImagePackRooms enabled, + required final void Function(ImagePackRooms enabled) onSave, + super.key, +}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final chosen = useState(enabled); + final roomId = useState(null); + final rooms = ref.watch( + RoomsController.provider.select( + (rooms) => rooms.values + .map((room) => room.metadata) + .nonNulls + .map( + (metadata) => ( + id: metadata.id, + name: metadata.name ?? metadata.id, + avatar: metadata.avatar, + ), + ) + .sortedBy((room) => room.name.toLowerCase()) + .toIList(), + ), + ); + + return SheetLayout( + title: Text("Add Image Packs"), + actions: [ + TextButton(onPressed: Navigator.of(context).pop, child: Text("Cancel")), + TextButton( + onPressed: () { + Navigator.of(context).pop(); + onSave(chosen.value); + }, + child: Text("Save"), + ), + ], + children: [ + Text("Packs you add can be used in every room."), + DropdownMenu( + expandedInsets: .zero, + menuHeight: 300, + enableFilter: true, + requestFocusOnTap: true, + label: Text("Room"), + onSelected: (id) => roomId.value = id, + dropdownMenuEntries: rooms + .map( + (room) => DropdownMenuEntry( + value: room.id, + label: room.name, + leadingIcon: AvatarOrHash( + room.avatar, + room.name, + fallback: Icon(Icons.numbers), + ), + ), + ) + .toList(), + ), + AnimatedSize( + duration: Durations.medium2, + curve: Curves.easeInOut, + alignment: .topCenter, + child: switch (roomId.value) { + final roomId? => + ref + .watch(RoomImagePacksController.provider(roomId)) + .betterWhen( + data: (packs) => packs.isEmpty + ? Text("This room has no image packs") + : Column( + mainAxisSize: .min, + children: packs.entries + .map( + (entry) => CheckboxListTile( + secondary: ImagePackAvatar( + entry.value.icon, + ), + title: Text(entry.value.name), + subtitle: Text(entry.value.imageCountLabel), + value: chosen.value.contains( + roomId, + entry.key, + ), + onChanged: (value) => + chosen.value = chosen.value.withPack( + roomId, + entry.key, + enabled: value ?? false, + ), + ), + ) + .toList(), + ), + ), + null => const SizedBox(width: .infinity), + }, + ), + ], + ); + } +} diff --git a/lib/widgets/settings/image_pack_sheet.dart b/lib/widgets/settings/image_pack_sheet.dart new file mode 100644 index 0000000..d18d3f6 --- /dev/null +++ b/lib/widgets/settings/image_pack_sheet.dart @@ -0,0 +1,249 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/helpers/file_dialog_helper.dart"; +import "package:nexus/helpers/hooks/saving.dart"; +import "package:nexus/main.dart"; +import "package:nexus/models/content/image_pack.dart"; +import "package:nexus/models/content/message.dart"; +import "package:nexus/widgets/avatars/image_pack_avatar.dart"; +import "package:nexus/widgets/emoji/mxc_emoji.dart"; +import "package:nexus/widgets/settings/image_usage_chips.dart"; +import "package:nexus/widgets/settings/pack_image_sheet.dart"; + +/// Edits an image pack, or only shows it if [onSave] is null. +class const ImagePackSheet({ + required final String title, + required final ImagePackContent content, + required final void Function(ImagePackContent content)? onSave, + final VoidCallback? onDeleted, + + super.key, +}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final editable = onSave != null; + final nameController = useTextEditingController( + text: content.pack?.displayName, + ); + final name = useValueListenable(nameController).text.trim(); + final avatar = useState(content.pack?.avatarUrl); + final usage = useState(content.pack?.usage ?? const ISet.empty()); + final images = useState(content.images); + final uploading = Saving.use(); + final packUsage = usage.value.isEmpty + ? ISet(ImageUsage.values) + : usage.value; + final valid = !uploading.active && name.isNotEmpty; + + Future upload( + void Function(String filename, PackImage image) onUploaded, + ) async { + final file = await ref + .read(FileDialogHelper.provider) + .pickFile(images: true); + if (file == null || !context.mounted) return; + + await uploading.run(() async { + final content = await ref + .read(ClientController.provider.notifier) + .uploadMedia(.new(path: file.path, encrypt: false)); + if (!context.mounted) return; + + if (content case ImageMessageContent(:final url, :final info)) { + onUploaded(file.name, PackImage(url: url, info: info)); + } else { + throw Exception("The file isn't an image"); + } + }); + } + + void editImage(String shortcode, PackImage image, {bool isNew = false}) => + context.showAdaptiveSheet( + (_) => PackImageSheet( + title: isNew + ? "Add Image" + : editable + ? "Edit Image" + : ":$shortcode:", + shortcode: shortcode, + image: image, + taken: isNew + ? images.value.keys.toISet() + : images.value.keys.toISet().remove(shortcode), + packUsage: packUsage, + onSave: editable + ? (newShortcode, newImage) => images.value = isNew + ? images.value.add(newShortcode, newImage) + // Replaced in place, to keep the images' order + : .fromEntries( + images.value.entries.map( + (entry) => entry.key == shortcode + ? MapEntry(newShortcode, newImage) + : entry, + ), + ) + : null, + onRemoved: editable && !isNew + ? () => images.value = images.value.remove(shortcode) + : null, + ), + ); + + Future delete() async { + final confirmed = await context.showAdaptiveSheet( + (context) => SheetLayout( + title: Text("Delete Pack"), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text("Cancel"), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + style: TextButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.error, + ), + child: Text("Delete"), + ), + ], + children: [ + Text( + "Delete this pack? Its images will no longer be available here, or to anyone using it in other rooms.", + ), + ], + ), + ); + if (confirmed != true || !context.mounted) return; + + Navigator.of(context).pop(); + onDeleted?.call(); + } + + void save() { + Navigator.of(context).pop(); + onSave!( + content.copyWith( + images: images.value, + pack: (content.pack ?? const PackInfo()).copyWith( + displayName: name, + avatarUrl: avatar.value, + usage: usage.value, + ), + ), + ); + } + + final textTheme = Theme.of(context).textTheme; + + return SheetLayout( + title: Text(title), + actions: [ + if (onDeleted != null) + TextButton( + onPressed: uploading.active ? null : delete, + style: TextButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.error, + ), + child: Text("Delete"), + ), + TextButton( + onPressed: Navigator.of(context).pop, + child: Text(editable ? "Cancel" : "Close"), + ), + if (editable) + TextButton(onPressed: valid ? save : null, child: Text("Save")), + ], + children: [ + TextField( + controller: nameController, + enabled: editable, + autofocus: true, + decoration: .new(labelText: "Name"), + ), + ListTile( + enabled: editable && !uploading.active, + leading: Icon(Icons.image), + title: Text("Avatar"), + subtitle: Text("The pack's first image if not set."), + trailing: Row( + mainAxisSize: .min, + spacing: 8, + children: [ + ImagePackAvatar( + avatar.value ?? images.value.values.firstOrNull?.url, + ), + if (avatar.value != null && editable) + IconButton( + tooltip: "Remove avatar", + icon: Icon(Icons.delete), + onPressed: uploading.active + ? null + : () => avatar.value = null, + ), + ], + ), + onTap: () => + upload((_, image) => avatar.value = image.url).onError(showError), + ), + Text("Default usage", style: textTheme.titleSmall), + ImageUsageChips( + value: packUsage, + onChanged: editable + ? (value) => + usage.value = value.length == ImageUsage.values.length + ? const .empty() + : value + : null, + ), + Text("Images", style: textTheme.titleSmall), + if (images.value.isEmpty && !editable) Text("No images"), + Wrap( + spacing: 4, + runSpacing: 4, + children: [ + ...images.value.entries.map( + (entry) => Tooltip( + message: ":${entry.key}:", + child: InkWell( + borderRadius: .circular(8), + onTap: () => editImage(entry.key, entry.value), + child: Padding( + padding: .all(4), + child: SizedBox.square( + dimension: 56, + child: MxcEmoji(entry.value.url, label: entry.key), + ), + ), + ), + ), + ), + if (editable) + SizedBox.square( + dimension: 64, + child: uploading.active + ? Center(child: CircularProgressIndicator()) + : IconButton( + tooltip: "Add image", + icon: Icon(Icons.add_photo_alternate), + onPressed: () => upload( + (filename, image) => editImage( + filename + .split(".") + .first + .replaceAll(RegExp(r"[^\w-]"), ""), + image, + isNew: true, + ), + ).onError(showError), + ), + ), + ], + ), + ], + ); + } +} diff --git a/lib/widgets/settings/image_usage_chips.dart b/lib/widgets/settings/image_usage_chips.dart new file mode 100644 index 0000000..e9d1fbb --- /dev/null +++ b/lib/widgets/settings/image_usage_chips.dart @@ -0,0 +1,38 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/models/content/image_pack.dart"; + +/// Chooses what images are used as, keeping at least one usage chosen. +class const ImageUsageChips({ + required final ISet value, + + /// Disables the chips if null. + required final void Function(ISet value)? onChanged, + super.key, +}) extends StatelessWidget { + static String nameOf(ImageUsage usage) => switch (usage) { + .emoticon => "Emoticons", + .sticker => "Stickers", + }; + + @override + Widget build(BuildContext context) => Wrap( + spacing: 8, + runSpacing: 8, + children: ImageUsage.values + .map( + (usage) => FilterChip( + label: Text(nameOf(usage)), + selected: value.contains(usage), + onSelected: + onChanged == null || + (value.length == 1 && value.contains(usage)) + ? null + : (selected) => onChanged!( + selected ? value.add(usage) : value.remove(usage), + ), + ), + ) + .toList(), + ); +} diff --git a/lib/widgets/settings/keyword_field.dart b/lib/widgets/settings/keyword_field.dart new file mode 100644 index 0000000..3d4ee61 --- /dev/null +++ b/lib/widgets/settings/keyword_field.dart @@ -0,0 +1,70 @@ +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/account_data.dart"; +import "package:nexus/helpers/hooks/saving.dart"; +import "package:nexus/main.dart"; + +/// Adds a keyword, which notifies with a highlight and sound for messages +/// containing it. +class const KeywordField({super.key}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final saving = Saving.use(); + final controller = useTextEditingController(); + final keyword = useValueListenable(controller).text.trim(); + final exists = ref.watch( + AccountDataController.provider.select( + (data) => data.pushRules.global.find(.content, keyword) != null, + ), + ); + + // Keywords are their rules' IDs, which can't be like these + final error = keyword.startsWith(".") + ? "Can't start with a ." + : keyword.contains(RegExp(r"[/\\]")) + ? r"Can't contain / or \" + : exists + ? "Already a keyword" + : null; + final canAdd = keyword.isNotEmpty && error == null && !saving.active; + + void add() { + if (!canAdd) return; + saving + .run(() async { + await ref + .read(AccountDataController.provider.notifier) + .savePushRule( + .content, + .new( + ruleId: keyword, + pattern: keyword, + actions: .highlightWithSound, + ), + ); + if (context.mounted) controller.clear(); + }) + .onError(showError); + } + + return Padding( + padding: .symmetric(horizontal: 16), + child: TextField( + controller: controller, + enabled: !saving.active, + onSubmitted: (_) => add(), + decoration: .new( + labelText: "New keyword", + helperText: "Matches whole words. * matches anything, and ? matches one character.", + errorText: error, + suffixIcon: IconButton( + tooltip: "Add keyword", + icon: Icon(Icons.add), + onPressed: canAdd ? add : null, + ), + ), + ), + ); + } +} diff --git a/lib/widgets/settings/local_aliases_sheet.dart b/lib/widgets/settings/local_aliases_sheet.dart index def7db9..b51b7c3 100644 --- a/lib/widgets/settings/local_aliases_sheet.dart +++ b/lib/widgets/settings/local_aliases_sheet.dart @@ -1,13 +1,13 @@ import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/controllers/local_aliases.dart"; import "package:nexus/helpers/extensions/better_when.dart"; import "package:nexus/helpers/hooks/saving.dart"; import "package:nexus/main.dart"; import "package:nexus/models/gomuks_exception.dart"; -import "package:nexus/widgets/sheet_layout.dart"; class const LocalAliasesSheet( final String roomId, { diff --git a/lib/widgets/settings/member_chooser.dart b/lib/widgets/settings/member_chooser.dart new file mode 100644 index 0000000..fbaaa8e --- /dev/null +++ b/lib/widgets/settings/member_chooser.dart @@ -0,0 +1,91 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/members.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/models/content/membership.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/settings/search_chooser.dart"; + +/// The [chosen] users, above a field searching [roomId]'s members, or taking a user ID, to choose more. +class const MemberChooser({ + required final String roomId, + required final ISet chosen, + required final void Function(String userId) onAdded, + required final void Function(String userId) onRemoved, + required final String label, + required final String removeTooltip, + + /// Users who can't be chosen, so aren't suggested. + final ISet excluded = const .empty(), + + /// Shown when trying to choose one of the [excluded] users. + final String excludedError = "Can't be chosen", + final String? emptyText, + final bool autofocus = false, + super.key, +}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final error = useState(null); + final searchController = useTextEditingController(); + + final members = IMap.fromEntries( + (ref.watch(MembersController.provider(roomId)).value ?? + const ISet.empty()) + .map( + (event) => switch ((event.stateKey, event.content)) { + (final userId?, final MembershipContent content) + when content.status == .join || content.status == .invite => + MapEntry(userId, content), + _ => null, + }, + ) + .nonNulls, + ); + + String nameOf(String id) => members[id]?.displayName ?? id.localpart; + + void add(String id) { + if (excluded.contains(id)) { + error.value = excludedError; + return; + } + onAdded(id); + searchController.clear(); + } + + return SearchChooser( + controller: searchController, + chosen: chosen, + options: members.keys + .where((id) => !excluded.contains(id)) + .sortedBy((id) => nameOf(id).toLowerCase()) + .toIList(), + nameOf: nameOf, + avatarOf: (id) => + AvatarOrHash(members[id]?.avatarUrl, nameOf(id), dimension: 40), + subtitleOf: (id) => id, + onAdded: add, + onRemoved: onRemoved, + onSubmitted: (text, topMatch) { + if (RegExp(r"^@[^:]+:.+$").hasMatch(text)) { + add(text); + } else if (topMatch != null) { + add(topMatch); + } else { + error.value = "Enter a user ID"; + } + }, + onChanged: (_) => error.value = null, + label: label, + hint: "Search members, or enter a user ID", + removeTooltip: removeTooltip, + emptyText: emptyText, + error: error.value, + autofocus: autofocus, + ); + } +} diff --git a/lib/widgets/settings/pack_image_sheet.dart b/lib/widgets/settings/pack_image_sheet.dart new file mode 100644 index 0000000..89ed4f7 --- /dev/null +++ b/lib/widgets/settings/pack_image_sheet.dart @@ -0,0 +1,134 @@ +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/models/content/image_pack.dart"; +import "package:nexus/widgets/emoji/mxc_emoji.dart"; +import "package:nexus/widgets/settings/image_usage_chips.dart"; + +/// Edits an image in a pack, or only shows it if [onSave] is null. +class const PackImageSheet({ + required final String title, + required final String shortcode, + required final PackImage image, + + /// The other images' shortcodes, which this one can't also have. + required final ISet taken, + + /// The pack's default usage, which images have unless they set their own. + required final ISet packUsage, + required final void Function(String shortcode, PackImage image)? onSave, + final VoidCallback? onRemoved, + super.key, +}) extends HookWidget { + static final shortcodePattern = RegExp(r"^[\w-]+$"); + + @override + Widget build(BuildContext context) { + final shortcodeController = useTextEditingController(text: shortcode); + final bodyController = useTextEditingController(text: image.body); + final usage = useState(image.usage); + final newShortcode = useValueListenable(shortcodeController).text.trim(); + final error = taken.contains(newShortcode) + ? "Another image has this shortcode" + : newShortcode.isNotEmpty && !shortcodePattern.hasMatch(newShortcode) + ? "Only letters, numbers, - and _ are allowed" + : null; + final valid = newShortcode.isNotEmpty && error == null; + + void save() { + final body = bodyController.text.trim(); + Navigator.of(context).pop(); + onSave!( + newShortcode, + image.copyWith(body: body.isEmpty ? null : body, usage: usage.value), + ); + } + + return SheetLayout( + title: Text(title), + actions: [ + if (onRemoved case final onRemoved?) + TextButton( + onPressed: () { + Navigator.of(context).pop(); + onRemoved(); + }, + style: TextButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.error, + ), + child: Text("Remove"), + ), + TextButton( + onPressed: Navigator.of(context).pop, + child: Text(onSave == null ? "Close" : "Cancel"), + ), + if (onSave != null) + TextButton(onPressed: valid ? save : null, child: Text("Save")), + ], + children: [ + Center( + child: SizedBox.square( + dimension: 128, + child: MxcEmoji(image.url, label: shortcode), + ), + ), + TextField( + controller: shortcodeController, + enabled: onSave != null, + onSubmitted: valid ? (_) => save() : null, + decoration: .new( + labelText: "Shortcode", + prefixText: ":", + suffixText: ":", + errorText: error, + ), + ), + TextField( + controller: bodyController, + enabled: onSave != null, + onSubmitted: valid ? (_) => save() : null, + decoration: .new( + labelText: "Description", + hintText: "Read by screen readers", + ), + ), + Column( + mainAxisSize: .min, + crossAxisAlignment: .stretch, + children: [ + SwitchListTile( + title: Text("Custom usage"), + subtitle: Text( + usage.value.isEmpty + ? "Same as the pack's default (${packUsage.map(ImageUsageChips.nameOf).join(", ")})" + : "Used as chosen below, instead of the pack's default", + ), + value: usage.value.isNotEmpty, + onChanged: onSave == null + ? null + : (custom) => + usage.value = custom ? packUsage : const .empty(), + ), + AnimatedSize( + duration: Durations.medium2, + curve: Curves.easeInOut, + alignment: .topCenter, + child: usage.value.isEmpty + ? const SizedBox(width: .infinity) + : Padding( + padding: .only(top: 8), + child: ImageUsageChips( + value: usage.value, + onChanged: onSave == null + ? null + : (value) => usage.value = value, + ), + ), + ), + ], + ), + ], + ); + } +} diff --git a/lib/widgets/settings/power_level_entry_sheet.dart b/lib/widgets/settings/power_level_entry_sheet.dart index 9d5e457..05b9831 100644 --- a/lib/widgets/settings/power_level_entry_sheet.dart +++ b/lib/widgets/settings/power_level_entry_sheet.dart @@ -1,7 +1,7 @@ import "package:flutter_hooks/flutter_hooks.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/widgets/settings/power_level_field.dart"; -import "package:nexus/widgets/sheet_layout.dart"; /// Gives something, like an event type, its own power level. class const PowerLevelEntrySheet({ diff --git a/lib/widgets/settings/power_level_tile.dart b/lib/widgets/settings/power_level_tile.dart index 5b7d4e6..e7df995 100644 --- a/lib/widgets/settings/power_level_tile.dart +++ b/lib/widgets/settings/power_level_tile.dart @@ -1,15 +1,16 @@ import "package:flutter_hooks/flutter_hooks.dart"; import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/widgets/settings/power_level_field.dart"; -import "package:nexus/widgets/sheet_layout.dart"; /// Sets the power level needed for something. class const PowerLevelTile({ required final Widget leading, required final String title, required final String? description, - required final int value, + + /// Null for several levels that differ, shown as custom. + required final int? value, /// The user's own power level, which they can't set or change levels above. required final double ownLevel, @@ -22,11 +23,14 @@ class const PowerLevelTile({ /// If given, asked before removing the level. final String? removeConfirmation, + + /// Shown after the level, like a button to expand what it sets. + final Widget? trailing, super.key, }) extends StatelessWidget { @override Widget build(BuildContext context) { - final enabled = onChanged != null && value <= ownLevel; + final enabled = onChanged != null && (value ?? 0) <= ownLevel; Future remove() async { if (removeConfirmation case final confirmation?) { @@ -65,7 +69,7 @@ class const PowerLevelTile({ children: [ Chip( label: Text( - "$value", + value?.toString() ?? "Custom", style: enabled ? null : .new(color: Colors.grey), ), ), @@ -75,12 +79,15 @@ class const PowerLevelTile({ icon: Icon(Icons.delete), onPressed: enabled ? remove : null, ), + ?trailing, ], ), onTap: () => context.showAdaptiveSheet( (context) => HookBuilder( builder: (context) { - final controller = useTextEditingController(text: "$value"); + final controller = useTextEditingController( + text: value?.toString(), + ); final level = PowerLevelField.levelFrom( useValueListenable(controller).text, ownLevel, diff --git a/lib/widgets/settings/radio_sheet.dart b/lib/widgets/settings/radio_sheet.dart index 9f9512e..2a58707 100644 --- a/lib/widgets/settings/radio_sheet.dart +++ b/lib/widgets/settings/radio_sheet.dart @@ -1,5 +1,5 @@ import "package:material_ui/material_ui.dart"; -import "package:nexus/widgets/sheet_layout.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:flutter_hooks/flutter_hooks.dart"; final class const RadioSheet({ @@ -36,7 +36,7 @@ final class const RadioSheet({ onChanged: (value) => chosen.value = (value as T,), child: Column( - mainAxisSize: MainAxisSize.min, + mainAxisSize: .min, children: options .map( (option) => RadioListTile( diff --git a/lib/widgets/settings/search_chooser.dart b/lib/widgets/settings/search_chooser.dart index feadcdd..f78d476 100644 --- a/lib/widgets/settings/search_chooser.dart +++ b/lib/widgets/settings/search_chooser.dart @@ -1,6 +1,7 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:material_ui/material_ui.dart"; +import "package:nexus/helpers/extensions/weighted_search.dart"; /// The [chosen] items, above a field searching [options] to choose more. class const SearchChooser({ @@ -30,15 +31,10 @@ class const SearchChooser({ }) extends HookWidget { @override Widget build(BuildContext context) { - final query = useValueListenable(controller).text.trim().toLowerCase(); + final query = useValueListenable(controller).text; final shown = options - .where( - (id) => - !chosen.contains(id) && - (nameOf(id).toLowerCase().contains(query) || - id.toLowerCase().contains(query)), - ) - .toIList(); + .where((id) => !chosen.contains(id)) + .search(query, (id) => [(nameOf(id), 2), (id, 1)]); ListTile tileOf(String id, {Widget? trailing, VoidCallback? onTap}) => ListTile( diff --git a/lib/widgets/settings/settings_layout.dart b/lib/widgets/settings/settings_layout.dart index 7f6c527..de20137 100644 --- a/lib/widgets/settings/settings_layout.dart +++ b/lib/widgets/settings/settings_layout.dart @@ -7,10 +7,12 @@ import "package:hooks_riverpod/misc.dart"; import "package:m3e_card_list/m3e_card_list.dart"; import "package:navigation_rail_m3e/navigation_rail_m3e.dart"; import "package:nexus/helpers/extensions/better_when.dart"; +import "package:nexus/helpers/extensions/weighted_search.dart"; import "package:nexus/models/settings_category.dart"; import "package:nexus/widgets/pages/settings_category.dart"; -import "package:nexus/widgets/divider_text.dart"; -import "package:nexus/widgets/highlight_wrapper.dart"; +import "package:nexus/widgets/common/divider_text.dart"; +import "package:nexus/widgets/common/highlight_wrapper.dart"; +import "package:nexus/widgets/common/m3e_rail_theme.dart"; import "package:super_sliver_list/super_sliver_list.dart"; /// A settings screen split into categories: a list of them that opens each @@ -43,32 +45,22 @@ class const SettingsLayout({ // Only searched once shown, by which point these have loaded final categories = ref.read(sectionsProvider).value ?? const IMap.empty(); - final query = controller.text.toLowerCase(); - final matches = categories.values.flattenedToList .asMap() .entries .expand( - (categoryEntry) => categoryEntry.value.settings - .asMap() - .entries - .where( - (settingEntry) => - settingEntry.value.title.toLowerCase().contains( - query, - ) || - settingEntry.value.description - .toLowerCase() - .contains(query), - ) - .map( + (categoryEntry) => + categoryEntry.value.settings.asMap().entries.map( (settingEntry) => ( (categoryEntry.key, settingEntry.key), settingEntry.value, ), ), ) - .toIList(); + .search( + controller.text, + (match) => [(match.$2.title, 2), (match.$2.description, 1)], + ); return matches.map( (match) => ListTile( @@ -179,8 +171,8 @@ class const SettingsLayout({ ) : Row( children: [ - MaterialUiCompatibilityBridge( - child: NavigationRailM3E( + M3ERailTheme( + builder: (_) => NavigationRailM3E( type: .alwaysExpand, trailing: searchBar, scrollable: true, diff --git a/lib/widgets/settings/text_setting_tile.dart b/lib/widgets/settings/text_setting_tile.dart index 6f97eb0..4789cc3 100644 --- a/lib/widgets/settings/text_setting_tile.dart +++ b/lib/widgets/settings/text_setting_tile.dart @@ -2,9 +2,8 @@ import "dart:async"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/helpers/hooks/saving.dart"; -import "package:nexus/widgets/sheet_layout.dart"; class const TextSettingTile({ required final Icon icon, diff --git a/lib/widgets/settings/upgrade_room_sheet.dart b/lib/widgets/settings/upgrade_room_sheet.dart new file mode 100644 index 0000000..a54325b --- /dev/null +++ b/lib/widgets/settings/upgrade_room_sheet.dart @@ -0,0 +1,100 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/capabilities.dart"; +import "package:nexus/helpers/extensions/better_when.dart"; +import "package:nexus/helpers/extensions/room_version_at_least.dart"; +import "package:nexus/widgets/settings/dialog_list_tile.dart"; +import "package:nexus/widgets/settings/member_chooser.dart"; + +/// Chooses a room version to upgrade [roomId] to, and its additional creators if the version has them. +class const UpgradeRoomSheet({ + required final String roomId, + required final String currentVersion, + + /// The room's current creators, other than the user, to keep in the new room. + required final ISet creators, + required final String? userId, + required final void Function(String version, ISet creators) onSave, + super.key, +}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final roomVersions = ref + .watch(CapabilitiesController.provider) + .whenData((capabilities) => capabilities.roomVersions); + final chosen = useState(null); + final chosenCreators = useState(creators); + + final versions = roomVersions.value; + final version = chosen.value ?? versions?.defaultVersion; + + final valid = version != null; + final withCreators = valid && version.versionAtLeast(12); + void save() { + Navigator.of(context).pop(); + onSave(version!, withCreators ? chosenCreators.value : const .empty()); + } + + return SheetLayout( + title: Text("Upgrade Room"), + actions: [ + TextButton(onPressed: Navigator.of(context).pop, child: Text("Cancel")), + TextButton(onPressed: valid ? save : null, child: Text("Upgrade")), + ], + children: [ + Text( + "Upgrading creates a new room with the chosen version and closes this one, pointing its members to the new room. Members will have to join the new room themselves.", + ), + roomVersions.betterWhen( + data: (versions) => versions == null + ? Text( + "Your homeserver didn't list the room versions it supports.", + ) + : DialogListTile( + icon: Icon(Icons.upgrade), + title: "Room Version", + subtitle: Text("The version the new room will have."), + value: version, + options: versions.available.keys.sortedBy( + (option) => int.tryParse(option) ?? double.infinity, + ), + getName: (option) => switch ([ + if (option == currentVersion) "current", + if (option == versions.defaultVersion) "default", + if (versions.available[option] == .unstable) "unstable", + ]) { + final labels when labels.isNotEmpty => + "$option (${labels.join(", ")})", + _ => option, + }, + onChanged: (value) => chosen.value = value, + ), + ), + AnimatedSize( + duration: Durations.medium2, + curve: Curves.easeInOut, + alignment: .topCenter, + child: withCreators + ? MemberChooser( + roomId: roomId, + chosen: chosenCreators.value, + excluded: ISet([?userId]), + excludedError: "You'll be a creator already", + onAdded: (id) => + chosenCreators.value = chosenCreators.value.add(id), + onRemoved: (id) => + chosenCreators.value = chosenCreators.value.remove(id), + label: "Add creator", + removeTooltip: "Remove creator", + emptyText: "Creators outrank everyone in the new room, and can't be demoted. You'll be one, and can add others.", + ) + : const SizedBox(width: .infinity), + ), + ], + ); + } +} diff --git a/lib/widgets/sheet_layout.dart b/lib/widgets/sheet_layout.dart deleted file mode 100644 index 9a15a1d..0000000 --- a/lib/widgets/sheet_layout.dart +++ /dev/null @@ -1,42 +0,0 @@ -import "package:material_ui/material_ui.dart"; - -class const SheetLayout({ - final Widget? title, - required final List children, - required final List actions, - super.key, -}) extends StatelessWidget { - @override - Widget build(BuildContext context) => Padding( - padding: .only(bottom: MediaQuery.viewInsetsOf(context).bottom), - child: Column( - mainAxisSize: .min, - crossAxisAlignment: .stretch, - children: [ - if (title case final title?) - Padding( - padding: const .fromLTRB(24, 24, 24, 0), - child: DefaultTextStyle( - style: Theme.of(context).textTheme.headlineSmall!, - child: title, - ), - ), - Flexible( - child: SingleChildScrollView( - padding: .fromLTRB(24, title == null ? 24 : 12, 24, 12), - child: Column( - mainAxisSize: .min, - crossAxisAlignment: .stretch, - spacing: 12, - children: children, - ), - ), - ), - Padding( - padding: const .fromLTRB(24, 0, 24, 24), - child: Row(mainAxisAlignment: .end, spacing: 8, children: actions), - ), - ], - ), - ); -} diff --git a/lib/widgets/sidebar/invite_card.dart b/lib/widgets/sidebar/invite_card.dart new file mode 100644 index 0000000..239d3c1 --- /dev/null +++ b/lib/widgets/sidebar/invite_card.dart @@ -0,0 +1,52 @@ +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/invites.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/helpers/extensions/room_summary_display.dart"; +import "package:nexus/models/room_summary.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/rooms/room_summary_sheet.dart"; + +class const InviteCard(final RoomSummary invite, {super.key}) + extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final responding = ref + .watch(InvitesController.respondMutation(invite.roomId)) + .isPending; + final name = invite.name ?? invite.canonicalAlias ?? invite.roomId; + final inviterName = + invite.inviterProfile?.displayName ?? invite.invitedBy?.localpart; + + return Card( + clipBehavior: .antiAlias, + child: ListTile( + onTap: responding + ? null + : () => context.showAdaptiveSheet((_) => RoomSummarySheet(invite)), + trailing: responding + ? const SizedBox.square( + dimension: 24, + child: CircularProgressIndicator(), + ) + : null, + leading: AvatarOrHash( + invite.avatarUrl, + name, + dimension: 40, + fallback: invite.isDirect ? null : Icon(invite.icon), + ), + title: Text(name, maxLines: 1, overflow: .ellipsis), + subtitle: Text( + [ + if (inviterName != null) + "${invite.isDirect ? "Direct message from" : "Invited by"} $inviterName", + ].join("\n"), + maxLines: 2, + overflow: .ellipsis, + ), + ), + ); + } +} diff --git a/lib/widgets/invites_list.dart b/lib/widgets/sidebar/invites_list.dart similarity index 53% rename from lib/widgets/invites_list.dart rename to lib/widgets/sidebar/invites_list.dart index f1be8f5..18fb5f0 100644 --- a/lib/widgets/invites_list.dart +++ b/lib/widgets/sidebar/invites_list.dart @@ -1,20 +1,12 @@ -import "package:flutter_hooks/flutter_hooks.dart"; +import "package:nexus/widgets/sidebar/invite_card.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; -import "package:nexus/widgets/sheet_layout.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/invites.dart"; -import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/main.dart"; -import "package:nexus/models/content/create.dart"; import "package:nexus/models/nav_page.dart"; -import "package:nexus/models/room_summary.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; -import "package:nexus/widgets/room_summary_sheet.dart"; -class const InvitesList({super.key}) - extends HookConsumerWidget - implements NavPage { +class const InvitesList({super.key}) extends ConsumerWidget implements NavPage { @override String get title => "Invites"; @@ -32,7 +24,9 @@ class const InvitesList({super.key}) @override Widget build(BuildContext context, WidgetRef ref) { final invites = ref.watch(InvitesController.provider); - final decliningAll = useState(false); + final decliningAll = ref + .watch(InvitesController.declineAllMutation) + .isPending; Future declineAll() async { final confirmed = await context.showAdaptiveSheet( @@ -57,12 +51,12 @@ class const InvitesList({super.key}) ); if (confirmed != true) return; - decliningAll.value = true; - await ref - .read(InvitesController.provider.notifier) - .declineAll() + await InvitesController.declineAllMutation + .run( + ref, + (_) => ref.read(InvitesController.provider.notifier).declineAll(), + ) .onError(showError); - if (context.mounted) decliningAll.value = false; } return Scaffold( @@ -70,8 +64,8 @@ class const InvitesList({super.key}) floatingActionButton: invites.isEmpty ? null : FloatingActionButton.extended( - onPressed: decliningAll.value ? null : declineAll, - icon: decliningAll.value + onPressed: decliningAll ? null : declineAll, + icon: decliningAll ? const SizedBox.square( dimension: 24, child: CircularProgressIndicator(), @@ -94,41 +88,3 @@ class const InvitesList({super.key}) ); } } - -class const InviteCard(final RoomSummary invite, {super.key}) - extends StatelessWidget { - @override - Widget build(BuildContext context) { - final name = invite.name ?? invite.canonicalAlias ?? invite.roomId; - final inviterName = - invite.inviterProfile?.displayName ?? invite.invitedBy?.localpart; - - return Card( - clipBehavior: .antiAlias, - child: ListTile( - onTap: () => context.showAdaptiveSheet((_) => RoomSummarySheet(invite)), - leading: AvatarOrHash( - invite.avatarUrl, - name, - dimension: 40, - fallback: invite.isDirect - ? null - : Icon( - invite.roomType == RoomType.space - ? Icons.workspaces - : Icons.numbers, - ), - ), - title: Text(name, maxLines: 1, overflow: .ellipsis), - subtitle: Text( - [ - if (inviterName != null) - "${invite.isDirect ? "Direct message from" : "Invited by"} $inviterName", - ].join("\n"), - maxLines: 2, - overflow: .ellipsis, - ), - ), - ); - } -} diff --git a/lib/widgets/notifications_list.dart b/lib/widgets/sidebar/notifications_list.dart similarity index 96% rename from lib/widgets/notifications_list.dart rename to lib/widgets/sidebar/notifications_list.dart index 0b0741f..f52f944 100644 --- a/lib/widgets/notifications_list.dart +++ b/lib/widgets/sidebar/notifications_list.dart @@ -9,9 +9,9 @@ import "package:nexus/controllers/notifications.dart"; import "package:nexus/helpers/extensions/focus_room.dart"; import "package:nexus/models/event.dart"; import "package:nexus/models/nav_page.dart"; -import "package:nexus/widgets/error_dialog.dart"; -import "package:nexus/widgets/highlight_wrapper.dart"; -import "package:nexus/widgets/loading.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/widgets/common/highlight_wrapper.dart"; +import "package:nexus/widgets/common/loading.dart"; import "package:nexus/widgets/renderers/event.dart"; import "package:super_sliver_list/super_sliver_list.dart"; @@ -151,7 +151,7 @@ class const NotificationsList({super.key}) listController: listController.value, controller: scrollController, itemCount: value.length, - padding: const EdgeInsets.symmetric( + padding: const .symmetric( horizontal: 8, vertical: 12, ), diff --git a/lib/widgets/sidebar/room_list.dart b/lib/widgets/sidebar/room_list.dart new file mode 100644 index 0000000..0e94cdb --- /dev/null +++ b/lib/widgets/sidebar/room_list.dart @@ -0,0 +1,59 @@ +import "package:nexus/widgets/sidebar/spaces_rail.dart"; +import "package:nexus/widgets/sidebar/rooms_pane.dart"; + +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/models/nav_page.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/controllers/spaces.dart"; + +class const RoomList({super.key}) extends ConsumerWidget implements NavPage { + @override + String get title => "Rooms"; + + @override + IconData get icon => Icons.list; + + @override + int? badgeCount(WidgetRef ref) { + final (notifications, hasUnread) = ref.watch( + RoomsController.provider.select( + (rooms) => rooms.values.fold( + (0, false), + (total, room) => ( + total.$1 + (room.metadata?.unreadNotifications ?? 0), + total.$2 || (room.metadata?.unreadMessages ?? 0) > 0, + ), + ), + ), + ); + + return notifications > 0 + ? notifications + : hasUnread + ? 0 + : null; + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final spacesAsync = ref.watch(SpacesController.provider); + if (spacesAsync.value == null) { + return switch (spacesAsync) { + AsyncError(:final error, :final stackTrace) => ErrorDialog( + error, + stackTrace, + ), + _ => const Center(child: CircularProgressIndicator()), + }; + } + + return const Row( + children: [ + SpacesRail(), + Expanded(child: RoomsPane()), + ], + ); + } +} diff --git a/lib/widgets/sidebar/rooms_pane.dart b/lib/widgets/sidebar/rooms_pane.dart new file mode 100644 index 0000000..aabebbb --- /dev/null +++ b/lib/widgets/sidebar/rooms_pane.dart @@ -0,0 +1,143 @@ +import "dart:math"; + +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:navigation_rail_m3e/navigation_rail_m3e.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/helpers/extensions/get_all_child_rooms.dart"; +import "package:nexus/helpers/extensions/room_destinations.dart"; +import "package:nexus/widgets/common/appbar.dart"; +import "package:nexus/widgets/rooms/room_title.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/common/divider_widget.dart"; +import "package:nexus/widgets/common/m3e_rail_theme.dart"; +import "package:nexus/widgets/rooms/room_summary_sheet.dart"; +import "package:nexus/widgets/rooms/room_menu_button.dart"; +import "package:nexus/widgets/rooms/space_hierarchy_sheet.dart"; +import "package:nexus/controllers/key.dart"; +import "package:nexus/controllers/selected_room.dart"; +import "package:nexus/controllers/selected_space.dart"; + +class const RoomsPane({super.key}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final selectedRoomId = ref.watch(SelectedRoomController.provider); + final selectedSpace = ref.watch(SelectedSpaceController.provider)!; + final isDm = selectedSpace.id == "dms"; + final spaceMetadata = selectedSpace.room?.metadata; + // In the order the rail shows them, with the space's own timeline first + final destinationIds = IList([?spaceMetadata?.id]) + .addAll(selectedSpace.allChildRooms.map((room) => room.metadata?.id)); + + return Scaffold( + backgroundColor: Colors.transparent, + appBar: Appbar( + // Home and DMs aren't real spaces, so they don't have a summary. + onTap: spaceMetadata == null + ? null + : () => context.showAdaptiveSheet( + (_) => RoomSummarySheet(.fromMetadata(spaceMetadata)), + ), + windowControls: false, + leading: AvatarOrHash( + spaceMetadata?.avatar, + fallback: selectedSpace.icon == null + ? null + : Icon(selectedSpace.icon), + selectedSpace.title, + ), + title: RoomTitle(selectedSpace.title, topic: spaceMetadata?.topic), + backgroundColor: Colors.transparent, + actions: .new([ + RoomMenuButton( + selectedSpace.room, + children: selectedSpace.allChildRooms, + ), + ]), + ), + body: M3ERailTheme( + extensions: [ + NavigationRailM3ETheme( + itemExpandedHeight: 48, + iconLabelGap: 16, + sectionHeaderSpacingTop: 0, + ), + ], + builder: (context) => Padding( + padding: const .only(top: 4), + child: NavigationRailM3E( + fab: selectedSpace.room == null + ? null + : .new( + icon: const Icon(Icons.explore), + label: "Browse space", + tooltip: "Browse and join rooms in this space", + onPressed: () => context.showAdaptiveSheet( + (_) => SpaceHierarchySheet(selectedSpace.id), + ), + ), + expandedWidth: double.infinity, + scrollable: true, + background: Colors.transparent, + type: .alwaysExpand, + selectedIndex: max(0, destinationIds.indexOf(selectedRoomId)), + sections: [ + if (selectedSpace.room case final room? + when spaceMetadata != null) + .new( + destinations: [ + room.toDestination( + isDm: isDm, + label: "Space timeline", + icon: const Icon(Icons.forum), + ), + ], + ), + .new( + header: selectedSpace.room == null + ? null + : const DividerWidget(Text("Rooms")), + destinations: selectedSpace.children.toDestinations(isDm: isDm), + ), + ...selectedSpace.subSpaces.map( + (subSpace) => NavigationRailM3ESection( + header: DividerWidget( + Row( + mainAxisSize: .min, + spacing: 8, + children: [ + if (subSpace.room.metadata?.avatar != null) + AvatarOrHash( + subSpace.room.metadata?.avatar, + subSpace.room.metadata?.name ?? "Unnamed Room", + dimension: 16, + ), + Flexible( + child: Text( + subSpace.room.metadata?.name ?? "Unnamed Space", + maxLines: 1, + overflow: .ellipsis, + ), + ), + ], + ), + ), + destinations: subSpace.children.toDestinations(isDm: isDm), + ), + ), + ], + onDestinationSelected: (value) { + ref + .read(KeyController.provider(KeyController.roomKey).notifier) + .set(destinationIds[value]); + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); + } + }, + ), + ), + ), + ); + } +} diff --git a/lib/widgets/sidebar.dart b/lib/widgets/sidebar/sidebar.dart similarity index 88% rename from lib/widgets/sidebar.dart rename to lib/widgets/sidebar/sidebar.dart index 3ed8daa..d8f98cb 100644 --- a/lib/widgets/sidebar.dart +++ b/lib/widgets/sidebar/sidebar.dart @@ -4,10 +4,10 @@ import "package:material_ui/material_ui.dart"; import "package:nexus/controllers/sidebar_page.dart"; import "package:nexus/models/nav_page.dart"; import "package:nexus/models/sidebar_page.dart"; -import "package:nexus/widgets/count_badge.dart"; -import "package:nexus/widgets/invites_list.dart"; -import "package:nexus/widgets/notifications_list.dart"; -import "package:nexus/widgets/room_list.dart"; +import "package:nexus/widgets/common/count_badge.dart"; +import "package:nexus/widgets/sidebar/invites_list.dart"; +import "package:nexus/widgets/sidebar/notifications_list.dart"; +import "package:nexus/widgets/sidebar/room_list.dart"; class const Sidebar({super.key}) extends ConsumerWidget { static NavPage pageFor(SidebarPage page) => switch (page) { diff --git a/lib/widgets/sidebar/spaces_rail.dart b/lib/widgets/sidebar/spaces_rail.dart new file mode 100644 index 0000000..d84a40a --- /dev/null +++ b/lib/widgets/sidebar/spaces_rail.dart @@ -0,0 +1,142 @@ +import "dart:math"; + +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:navigation_rail_m3e/navigation_rail_m3e.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/helpers/extensions/get_all_child_rooms.dart"; +import "package:nexus/widgets/common/account_switcher.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/rooms/create_room_sheet.dart"; +import "package:nexus/widgets/users/start_dm_sheet.dart"; +import "package:nexus/widgets/pages/explore.dart"; +import "package:nexus/widgets/pages/settings.dart"; +import "package:nexus/widgets/rooms/join_sheet.dart"; +import "package:nexus/widgets/common/m3e_rail_theme.dart"; +import "package:nexus/controllers/key.dart"; +import "package:nexus/controllers/spaces.dart"; + +class const SpacesRail({super.key}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final spaces = ref.watch( + SpacesController.provider.select((async) => async.requireValue), + ); + final selectedSpaceId = ref.watch( + KeyController.provider(KeyController.spaceKey) + .select((async) => async.requireValue), + ); + + return M3ERailTheme( + extensions: [ + NavigationRailM3ETheme(itemCollapsedHeight: 48, itemVerticalGap: 0), + ], + builder: (context) => Container( + color: NavigationRailTokensAdapter(context).containerColor, + padding: .only(top: 16), + child: NavigationRailM3E( + type: .alwaysCollapse, + labelBehavior: .alwaysHide, + scrollable: true, + onDestinationSelected: (value) { + ref + .read(KeyController.provider(KeyController.spaceKey).notifier) + .set(spaces[value].id); + ref + .read(KeyController.provider(KeyController.roomKey).notifier) + .set(spaces[value].children.firstOrNull?.metadata?.id); + }, + sections: [ + .new( + destinations: spaces.map((space) { + final notifications = space.allChildRooms.fold( + 0, + (sum, room) => + sum + (room.metadata?.unreadNotifications ?? 0), + ); + + return NavigationRailM3EDestination( + badgeCount: notifications > 0 + ? notifications + : space.allChildRooms.any( + (room) => room.metadata?.unreadMessages != 0, + ) + ? 0 + : null, + short: true, + icon: AvatarOrHash( + dimension: 28, + space.room?.metadata?.avatar, + fallback: space.icon == null ? null : Icon(space.icon), + space.title, + ), + label: space.title, + ); + }).toList(), + ), + ], + selectedIndex: max( + 0, + spaces.indexWhere((space) => space.id == selectedSpaceId), + ), + trailingAtBottom: true, + trailing: Padding( + padding: .only(top: 8), + child: Column( + children: [ + AdaptiveMenuButton( + tooltip: "Add a room", + itemBuilder: (_) => [ + PopupMenuItem( + onTap: () => + context.showAdaptiveSheet((_) => JoinSheet(ref)), + child: const ListTile( + title: Text("Join an existing room (or space)"), + leading: Icon(Icons.numbers), + ), + ), + PopupMenuItem( + onTap: () => context.showAdaptiveSheet( + (_) => const CreateRoomSheet(), + ), + child: const ListTile( + title: Text("Create a new room (or space)"), + leading: Icon(Icons.add), + ), + ), + PopupMenuItem( + onTap: () => context.showAdaptiveSheet( + (_) => const StartDmSheet(), + ), + child: const ListTile( + title: Text("Start a direct message"), + leading: Icon(Icons.person_add), + ), + ), + ], + icon: const Icon(Icons.add), + ), + const AccountSwitcher(), + IconButton( + tooltip: "Explore other rooms", + onPressed: () => Navigator.of(context).push( + MaterialPageRoute(builder: (_) => const ExplorePage()), + ), + icon: const Icon(Icons.explore), + ), + IconButton( + tooltip: "Open settings", + onPressed: () => showDialog( + context: context, + builder: (_) => SettingsPage(), + ), + icon: const Icon(Icons.settings), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/threads/thread_drawer.dart b/lib/widgets/threads/thread_drawer.dart new file mode 100644 index 0000000..bc88933 --- /dev/null +++ b/lib/widgets/threads/thread_drawer.dart @@ -0,0 +1,125 @@ +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/room_chat.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/build_event_options.dart"; +import "package:nexus/helpers/hooks/chat_composer.dart"; +import "package:nexus/helpers/hooks/chat_scroll.dart"; +import "package:nexus/widgets/room_chat/chat_body.dart"; + +/// The thread from [threadRoot], with a composer to send to it. +final class const ThreadDrawer( + final String roomId, { + required final String threadRoot, + + /// An event in the thread to scroll to once it loads. + final int? initialEvent, + required final String userId, + + /// Jumps to events outside this thread, like ones replied to from it. + required final JumpToEvent jumpToRoomEvent, + super.key, +}) extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final composer = ChatComposer.use(ref, ( + roomId: roomId, + threadRoot: threadRoot, + )); + final contextualEvent = useState(initialEvent); + + final ChatParams chat = ( + roomId: roomId, + contextualEvent: contextualEvent.value, + threadRoot: threadRoot, + ); + final controllerProvider = RoomChatController.provider(chat); + final controllerData = ref.watch(controllerProvider); + + final scroll = ChatScroll.use( + controllerData: controllerData, + paginate: ref.watch(controllerProvider.notifier).paginate, + contextualEvent: contextualEvent, + markRead: () async { + final room = ref.read( + RoomsController.provider.select((rooms) => rooms[roomId]), + ); + + if (room != null) { + await ref + .read(ClientController.provider.notifier) + .markRead(room, threadRoot: threadRoot); + } + }, + ); + + final initialEventLoaded = + controllerData.value?.timeline.contains(initialEvent) ?? false; + // Only once, so returning to the newest events doesn't jump back to it + final jumpedToInitialEvent = useRef(false); + useEffect(() { + if (initialEvent case final rowId? + when initialEventLoaded && !jumpedToInitialEvent.value) { + jumpedToInitialEvent.value = true; + WidgetsBinding.instance.addPostFrameCallback( + (_) => scroll.jumpToEvent(rowId), + ); + } + + return null; + }, [initialEventLoaded]); + + // This chat only has the thread, so other events are left to the room. + // Ones in the thread that aren't loaded are loaded around, like the room. + Future jumpToEvent(int rowId) async { + final isInThread = + ref + .read(RoomsController.provider)[roomId] + ?.events[rowId] + ?.threadRoot == + threadRoot; + if (isInThread || + (controllerData.value?.timeline.contains(rowId) ?? false)) { + return scroll.jumpToEvent(rowId); + } + + Scaffold.of(context).closeEndDrawer(); + await jumpToRoomEvent(rowId); + } + + return Drawer( + width: 400, + child: Scaffold( + backgroundColor: Colors.transparent, + appBar: AppBar( + scrolledUnderElevation: 0, + leading: Icon(Icons.forum), + title: Text("Thread"), + actionsPadding: .only(right: 4), + actions: [ + IconButton( + onPressed: Scaffold.of(context).closeEndDrawer, + icon: Icon(Icons.close), + tooltip: "Close thread", + ), + ], + ), + body: ChatBody( + chat: chat, + scroll: scroll, + jumpToEvent: jumpToEvent, + getEventOptions: (event) => event.buildEventOptions( + context: context, + ref: ref, + roomId: roomId, + userId: userId, + onRelation: composer.relate, + ), + composer: composer, + ), + ), + ); + } +} diff --git a/lib/widgets/threads/thread_summary.dart b/lib/widgets/threads/thread_summary.dart new file mode 100644 index 0000000..fba44ba --- /dev/null +++ b/lib/widgets/threads/thread_summary.dart @@ -0,0 +1,88 @@ +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/thread_events.dart"; +import "package:nexus/models/event.dart"; +import "package:nexus/widgets/lazy_loading/message_avatar.dart"; +import "package:nexus/widgets/lazy_loading/message_displayname.dart"; +import "package:nexus/widgets/renderers/event.dart"; + +/// How many replies are in the thread from [root], and the latest one, or nothing if it has none. +class const ThreadSummary( + final Event root, { + required final VoidCallback onTap, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + + final thread = ref.watch( + RoomsController.provider.select( + (rooms) => rooms[root.roomId]?.thread(root), + ), + ); + + if (thread case (:final count, :final latest) when count > 0) { + return Card( + margin: .only(top: 8), + color: colorScheme.surfaceContainerHigh, + child: InkWell( + onTap: onTap, + child: Padding( + padding: .symmetric(vertical: 12, horizontal: 16), + child: Column( + crossAxisAlignment: .start, + spacing: 8, + children: [ + Row( + mainAxisSize: .min, + spacing: 6, + children: [ + Icon(Icons.forum, size: 16, color: colorScheme.primary), + Text( + "$count ${count == 1 ? "reply" : "replies"}", + style: theme.textTheme.labelLarge?.copyWith( + color: colorScheme.primary, + ), + ), + Icon( + Icons.chevron_right, + size: 16, + color: colorScheme.primary, + ), + ], + ), + if (latest != null) + IgnorePointer( + child: Row( + mainAxisSize: .min, + spacing: 8, + children: [ + MessageAvatar(latest, height: 24), + Flexible( + child: MessageDisplayname(latest, shouldWrap: false), + ), + Flexible( + flex: 2, + child: EventRenderer( + latest.rowId, + roomId: latest.roomId, + textOnly: true, + maxLines: 1, + ), + ), + ], + ), + ), + ], + ), + ), + ), + ); + } + + return SizedBox.shrink(); + } +} diff --git a/lib/widgets/threads/threads_drawer.dart b/lib/widgets/threads/threads_drawer.dart new file mode 100644 index 0000000..e7931da --- /dev/null +++ b/lib/widgets/threads/threads_drawer.dart @@ -0,0 +1,157 @@ +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/thread_list.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/helpers/extensions/thread_events.dart"; +import "package:nexus/main.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/widgets/common/loading.dart"; +import "package:nexus/widgets/renderers/event_preview.dart"; +import "package:nexus/widgets/common/timestamp.dart"; + +final class const ThreadsDrawer( + final String roomId, { + required final void Function(String threadRoot) onOpenThread, + super.key, +}) extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final threads = ref.watch( + RoomsController.provider.select( + (rooms) => rooms[roomId]?.threads ?? const .empty(), + ), + ); + final serverProvider = ThreadListController.provider(roomId); + final server = ref.watch(serverProvider); + final theme = Theme.of(context); + + void open(String threadRoot) { + Navigator.of(context).pop(); + onOpenThread(threadRoot); + } + + return Drawer( + width: 400, + child: Scaffold( + backgroundColor: Colors.transparent, + appBar: AppBar( + scrolledUnderElevation: 0, + leading: Icon(Icons.forum), + title: Text("Threads"), + actionsPadding: .only(right: 4), + actions: [ + IconButton( + onPressed: Scaffold.of(context).closeEndDrawer, + icon: Icon(Icons.close), + tooltip: "Close threads", + ), + ], + ), + body: switch (server) { + AsyncError(:final error, :final stackTrace) => ErrorDialog( + error, + stackTrace, + ), + AsyncValue(hasValue: true, value: final nextBatch) + when threads.isNotEmpty => + ListView.builder( + padding: .all(8), + itemCount: threads.length + (nextBatch == null ? 0 : 1), + itemBuilder: (context, index) { + if (index == threads.length) { + return Center( + child: TextButton( + onPressed: server.isLoading + ? null + : () => ref + .read(serverProvider.notifier) + .loadMore() + .onError(showError), + child: Text("Load more"), + ), + ); + } + + final (:root, :info) = threads[index]; + return Card( + margin: .symmetric(vertical: 4), + color: theme.colorScheme.surfaceContainerHigh, + clipBehavior: .antiAlias, + child: InkWell( + onTap: () => open(root.eventId), + child: Padding( + padding: .symmetric(vertical: 8, horizontal: 12), + child: Column( + crossAxisAlignment: .start, + spacing: 4, + children: [ + EventPreview(root.rowId, roomId: roomId), + Row( + spacing: 6, + children: [ + Icon( + Icons.forum, + size: 16, + color: theme.colorScheme.primary, + ), + Text( + "${info.count} ${info.count == 1 ? "reply" : "replies"}", + style: theme.textTheme.labelLarge?.copyWith( + color: theme.colorScheme.primary, + ), + ), + if (info.latest case final latest?) + Expanded( + child: Row( + mainAxisAlignment: .end, + spacing: 4, + children: [ + Flexible( + child: Text( + "Last active:", + maxLines: 1, + overflow: .ellipsis, + style: theme.textTheme.labelSmall + ?.copyWith(color: Colors.grey), + ), + ), + Timestamp(latest.timestamp), + ], + ), + ) + else + Spacer(), + Icon( + Icons.chevron_right, + size: 16, + color: theme.colorScheme.primary, + ), + ], + ), + ], + ), + ), + ), + ); + }, + ), + AsyncLoading() => Loading(), + AsyncData() => Center( + child: Column( + mainAxisSize: .min, + children: [ + Icon( + Icons.forum_outlined, + size: 48, + color: theme.colorScheme.onSurface, + ), + SizedBox(height: 12), + Text("No threads", style: theme.textTheme.headlineSmall), + ], + ), + ), + }, + ), + ); + } +} diff --git a/lib/widgets/mutual_rooms_sheet.dart b/lib/widgets/users/mutual_rooms_sheet.dart similarity index 95% rename from lib/widgets/mutual_rooms_sheet.dart rename to lib/widgets/users/mutual_rooms_sheet.dart index 68b90e5..16066b0 100644 --- a/lib/widgets/mutual_rooms_sheet.dart +++ b/lib/widgets/users/mutual_rooms_sheet.dart @@ -1,13 +1,13 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/mutual_rooms.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/sidebar_page.dart"; import "package:nexus/helpers/extensions/better_when.dart"; import "package:nexus/helpers/extensions/focus_room.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; -import "package:nexus/widgets/sheet_layout.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; /// The rooms the user shares with [userId]. class const MutualRoomsSheet(final String userId, {super.key}) diff --git a/lib/widgets/start_dm_sheet.dart b/lib/widgets/users/start_dm_sheet.dart similarity index 97% rename from lib/widgets/start_dm_sheet.dart rename to lib/widgets/users/start_dm_sheet.dart index 4952b0a..e0f38df 100644 --- a/lib/widgets/start_dm_sheet.dart +++ b/lib/widgets/users/start_dm_sheet.dart @@ -1,8 +1,8 @@ import "package:flutter_hooks/flutter_hooks.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/create_room.dart"; -import "package:nexus/widgets/sheet_layout.dart"; /// Starts a DM, asking for a user ID unless [userId] is given. Pops with true /// if a DM was started. diff --git a/lib/widgets/timezone_field.dart b/lib/widgets/users/timezone_field.dart similarity index 94% rename from lib/widgets/timezone_field.dart rename to lib/widgets/users/timezone_field.dart index aeab833..6f802b6 100644 --- a/lib/widgets/timezone_field.dart +++ b/lib/widgets/users/timezone_field.dart @@ -2,8 +2,9 @@ import "dart:async"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/timezones.dart"; -import "package:nexus/helpers/extensions/is_desktop.dart"; +import "package:nexus/helpers/extensions/weighted_search.dart"; import "package:nexus/helpers/hooks/saving.dart"; import "package:nexus/widgets/settings/inline_text_field.dart"; import "package:timezone/timezone.dart"; @@ -84,7 +85,7 @@ class const TimezoneField({ onTap: () => choose(controller, null), ), ...timezones - .where((timezone) => timezone.toLowerCase().contains(query)) + .search(query, (timezone) => [(timezone, 1)]) .map( (timezone) => ListTile( leading: Icon( diff --git a/lib/widgets/user_bottom_sheet.dart b/lib/widgets/users/user_bottom_sheet.dart similarity index 82% rename from lib/widgets/user_bottom_sheet.dart rename to lib/widgets/users/user_bottom_sheet.dart index 58e29d2..12e0e24 100644 --- a/lib/widgets/user_bottom_sheet.dart +++ b/lib/widgets/users/user_bottom_sheet.dart @@ -1,12 +1,12 @@ import "package:collection/collection.dart"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:dynamic_color/dynamic_color.dart"; import "package:material_ui/material_ui.dart"; -import "package:nexus/widgets/sheet_layout.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:intl/intl.dart"; import "package:m3e_buttons/m3e_buttons.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/account_data.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/controllers/mutual_rooms.dart"; @@ -16,21 +16,22 @@ import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/user.dart"; import "package:nexus/helpers/extensions/better_when.dart"; import "package:nexus/helpers/extensions/create_room.dart"; -import "package:nexus/helpers/extensions/show_adaptive_sheet.dart"; +import "package:nexus/helpers/extensions/success_scheme.dart"; +import "package:nexus/helpers/extensions/with_progress_snackbar.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; -import "package:nexus/widgets/error_dialog.dart"; -import "package:nexus/widgets/loading.dart"; -import "package:nexus/widgets/mutual_rooms_sheet.dart"; +import "package:nexus/widgets/common/error_dialog.dart"; +import "package:nexus/widgets/common/loading.dart"; +import "package:nexus/widgets/users/mutual_rooms_sheet.dart"; import "package:nexus/models/content/membership.dart"; import "package:nexus/models/membership_action.dart"; import "package:nexus/models/profile_response.dart"; -import "package:nexus/widgets/avatar_or_hash.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; import "package:nexus/main.dart"; -import "package:nexus/widgets/editable_avatar.dart"; -import "package:nexus/widgets/expandable_image.dart"; +import "package:nexus/widgets/avatars/editable_avatar.dart"; +import "package:nexus/widgets/common/expandable_image.dart"; import "package:nexus/widgets/settings/inline_text_field.dart"; -import "package:nexus/widgets/start_dm_sheet.dart"; -import "package:nexus/widgets/timezone_field.dart"; +import "package:nexus/widgets/users/start_dm_sheet.dart"; +import "package:nexus/widgets/users/timezone_field.dart"; final class const UserBottomSheet( final String userId, { @@ -80,12 +81,6 @@ final class const UserBottomSheet( ), ); - // Green for accepting knocks, harmonized so it fits the current theme - final acceptScheme = ColorScheme.fromSeed( - seedColor: Colors.green.harmonizeWith(theme.colorScheme.primary), - brightness: theme.brightness, - ); - void showMembershipSheet(MembershipAction action) => context.showAdaptiveSheet( (context) => HookBuilder( @@ -151,7 +146,65 @@ final class const UserBottomSheet( if (!editable) ...[ Row( mainAxisAlignment: .end, + spacing: 8, children: [ + if (userId != + ref.watch(ClientStateController.provider)?.userId) + Consumer( + builder: (context, ref, _) { + final ignored = ref.watch( + AccountDataController.provider.select( + (data) => data.ignoredUserList.contains(userId), + ), + ); + final name = member.displayName ?? userId.localpart; + Future setIgnored( + bool ignored, + ) => context.withProgressSnackbar( + "${ignored ? "Blocking" : "Unblocking"} $name...", + () => ref + .read(AccountDataController.provider.notifier) + .setIgnored(userId, ignored: ignored), + ); + + return M3EButton( + tooltip: ignored ? "Unblock" : "Block", + onPressed: ignored + ? () => setIgnored(false) + : () => context.showAdaptiveSheet( + (context) => SheetLayout( + title: Text("Block $name"), + actions: [ + TextButton( + onPressed: Navigator.of(context).pop, + child: Text("Cancel"), + ), + TextButton( + onPressed: () { + Navigator.of(context).pop(); + setIgnored(true); + }, + style: TextButton.styleFrom( + foregroundColor: + theme.colorScheme.error, + ), + child: Text("Block"), + ), + ], + children: [ + Text( + "Are you sure you want to block $userId? You won't see their new messages or invites.", + ), + ], + ), + ), + style: .tonal, + child: Icon( + ignored ? Icons.lock_open : Icons.block, + ), + ); + }, + ), M3EButton( onPressed: Navigator.of(context).pop, child: Icon(Icons.close), @@ -407,8 +460,8 @@ final class const UserBottomSheet( icon: Icon(Icons.check), label: Text("Accept knock"), decoration: .styleFrom( - backgroundColor: acceptScheme.primary, - foregroundColor: acceptScheme.onPrimary, + backgroundColor: theme.successScheme.primary, + foregroundColor: theme.successScheme.onPrimary, ), ), ), diff --git a/lib/widgets/users/user_span.dart b/lib/widgets/users/user_span.dart new file mode 100644 index 0000000..d8a305c --- /dev/null +++ b/lib/widgets/users/user_span.dart @@ -0,0 +1,67 @@ +import "package:flutter/gestures.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:material_ui/material_ui.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/controllers/author.dart"; +import "package:nexus/helpers/extensions/displayname_color.dart"; +import "package:nexus/helpers/extensions/get_localpart.dart"; +import "package:nexus/helpers/extensions/show_user_popover.dart"; +import "package:nexus/models/event.dart"; + +/// A user's [name] in text, opening their popover when tapped. Unlike a widget +/// in text, it wraps and ellipsizes with the rest of it. + +// Can't be const, since it sets the recognizer's onTapUp +// ignore: prefer_const_constructors_in_immutables +class UserSpan( + BuildContext context, + String name, { + required String userId, + required TapGestureRecognizer recognizer, + String? roomId, + super.style, + super.children, +}) extends TextSpan { + this + : super( + text: name, + recognizer: recognizer + ..onTapUp = (details) { + if (!context.mounted) return; + + context.showUserPopover( + userId, + roomId: roomId, + anchor: context.globalRectAt(details.globalPosition), + ); + }, + ); + + factory UserSpan.sender( + BuildContext context, + WidgetRef ref, + Event event, { + required TapGestureRecognizer recognizer, + }) { + final color = ref.displaynameColor(event.roomId, event.sender); + + return UserSpan( + context, + ref.watch(AuthorController.provider(.fromEvent(event))).value?.displayName ?? + event.sender.localpart, + userId: event.sender, + roomId: event.roomId, + recognizer: recognizer, + style: TextStyle(color: color, fontWeight: .bold), + children: [ + if (event.pmp != null) + TextSpan( + text: " (via ${event.sender})", + recognizer: recognizer, + style: Theme.of(context).textTheme.labelSmall + ?.copyWith(color: color, fontWeight: .bold), + ), + ], + ); + } +} diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt index 2e0c766..7f5e185 100644 --- a/linux/CMakeLists.txt +++ b/linux/CMakeLists.txt @@ -126,3 +126,42 @@ if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() + +# On Debug builds, register this build as the handler for the app's URI +# scheme, so links like OAuth redirects open it, based on the packaged +# desktop file but running this bundle's binary. +if(CMAKE_BUILD_TYPE MATCHES "Debug") + install(CODE " + set(URI_DESKTOP_FILE \"${CMAKE_CURRENT_SOURCE_DIR}/${APPLICATION_ID}.uri.desktop\") + set(URI_DESKTOP_NAME \"${APPLICATION_ID}.uri.desktop\") + set(URI_BINARY_NAME \"${BINARY_NAME}\") + " COMPONENT Runtime) + install(CODE [[ + if(DEFINED ENV{XDG_DATA_HOME} AND NOT "$ENV{XDG_DATA_HOME}" STREQUAL "") + set(applications_dir "$ENV{XDG_DATA_HOME}/applications") + else() + set(applications_dir "$ENV{HOME}/.local/share/applications") + endif() + + file(READ "${URI_DESKTOP_FILE}" desktop_entry) + string(REGEX REPLACE "(^|\n)Exec=${URI_BINARY_NAME} " + "\\1Exec=\"${CMAKE_INSTALL_PREFIX}/${URI_BINARY_NAME}\" " + desktop_entry "${desktop_entry}") + + # Only rewritten when it changes, so the desktop database isn't refreshed + # on every build + set(destination "${applications_dir}/${URI_DESKTOP_NAME}") + set(existing "") + if(EXISTS "${destination}") + file(READ "${destination}" existing) + endif() + if(NOT existing STREQUAL desktop_entry) + message(STATUS "Registering URI handler: ${destination}") + file(WRITE "${destination}" "${desktop_entry}") + execute_process( + COMMAND update-desktop-database "${applications_dir}" + RESULT_VARIABLE _ OUTPUT_QUIET ERROR_QUIET + ) + endif() + ]] COMPONENT Runtime) +endif() diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index 077376d..955bc02 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -7,10 +7,11 @@ #include "generated_plugin_registrant.h" #include +#include +#include #include #include -#include -#include +#include #include #include @@ -18,18 +19,21 @@ void fl_register_plugins(FlPluginRegistry* registry) { g_autoptr(FlPluginRegistrar) app_links_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "AppLinksPluginLinux"); app_links_plugin_linux_register_with_registrar(app_links_linux_registrar); + g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin"); + audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar); + g_autoptr(FlPluginRegistrar) better_player_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "BetterPlayerLinuxPlugin"); + better_player_linux_plugin_register_with_registrar(better_player_linux_registrar); g_autoptr(FlPluginRegistrar) dynamic_color_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "DynamicColorPlugin"); dynamic_color_plugin_register_with_registrar(dynamic_color_registrar); g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); file_selector_plugin_register_with_registrar(file_selector_linux_registrar); - g_autoptr(FlPluginRegistrar) media_kit_libs_linux_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "MediaKitLibsLinuxPlugin"); - media_kit_libs_linux_plugin_register_with_registrar(media_kit_libs_linux_registrar); - g_autoptr(FlPluginRegistrar) media_kit_video_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "MediaKitVideoPlugin"); - media_kit_video_plugin_register_with_registrar(media_kit_video_registrar); + g_autoptr(FlPluginRegistrar) location_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "LocationPlugin"); + location_plugin_register_with_registrar(location_registrar); g_autoptr(FlPluginRegistrar) pasteboard_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "PasteboardPlugin"); pasteboard_plugin_register_with_registrar(pasteboard_registrar); diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 66d7f77..c41bfb1 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -4,15 +4,17 @@ list(APPEND FLUTTER_PLUGIN_LIST app_links_linux + audioplayers_linux + better_player_linux dynamic_color file_selector_linux - media_kit_libs_linux - media_kit_video + location pasteboard url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni ) set(PLUGIN_BUNDLED_LIBRARIES) diff --git a/linux/nexus.federated.nexus.metainfo.xml b/linux/nexus.federated.nexus.metainfo.xml new file mode 100644 index 0000000..53c738c --- /dev/null +++ b/linux/nexus.federated.nexus.metainfo.xml @@ -0,0 +1,78 @@ + + + nexus.federated.nexus + CC0-1.0 + GPL-3.0-only + + Nexus + A simple and user-friendly Matrix client + + QuadRadical + + + +

+ Nexus is a simple and user-friendly client for Matrix, the open and + decentralized chat network. It's made with Flutter, with gomuks handling + the Matrix side. +

+

Features include:

+
    +
  • Spaces, threads, replies and reactions
  • +
  • End-to-end encryption, with verification and recovery keys
  • +
  • Polls, location sharing, and custom emoji and sticker packs
  • +
  • Multiple accounts
  • +
  • Notifications through UnifiedPush
  • +
  • Layouts for phones and desktops, including Linux phones
  • +
+
+ + nexus.federated.nexus.desktop + + https://git.federated.nexus/Nexus/nexus + https://git.federated.nexus/Nexus/nexus/issues + https://git.federated.nexus/Nexus/nexus + + + + + Chatting in a room, with its members + https://git.federated.nexus/Nexus/nexus/raw/branch/main/assets/screenshots/desktop-light.png + + + The same, in dark mode + https://git.federated.nexus/Nexus/nexus/raw/branch/main/assets/screenshots/desktop-dark.png + + + Chatting on a phone + https://git.federated.nexus/Nexus/nexus/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png + + + Spaces and rooms on a phone + https://git.federated.nexus/Nexus/nexus/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png + + + + + 360 + + + keyboard + pointing + touch + + + + intense + intense + + + + + + + + + + +
diff --git a/linux/nexus.federated.nexus.uri.desktop b/linux/nexus.federated.nexus.uri.desktop index 10f495f..275c352 100644 --- a/linux/nexus.federated.nexus.uri.desktop +++ b/linux/nexus.federated.nexus.uri.desktop @@ -5,4 +5,4 @@ Icon=nexus Terminal=false Type=Application NoDisplay=true -MimeType=x-scheme-handler/nexus.federated.nexus; \ No newline at end of file +MimeType=x-scheme-handler/nexus.federated.nexus;x-scheme-handler/matrix; \ No newline at end of file diff --git a/linux/nix/build_env.nix b/linux/nix/build_env.nix new file mode 100644 index 0000000..8883959 --- /dev/null +++ b/linux/nix/build_env.nix @@ -0,0 +1,64 @@ +{ pkgs, lib }: +# What building Nexus needs, shared by the dev shell and the e2e tests +{ + packages = + with pkgs; + [ + stdenv.cc + # webcrypto's build hook runs CMake with the Unix Makefiles generator + gnumake + go + git + ffmpeg-headless + + libGL + (flutter.override { + # audioplayers plays audio through GStreamer + extraPkgConfigPackages = [ + gst_all_1.gstreamer + gst_all_1.gst-plugins-base + ]; + }) + ] + ++ lib.optionals pkgs.stdenv.isLinux [ + wayland + (callPackage ./pkg/hook_pkg_config.nix { }) + ]; + + env = lib.optionalAttrs pkgs.stdenv.isLinux { + # nativeapi includes XInput2.h and GTK's Wayland headers, which need these, but xi.pc and gdk-3.0.pc + # only list them privately, so its hook's pkg-config doesn't return them. Hooks only get NIX_ variables. + "NIX_CFLAGS_COMPILE_${pkgs.stdenv.cc.suffixSalt}" = + lib.concatMapStringsSep " " (pkg: "-isystem ${lib.getDev pkg}/include") + ( + with pkgs; + [ + libxext + libxfixes + wayland + ] + ); + # better_player loads libmpv at runtime to play videos + LD_LIBRARY_PATH = "./build/native_assets/linux:${ + lib.makeLibraryPath [ + pkgs.zlib + pkgs.mpv-unwrapped + ] + }"; + # audioplayers links GStreamer by name only, without its library directory + LIBRARY_PATH = lib.makeLibraryPath [ + pkgs.gst_all_1.gstreamer + pkgs.gst_all_1.gst-plugins-base + pkgs.glib + ]; + GST_PLUGIN_SYSTEM_PATH_1_0 = lib.makeSearchPathOutput "lib" "lib/gstreamer-1.0" ( + with pkgs.gst_all_1; + [ + gstreamer + gst-plugins-base + gst-plugins-good + gst-libav + ] + ); + }; +} diff --git a/linux/nix/bump_libmpv.sh b/linux/nix/bump_libmpv.sh new file mode 100644 index 0000000..02a74f1 --- /dev/null +++ b/linux/nix/bump_libmpv.sh @@ -0,0 +1,60 @@ +# shellcheck shell=bash + +# Opens a PR bumping the libmpv build that the Windows CI downloads, if +# mpv-winbuild-cmake has published a newer one. Run it from the repo root, with +# TOKEN set to a Forgejo token that can push branches and open PRs. + +# Checked first, so that nothing is pushed if the PR can't be opened +: "${TOKEN:?needs a Forgejo token}" +: "${GITHUB_SERVER_URL:?is set by Forgejo Actions}" +: "${GITHUB_REPOSITORY:?is set by Forgejo Actions}" +: "${GITHUB_REF_NAME:?is set by Forgejo Actions}" + +workflow=.github/workflows/windows.yml +current_url=$(grep -oE 'https://github\.com/shinchiro/mpv-winbuild-cmake/releases/download/[^"]+\.7z' "$workflow") +current_hash=$(grep -oE -- '-ne "[0-9a-f]{64}"' "$workflow" | grep -oE '[0-9a-f]{64}') + +release=$(curl -fsSL https://api.github.com/repos/shinchiro/mpv-winbuild-cmake/releases/latest) +tag=$(jq -r .tag_name <<<"$release") +url=$(jq -r '.assets[] | select(.name | test("^mpv-dev-x86_64-[0-9]{8}-git-[0-9a-f]+\\.7z$")) | .browser_download_url' <<<"$release") + +if [ -z "$url" ]; then + echo "Release $tag has no x86_64 libmpv archive" >&2 + exit 1 +fi +if [ "$url" = "$current_url" ]; then + echo "libmpv is up to date ($tag)" + exit 0 +fi + +branch="bump-libmpv-$tag" +if git ls-remote --exit-code --heads origin "$branch" >/dev/null; then + echo "$branch already exists, so its PR should already be open" + exit 0 +fi + +archive=$(mktemp) +curl -fsSL "$url" -o "$archive" +hash=$(sha256sum "$archive" | cut -d " " -f 1) +rm "$archive" + +sed -i "s|$current_url|$url|; s|$current_hash|$hash|" "$workflow" + +git config user.name "Forgejo Actions" +git config user.email "forgejo-actions@noreply.git.federated.nexus" +git switch -c "$branch" +git commit -am "bump libmpv to $tag" +git push origin "$branch" + +curl -fsS -X POST "$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY/pulls" \ + -H "Authorization: token $TOKEN" \ + -H "Content-Type: application/json" \ + -d "$(jq -n \ + --arg head "$branch" \ + --arg base "$GITHUB_REF_NAME" \ + --arg title "Bump libmpv to $tag" \ + --arg body "Updates the libmpv build that the Windows CI bundles to [$tag](https://github.com/shinchiro/mpv-winbuild-cmake/releases/tag/$tag)." \ + '{head: $head, base: $base, title: $title, body: $body}')" \ + >/dev/null + +echo "Opened a PR bumping libmpv to $tag" diff --git a/linux/nix/default.nix b/linux/nix/default.nix index 3c0a301..8f09dbc 100644 --- a/linux/nix/default.nix +++ b/linux/nix/default.nix @@ -30,7 +30,14 @@ appName = "Nexus"; developer = "QuadRadical"; appId = "nexus.federated.nexus"; - package = default; + # The runtime's GStreamer gets loaded instead of ours, and it can't + # load our plugins, so keep wrapGAppsHook from pointing it at them + package = default.overrideAttrs (old: { + postInstall = '' + unset GST_PLUGIN_SYSTEM_PATH_1_0 + '' + + old.postInstall; + }); runtime = "org.gnome.Platform/51"; permissions = { share = [ "network" ]; @@ -54,6 +61,94 @@ }; devShells.default = pkgs.callPackage ./devshell.nix { }; + + apps = + let + buildEnv = import ./build_env.nix { inherit pkgs lib; }; + testEnv = buildEnv.env // { + DBUS_SESSION_CONFIG = "${pkgs.dbus}/share/dbus-1/session.conf"; + }; + e2e = pkgs.writeShellApplication { + name = "nexus-e2e"; + runtimeInputs = + buildEnv.packages + ++ (with pkgs; [ + # TEMPORARY: matrix-continuwuity, once the local fixes are released + (inputs.continuwuity.packages.${system}.default.overrideAttrs { doCheck = false; }) + curl + dbus + ]); + runtimeEnv = testEnv; + text = builtins.readFile ./e2e.sh; + }; + screenshots = pkgs.writeShellApplication { + name = "nexus-screenshots"; + runtimeInputs = + buildEnv.packages + ++ (with pkgs; [ + dbus + oxipng + pngquant + ]); + runtimeEnv = testEnv; + text = builtins.readFile ./screenshots.sh; + }; + + headless = + program: + lib.getExe ( + pkgs.writeShellApplication { + name = "${lib.getName program}-headless"; + runtimeInputs = [ pkgs.cage ]; + runtimeEnv = { + WLR_BACKENDS = "headless"; + __EGL_VENDOR_LIBRARY_FILENAMES = "${pkgs.mesa}/share/glvnd/egl_vendor.d/50_mesa.json"; + }; + text = '' + unset DISPLAY WAYLAND_DISPLAY + # Wayland needs one, which CI may not have + XDG_RUNTIME_DIR="''${XDG_RUNTIME_DIR:-$(mktemp -d)}" + export XDG_RUNTIME_DIR + + exec cage -- ${lib.getExe program} "$@" + ''; + } + ); + in + { + e2e = { + type = "app"; + program = lib.getExe e2e; + }; + + bump-libmpv = { + type = "app"; + program = lib.getExe ( + pkgs.writeShellApplication { + name = "nexus-bump-libmpv"; + runtimeInputs = with pkgs; [ + coreutils + curl + git + gnugrep + gnused + jq + ]; + text = builtins.readFile ./bump_libmpv.sh; + } + ); + }; + + e2e-headless = { + type = "app"; + program = headless e2e; + }; + + screenshots = { + type = "app"; + program = headless screenshots; + }; + }; }; flake.nixosModules.default = import ./module.nix self; diff --git a/linux/nix/devshell.nix b/linux/nix/devshell.nix index a47f824..1f02b67 100644 --- a/linux/nix/devshell.nix +++ b/linux/nix/devshell.nix @@ -1,5 +1,6 @@ { pkgs, lib }: let + ndkVersion = "28.2.13676358"; android = pkgs.androidenv.composeAndroidPackages { toolsVersion = "26.1.1"; platformToolsVersion = "37.0.1"; @@ -10,50 +11,42 @@ let cmakeVersions = [ "3.22.1" ]; platformVersions = [ "34" + "35" "36" + "37.0" ]; abiVersions = [ "armeabi-v7a" "arm64-v8a" ]; includeNDK = true; - ndkVersions = [ "28.2.13676358" ]; + ndkVersions = [ ndkVersion ]; }; + buildEnv = import ./build_env.nix { inherit pkgs lib; }; in pkgs.mkShell { packages = - with pkgs; - [ - go - git + buildEnv.packages + ++ [ android.platform-tools ] + # For scripts/build_avif_native.sh + ++ (with pkgs; [ + cmake + jq + meson + ninja + python3 + ]); - libGL - (flutter.override { - extraPkgConfigPackages = [ - mpv-unwrapped - libass - ]; - }) - android.platform-tools - ] - ++ lib.optionals pkgs.stdenv.isLinux [ - wayland - # nativeapi includes XInput2.h, which needs these, but xi.pc only lists them privately - libxext - libxfixes - (callPackage ./pkg/hook_pkg_config.nix { }) - ]; + env = + rec { + LIBCLANG_PATH = lib.makeLibraryPath [ pkgs.libclang ]; - env = rec { - LIBCLANG_PATH = lib.makeLibraryPath [ pkgs.libclang ]; + ANDROID_HOME = "${android.androidsdk}/libexec/android-sdk"; + ANDROID_SDK_ROOT = ANDROID_HOME; + ANDROID_NDK_HOME = "${ANDROID_HOME}/ndk/${ndkVersion}"; + JAVA_HOME = pkgs.jdk21; - ANDROID_HOME = "${android.androidsdk}/libexec/android-sdk"; - ANDROID_SDK_ROOT = ANDROID_HOME; - JAVA_HOME = pkgs.jdk21; - - GRADLE_OPTS = "-Dorg.gradle.project.android.aapt2FromMavenOverride=${ANDROID_HOME}/build-tools/36.0.0/aapt2"; - } - // lib.optionalAttrs pkgs.stdenv.isLinux { - LD_LIBRARY_PATH = "./build/native_assets/linux:${lib.makeLibraryPath [ pkgs.zlib ]}"; - }; + GRADLE_OPTS = "-Dorg.gradle.project.android.aapt2FromMavenOverride=${ANDROID_HOME}/build-tools/36.0.0/aapt2"; + } + // buildEnv.env; } diff --git a/linux/nix/e2e.sh b/linux/nix/e2e.sh new file mode 100755 index 0000000..6a7a426 --- /dev/null +++ b/linux/nix/e2e.sh @@ -0,0 +1,85 @@ +# shellcheck shell=bash + +files=() +flutter_args=() +for arg in "$@"; do + if [[ "$arg" == *.dart ]]; then files+=("$arg"); else flutter_args+=("$arg"); fi +done +if [[ ${#files[@]} -eq 0 ]]; then files=(integration_test/*_test.dart); fi + +homeserver="http://localhost:8448" + +if curl -s -o /dev/null "$homeserver"; then + echo "Something is already using port 8448, like another e2e run." >&2 + exit 1 +fi + +work="$(mktemp -d)" +# shellcheck disable=SC2329 # Run by the trap +cleanup() { + [[ -n "${server_pid:-}" ]] && kill "$server_pid" 2>/dev/null && wait "$server_pid" 2>/dev/null + rm -rf "$work" +} +trap cleanup EXIT + +mkdir -p "$work/db" +cat > "$work/continuwuity.toml" < "$work/continuwuity.log" 2>&1 & +server_pid=$! + +all_can_log_in() { + for user in "${users[@]}"; do + curl -sf -XPOST "$homeserver/_matrix/client/v3/login" \ + -d "{\"type\":\"m.login.password\",\"identifier\":{\"type\":\"m.id.user\",\"user\":\"$user\"},\"password\":\"${user}pass\"}" \ + > /dev/null || return 1 + done +} + +# Wait until login succeeds, otherwise you might try to log in before the account is created +attempts=60 +until all_can_log_in; do + kill -0 "$server_pid" 2>/dev/null || { cat "$work/continuwuity.log"; exit 1; } + (( --attempts )) || { echo "Test users weren't created" >&2; exit 1; } + sleep 0.5 +done + +GOCACHE="$(go env GOCACHE)" +export GOCACHE + +# shellcheck disable=SC2329 +run_flutter_test() { + export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS%%;*}" + flutter test "$@" -d linux +} +export -f run_flutter_test + +status=0 +for file in "${files[@]}"; do + name="$(basename "$file" .dart)" + mkdir -p "$work/$name/data" "$work/$name/cache" + + XDG_DATA_HOME="$work/$name/data" XDG_CACHE_HOME="$work/$name/cache" \ + dbus-run-session --config-file="$DBUS_SESSION_CONFIG" -- \ + bash -c 'run_flutter_test "$@"' -- "$file" \ + --dart-define="NEXUS_E2E_HOMESERVER=$homeserver" "${flutter_args[@]}" || + status=$? +done +exit "$status" \ No newline at end of file diff --git a/linux/nix/pkg/avif_native.nix b/linux/nix/pkg/avif_native.nix index 16d0fc0..64dcb81 100644 --- a/linux/nix/pkg/avif_native.nix +++ b/linux/nix/pkg/avif_native.nix @@ -1,24 +1,11 @@ # avif_native's build hook downloads its prebuilt library, which the sandbox -# can't do, so bundle it and point the manifest at the local copy instead +# can't do, so build it from source against nixpkgs' libavif, and point the +# manifest at it { stdenv, - fetchurl, + libavif, jq, }: -let - artifacts = { - x86_64-linux = { - arch = "x64"; - sha256 = "252b064f8ff4f0f265bc44294d4a7ed703dd7199688942c272dd8aa8d3039d5a"; - }; - aarch64-linux = { - arch = "arm64"; - sha256 = "cdcf17cfd18b9b0f965b72615ddf11246121114577dc570d0bba25964e56c726"; - }; - }; - inherit (artifacts.${stdenv.hostPlatform.system}) arch sha256; - key = "linux-${arch}-decode-dav1d"; -in { version, src, ... }: stdenv.mkDerivation { pname = "avif_native"; @@ -26,24 +13,23 @@ stdenv.mkDerivation { inherit (src) passthru; nativeBuildInputs = [ jq ]; + buildInputs = [ libavif ]; - library = fetchurl { - url = "https://github.com/Zhangw1998/avif_native/releases/download/native-v0.1.0/${key}-libavif_native.so.gz"; - inherit sha256; - }; + buildPhase = '' + $CC -shared -fPIC src/avif_shim.c -lavif -o native/libavif_native.so + ''; - # The hook checksums the library, so it must stay byte-identical + # The hook checksums the library, so it mustn't change after it's hashed dontFixup = true; + # Nexus only decodes, with dav1d, see hooks.user_defines in pubspec.yaml installPhase = '' - runHook preInstall - cp -r . $out - chmod -R u+w $out - gunzip -c $library > $out/native/libavif_native.so - jq '.artifacts["${key}"].path = "libavif_native.so"' \ - native/manifest.json > $out/native/manifest.json - - runHook postInstall + jq --arg hash "$(sha256sum native/libavif_native.so | cut -d " " -f 1)" \ + '.artifacts |= with_entries( + if .key | test("^linux-.*-decode-dav1d$") + then .value += { path: "libavif_native.so", librarySha256: $hash } + else . end + )' native/manifest.json > $out/native/manifest.json ''; } diff --git a/linux/nix/pkg/default.nix b/linux/nix/pkg/default.nix index 47bf2d7..0bd7728 100644 --- a/linux/nix/pkg/default.nix +++ b/linux/nix/pkg/default.nix @@ -2,19 +2,29 @@ lib, callPackage, mpv-unwrapped, - libass, + gst_all_1, + ffmpeg-headless, libxext, libxfixes, libclang, flutter, stdenv, + runCommand, + yq, src, commit ? "dev", }: +let + pubspec = lib.importJSON ( + runCommand "pubspec.json" { nativeBuildInputs = [ yq ]; } '' + yq . ${src}/pubspec.yaml > $out + '' + ); +in flutter.buildFlutterApplication { pname = "nexus"; - version = "1.0.0"; + version = lib.head (lib.splitString "+" pubspec.version); inherit src; preBuild = '' @@ -30,8 +40,12 @@ flutter.buildFlutterApplication { nativeBuildInputs = [ (callPackage ./hook_pkg_config.nix { }) ]; buildInputs = [ - mpv-unwrapped - libass + # audioplayers plays audio through GStreamer, and wrapGAppsHook adds + # these plugins to the wrapper's GST_PLUGIN_SYSTEM_PATH_1_0 + gst_all_1.gstreamer + gst_all_1.gst-plugins-base + gst_all_1.gst-plugins-good + gst_all_1.gst-libav # nativeapi includes XInput2.h, which needs these, but xi.pc only lists them privately libxext libxfixes @@ -45,27 +59,34 @@ flutter.buildFlutterApplication { gitHashes = { linkify = "sha256-TpMD6+0zyY6i9l+6d8ErnVufmepCv362rCtnbOht/z4="; + location = "sha256-RL+l46pBhv75xP7ASJuazyYoi9vI35TSYAV11mkjAwY="; fab_m3e = "sha256-5V9m6yY0jimx2gh7lQHYg4HDKQ4Wrl0ATmBhw5DkQMI="; + fluttertagger = "sha256-tHUNU2+fBPkq5UK5YRi3SWs1zF2PIPz6RgSbwignU/I="; m3e_design = "sha256-5V9m6yY0jimx2gh7lQHYg4HDKQ4Wrl0ATmBhw5DkQMI="; native_toolchain_cmake = "sha256-/drnHZebmTnsCnHgC1xmlAe+U4PSrjw5Sm9axicuTrY="; navigation_rail_m3e = "sha256-5V9m6yY0jimx2gh7lQHYg4HDKQ4Wrl0ATmBhw5DkQMI="; + pasteboard = "sha256-J3yray5n7XwVXMcOsvQ5+OvADEK2lPMeYniGg+yR704="; unifiedpush_linux = "sha256-KQKyBPL2ORK9O89C4K3RHGve/lvFaU1vIjSDnj6+bj4="; unifiedpush_platform_interface = "sha256-KQKyBPL2ORK9O89C4K3RHGve/lvFaU1vIjSDnj6+bj4="; - webcrypto = "sha256-HW0NukbddwOYd9iVUFA3L8iy1qggnyOBgcbMj0MTYss="; - window_manager = "sha256-xUd5hG+/V6F+m0ZUL/3XGPACFG/zqI5JM6IaMVvLgx4="; xdg_desktop_portal = "sha256-8GgiXHGv+wy6hJgj/rZxbymMitNVmdDLAnedZm9STSc="; }; postInstall = '' install -D assets/bundled/icon.svg $out/share/icons/hicolor/scalable/apps/nexus.svg install -Dm755 linux/*.desktop -t $out/share/applications + install -Dm644 linux/*.metainfo.xml -t $out/share/metainfo install -Dm644 linux/*.service -t $out/share/dbus-1/services + # better_player loads libmpv at runtime to play videos + # gomuks uses ffmpeg and ffprobe for video thumbnails and metadata wrapProgram $out/bin/nexus \ - --suffix LD_LIBRARY_PATH : $out/app/nexus/lib + --suffix LD_LIBRARY_PATH : $out/app/nexus/lib \ + --prefix LD_LIBRARY_PATH : ${lib.makeLibraryPath [ mpv-unwrapped ]} \ + --prefix PATH : ${lib.makeBinPath [ ffmpeg-headless ]} ''; meta = { description = "A simple and user-friendly Matrix client"; + license = lib.licenses.gpl3Only; mainProgram = "nexus"; platforms = lib.platforms.unix; diff --git a/linux/nix/pkg/gomuks.nix b/linux/nix/pkg/gomuks.nix index 6c383d2..dc9f9ac 100644 --- a/linux/nix/pkg/gomuks.nix +++ b/linux/nix/pkg/gomuks.nix @@ -17,12 +17,12 @@ buildGoModule ( src = "${src}/gomuks"; - vendorHash = "sha256-nd0NEKXscgrFE/gBEW2aP+YeZNTOdbRa4QDLTRwIAZU="; + vendorHash = "sha256-MJu9qN1NhUkjF3MAz+ejVMY9dxg8yxMBqCCHzPh9RHc="; buildPhase = '' runHook preBuild - go build -buildmode=c-shared -o ${filename} -tags goolm,noheic,sqlite_fts5 ./pkg/ffi + go build -buildmode=c-shared -o ${filename} -tags noheic,sqlite_fts5 ./pkg/ffi runHook postBuild ''; diff --git a/linux/nix/screenshots.sh b/linux/nix/screenshots.sh new file mode 100644 index 0000000..f3dced6 --- /dev/null +++ b/linux/nix/screenshots.sh @@ -0,0 +1,30 @@ +# shellcheck shell=bash + +# Regenerates the README, AppStream and Fastlane screenshots, from +# integration_test/screenshots. Run it from the repo root. + +work="$(mktemp -d)" +# shellcheck disable=SC2329 # Run by the trap +cleanup() { rm -rf "$work"; } +trap cleanup EXIT + +GOCACHE="$(go env GOCACHE)" +export GOCACHE + +XDG_DATA_HOME="$work/data" XDG_CACHE_HOME="$work/cache" \ + dbus-run-session --config-file="$DBUS_SESSION_CONFIG" -- \ + flutter test integration_test/screenshots/screenshots_test.dart -d linux \ + --dart-define="SCREENSHOTS_DIR=$work/out" "$@" + +for shot in "$work"/out/*.png; do + pngquant --quality 65-95 --speed 1 --strip --force --ext .png "$shot" + oxipng --quiet --opt 4 --strip safe "$shot" +done + +install -Dm644 "$work"/out/desktop-*.png -t assets/screenshots + +phone=fastlane/metadata/android/en-US/images/phoneScreenshots +install -Dm644 "$work/out/phone-chat-light.png" "$phone/1.png" +install -Dm644 "$work/out/phone-chat-dark.png" "$phone/2.png" +install -Dm644 "$work/out/phone-rooms-light.png" "$phone/3.png" +install -Dm644 "$work/out/phone-rooms-dark.png" "$phone/4.png" diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc index f5795d0..defa773 100644 --- a/linux/runner/my_application.cc +++ b/linux/runner/my_application.cc @@ -1,5 +1,6 @@ #include "my_application.h" +#include #include #include @@ -301,6 +302,9 @@ static void my_application_startup( G_APPLICATION_CLASS( my_application_parent_class) ->startup(application); + + // mpv hates normal locales + setlocale(LC_NUMERIC, "C"); } static void my_application_shutdown( diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig index 4b81f9b..c2efd0b 100644 --- a/macos/Flutter/Flutter-Debug.xcconfig +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig index 5caa9d1..c2efd0b 100644 --- a/macos/Flutter/Flutter-Release.xcconfig +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index f10315f..662a521 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -6,11 +6,12 @@ import FlutterMacOS import Foundation import app_links +import audioplayers_darwin +import better_player_macos import dynamic_color import file_selector_macos import flutter_local_notifications -import media_kit_libs_macos_video -import media_kit_video +import location import package_info_plus import pasteboard import shared_preferences_foundation @@ -19,11 +20,12 @@ import wakelock_plus func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { AppLinksMacosPlugin.register(with: registry.registrar(forPlugin: "AppLinksMacosPlugin")) + AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin")) + BetterPlayerPlugin.register(with: registry.registrar(forPlugin: "BetterPlayerPlugin")) DynamicColorPlugin.register(with: registry.registrar(forPlugin: "DynamicColorPlugin")) FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) - MediaKitLibsMacosVideoPlugin.register(with: registry.registrar(forPlugin: "MediaKitLibsMacosVideoPlugin")) - MediaKitVideoPlugin.register(with: registry.registrar(forPlugin: "MediaKitVideoPlugin")) + LocationPlugin.register(with: registry.registrar(forPlugin: "LocationPlugin")) FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) PasteboardPlugin.register(with: registry.registrar(forPlugin: "PasteboardPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) diff --git a/macos/Podfile b/macos/Podfile deleted file mode 100644 index 65543e2..0000000 --- a/macos/Podfile +++ /dev/null @@ -1,42 +0,0 @@ -platform :osx, '13.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_macos_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_macos_build_settings(target) - end -end diff --git a/macos/Podfile.lock b/macos/Podfile.lock deleted file mode 100644 index 08cb773..0000000 --- a/macos/Podfile.lock +++ /dev/null @@ -1,28 +0,0 @@ -PODS: - - FlutterMacOS (1.0.0) - - media_kit_libs_macos_video (1.0.4): - - FlutterMacOS - - media_kit_video (0.0.1): - - FlutterMacOS - -DEPENDENCIES: - - FlutterMacOS (from `Flutter/ephemeral`) - - media_kit_libs_macos_video (from `Flutter/ephemeral/.symlinks/plugins/media_kit_libs_macos_video/macos`) - - media_kit_video (from `Flutter/ephemeral/.symlinks/plugins/media_kit_video/macos`) - -EXTERNAL SOURCES: - FlutterMacOS: - :path: Flutter/ephemeral - media_kit_libs_macos_video: - :path: Flutter/ephemeral/.symlinks/plugins/media_kit_libs_macos_video/macos - media_kit_video: - :path: Flutter/ephemeral/.symlinks/plugins/media_kit_video/macos - -SPEC CHECKSUMS: - FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1 - media_kit_libs_macos_video: 85a23e549b5f480e72cae3e5634b5514bc692f65 - media_kit_video: fa6564e3799a0a28bff39442334817088b7ca758 - -PODFILE CHECKSUM: 54d867c82ac51cbd61b565781b9fada492027009 - -COCOAPODS: 1.17.0 diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj index fa18d44..cc638f9 100644 --- a/macos/Runner.xcodeproj/project.pbxproj +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -27,9 +27,7 @@ 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; - 34AEA7295333B7F48CD3BE4C /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D76F30AE9CCFCA04C354BD4C /* Pods_RunnerTests.framework */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; - BAF79690465DBAC1A1E19D28 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 70FD05041ACDA7E801BB9823 /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -63,7 +61,6 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 18EDDEF1FB58EC56ABDA1BEB /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; @@ -80,16 +77,9 @@ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; - 5099E6191AE87E21D356D9C8 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; - 6D9F8F8BBED102075ECF1DF9 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - 70FD05041ACDA7E801BB9823 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; - 8F5ECEC7BF9DD35CB3E7196E /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; - 9DDE815F827B87E2C55DF94C /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - CBD1D9203BEE9731F981EEF8 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; - D76F30AE9CCFCA04C354BD4C /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -97,7 +87,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 34AEA7295333B7F48CD3BE4C /* Pods_RunnerTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -106,7 +95,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - BAF79690465DBAC1A1E19D28 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -139,8 +127,6 @@ 33CEB47122A05771004F2AC0 /* Flutter */, 331C80D6294CF71000263BE5 /* RunnerTests */, 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, - FC780AF47288088B9004ACE2 /* Pods */, ); sourceTree = ""; }; @@ -189,29 +175,6 @@ path = Runner; sourceTree = ""; }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 70FD05041ACDA7E801BB9823 /* Pods_Runner.framework */, - D76F30AE9CCFCA04C354BD4C /* Pods_RunnerTests.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - FC780AF47288088B9004ACE2 /* Pods */ = { - isa = PBXGroup; - children = ( - 6D9F8F8BBED102075ECF1DF9 /* Pods-Runner.debug.xcconfig */, - 9DDE815F827B87E2C55DF94C /* Pods-Runner.release.xcconfig */, - CBD1D9203BEE9731F981EEF8 /* Pods-Runner.profile.xcconfig */, - 18EDDEF1FB58EC56ABDA1BEB /* Pods-RunnerTests.debug.xcconfig */, - 8F5ECEC7BF9DD35CB3E7196E /* Pods-RunnerTests.release.xcconfig */, - 5099E6191AE87E21D356D9C8 /* Pods-RunnerTests.profile.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -219,7 +182,6 @@ isa = PBXNativeTarget; buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - C413A8A75594D2165C9D56BD /* [CP] Check Pods Manifest.lock */, 331C80D1294CF70F00263BE5 /* Sources */, 331C80D2294CF70F00263BE5 /* Frameworks */, 331C80D3294CF70F00263BE5 /* Resources */, @@ -238,13 +200,11 @@ isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 446C82D5FE82BD05F78EDA6A /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, 33CC110E2044A8840003C045 /* Bundle Framework */, 3399D490228B24CF009A79C7 /* ShellScript */, - C4D158541D7059C07D3CA9B3 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -371,67 +331,6 @@ shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; - 446C82D5FE82BD05F78EDA6A /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - C413A8A75594D2165C9D56BD /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - C4D158541D7059C07D3CA9B3 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -483,7 +382,6 @@ /* Begin XCBuildConfiguration section */ 331C80DB294CF71000263BE5 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 18EDDEF1FB58EC56ABDA1BEB /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -498,7 +396,6 @@ }; 331C80DC294CF71000263BE5 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8F5ECEC7BF9DD35CB3E7196E /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -513,7 +410,6 @@ }; 331C80DD294CF71000263BE5 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 5099E6191AE87E21D356D9C8 /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata index 21a3cc1..1d526a1 100644 --- a/macos/Runner.xcworkspace/contents.xcworkspacedata +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -4,7 +4,4 @@ - - diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements index 4e593b0..575757f 100644 --- a/macos/Runner/DebugProfile.entitlements +++ b/macos/Runner/DebugProfile.entitlements @@ -12,5 +12,7 @@ com.apple.security.files.user-selected.read-only + com.apple.security.personal-information.location + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist index 36999ec..d4f66d1 100644 --- a/macos/Runner/Info.plist +++ b/macos/Runner/Info.plist @@ -38,8 +38,13 @@ nexus.federated.nexus + matrix + NSLocationUsageDescription + Nexus uses your location only when you choose to share it in a message. + NSLocationWhenInUseUsageDescription + Nexus uses your location only when you choose to share it in a message. diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements index 741903e..14e2faf 100644 --- a/macos/Runner/Release.entitlements +++ b/macos/Runner/Release.entitlements @@ -8,5 +8,7 @@ com.apple.security.files.user-selected.read-only + com.apple.security.personal-information.location + diff --git a/pubspec.lock b/pubspec.lock index 670b2ca..d5b2431 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,26 +5,26 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: "48e48f73a431eb269eec66d243a63a07ed90ef9417a74047a3b98d52338626ad" + sha256: "1c5591cc6f252d5f440d96ab87c03e43504be552a3fa49d7cb7563f04c51fb0a" url: "https://pub.dev" source: hosted - version: "109.0.0" + version: "111.0.0" analysis_server_plugin: dependency: transitive description: name: analysis_server_plugin - sha256: "9f293f95cf41cb513a9a4f322354e2fa5483125e0f18bbeca254543ac9c3dda6" + sha256: "1ff5b5f6bc3d4091ffbc4da2ca9a5de36b49d590332d94e502d0746e80b3d64e" url: "https://pub.dev" source: hosted - version: "0.3.24" + version: "0.3.26" analyzer: dependency: transitive description: name: analyzer - sha256: "6d377901d198536b648172974d9d4f277910502cad92193466869cac0ff34990" + sha256: "6c39bd5486a310e56217bed7cb1691377959f31be4227e41750107db7e6dd55c" url: "https://pub.dev" source: hosted - version: "14.5.0" + version: "14.7.0" analyzer_buffer: dependency: transitive description: @@ -37,10 +37,10 @@ packages: dependency: transitive description: name: analyzer_plugin - sha256: "2c59e6fba4971dc9ece97acd55b4f95b67a98e6ae0a55bff6f9dfc2bb59e8b1a" + sha256: "8929dfe59ae5ea8e012f1238e368875642370beabffd15d4048545544ae44aa8" url: "https://pub.dev" source: hosted - version: "0.14.18" + version: "0.14.20" app_links: dependency: "direct main" description: @@ -53,12 +53,12 @@ packages: dependency: transitive description: name: app_links_linux - sha256: "9ccb5802085a1e57bb07b6256fd1d61a78c7ec104944d4965e62938b4fefd9cb" + sha256: "734aa57a2f65d1b35c3643384ccfbe668730157a08479bfa488e10a9da847853" url: "https://pub.dev" source: hosted - version: "1.0.4" + version: "1.0.5" app_links_platform_interface: - dependency: transitive + dependency: "direct dev" description: name: app_links_platform_interface sha256: "7546f09a6e93f4a2df2fe2bd40a5c6c64310ac461b036d82b43033be7a59f809" @@ -77,10 +77,10 @@ packages: dependency: transitive description: name: archive - sha256: f773153144ce0456ae77d96bd247f2efd58efe4f3e5ad42616d0385c031aea11 + sha256: "2fda90592c0afd219c5e285618a98da835cd10df38372666093d25dfe457a2d0" url: "https://pub.dev" source: hosted - version: "4.5.1" + version: "4.7.1" args: dependency: transitive description: @@ -89,14 +89,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.7.0" - asn1lib: - dependency: transitive - description: - name: asn1lib - sha256: "9a8f69025044eb466b9b60ef3bc3ac99b4dc6c158ae9c56d25eeccf5bc56d024" - url: "https://pub.dev" - source: hosted - version: "1.6.5" async: dependency: transitive description: @@ -105,14 +97,134 @@ packages: url: "https://pub.dev" source: hosted version: "2.13.1" + audioplayers: + dependency: "direct main" + description: + name: audioplayers + sha256: "2ba4bb2944baacbdd5372ff8254a8e7feb8c10d7739545e392f5605a8f618745" + url: "https://pub.dev" + source: hosted + version: "6.8.1" + audioplayers_android: + dependency: transitive + description: + name: audioplayers_android + sha256: f5ff5b15620fbab8cb0849e9636c48e2b96c3f0f71723bbbe2ad3c761b205f05 + url: "https://pub.dev" + source: hosted + version: "5.3.0" + audioplayers_darwin: + dependency: transitive + description: + name: audioplayers_darwin + sha256: "1ca553add991384ecf421b9569da850f3ab2472ffb83f6970b0416365abc51be" + url: "https://pub.dev" + source: hosted + version: "6.5.0" + audioplayers_linux: + dependency: transitive + description: + name: audioplayers_linux + sha256: "15178b726b7cdee5364d0463c8d445630c4e0fb7d26612b73c767e7d25de9417" + url: "https://pub.dev" + source: hosted + version: "4.3.0" + audioplayers_platform_interface: + dependency: transitive + description: + name: audioplayers_platform_interface + sha256: "765f6f0e6dca55cb471c9483fc77700564b3484d19198aca4ebb5147c6c85acb" + url: "https://pub.dev" + source: hosted + version: "7.2.0" + audioplayers_web: + dependency: transitive + description: + name: audioplayers_web + sha256: ae1e0103c865a03e273f6d13d97b93f5595eac09915729cd5e37ef96e2857319 + url: "https://pub.dev" + source: hosted + version: "5.3.0" + audioplayers_windows: + dependency: transitive + description: + name: audioplayers_windows + sha256: a70ae82bba2dfcb6eb03dd4815d737a2d46d33ea5a96a03f535cfcaac490e413 + url: "https://pub.dev" + source: hosted + version: "4.4.1" avif_native: dependency: "direct main" description: name: avif_native - sha256: "0a374a7ddc6e48d671792bd33efd9f46f199389cdcd42561210bd886facbc62e" + sha256: fed1aad8f8e855abf40a16484dcbfacea89b65154832d6af8ad46bf9353faf7a url: "https://pub.dev" source: hosted - version: "0.1.1" + version: "0.2.0" + better_player: + dependency: "direct main" + description: + name: better_player + sha256: f9b928eec81622f33457a5019a02c79d102dffe54b432baa43bb3400d31439e1 + url: "https://pub.dev" + source: hosted + version: "1.38.0" + better_player_android: + dependency: transitive + description: + name: better_player_android + sha256: "2c7df9bfb1e7fa69c86d3bb91a1825bba30292968307724fa51869bc3a0bb75d" + url: "https://pub.dev" + source: hosted + version: "1.13.2" + better_player_ios: + dependency: transitive + description: + name: better_player_ios + sha256: "4b9c08690374aa84b15ba88ab5d6b695cda618fb895b445a6a4186c220599c84" + url: "https://pub.dev" + source: hosted + version: "1.15.0" + better_player_linux: + dependency: transitive + description: + name: better_player_linux + sha256: "97d9eb16a587df4d714c1906ef2c49b825c1483e7d4c9050d63e696e26998f6e" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + better_player_macos: + dependency: transitive + description: + name: better_player_macos + sha256: "90f6fc0e354b034043850661a7c4e39ac34261ff7cc21c2895ea7bded126d15c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + better_player_platform_interface: + dependency: transitive + description: + name: better_player_platform_interface + sha256: e5218199dd12ffe6f43c01d5cdeecad0b53125926f8da8c3f4b90136d8b55ec1 + url: "https://pub.dev" + source: hosted + version: "1.8.0" + better_player_web: + dependency: transitive + description: + name: better_player_web + sha256: d7b365221f7724f22d3fef7840e45af2493a784e2429a30e980f807bcb7c9539 + url: "https://pub.dev" + source: hosted + version: "1.6.1" + better_player_windows: + dependency: transitive + description: + name: better_player_windows + sha256: eddc817dce6af08e74de456ad711ffd987a641c45f73998cbe9ccbf6ab5ebf22 + url: "https://pub.dev" + source: hosted + version: "1.5.1" boolean_selector: dependency: transitive description: @@ -125,34 +237,34 @@ packages: dependency: transitive description: name: build - sha256: "8a5c5761af8e31748bba3c82f68925ace40f3225c3eea25be9beb57eca7cd7a8" + sha256: "50df3d1558953a0d936401c1687cc41dbc039f9132f538c7bcb2aac2a580ae7f" url: "https://pub.dev" source: hosted - version: "4.0.11" + version: "5.0.0" build_config: dependency: transitive description: name: build_config - sha256: d466ed2dc9c6cd1d169948879b84ee061eb5e22c64a7c6089879c6296d272a8d + sha256: "4703a785fbc3c266c5c7518589d0863f6a05078ee33f7ca5aa4b87a56f1cedd2" url: "https://pub.dev" source: hosted - version: "1.3.3" + version: "1.4.0" build_daemon: dependency: transitive description: name: build_daemon - sha256: e1d40ef3f7934986d5da2271b1ba07794921ce263e44d622fb6c406d76589e33 + sha256: "39ab65f7c60c19af64b9ef96e6a5d3ab48355f7dddfd98a9079d55a8cb6628fc" url: "https://pub.dev" source: hosted - version: "4.1.6" + version: "4.1.7" build_runner: dependency: "direct dev" description: name: build_runner - sha256: "6feadd32d90a68253c1f7b4fcff76adb4b41ad32a53f8bad835dc65f01ac9dc5" + sha256: "96b9da39a3a8d4365aa1ca6f7655437d80f514ba13d4c21d8408cc8aacb94681" url: "https://pub.dev" source: hosted - version: "2.16.2" + version: "2.17.1" built_collection: dependency: transitive description: @@ -221,18 +333,18 @@ packages: dependency: transitive description: name: cnativeapi - sha256: "251fb93cd7ec205445fa512ee5ddeb0b82b3273d071cfc0784ddffbbdebbf5d3" + sha256: c43703998995e132b0656d2b8a95ed2bedc6b22ccee2c827bcdc075e0330e319 url: "https://pub.dev" source: hosted - version: "0.5.2" + version: "0.5.10" code_assets: dependency: "direct main" description: name: code_assets - sha256: "828110d598123b5ea96c00c9f3c72105bf79f8ee36c20a39b26209ade421ec57" + sha256: "1ef22a0be3af9370bd9481ac76db114db92bfe75d5ca2b2d7bc911764478a4d9" url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "2.2.0" collection: dependency: "direct main" description: @@ -269,10 +381,10 @@ packages: dependency: transitive description: name: crypto - sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4 url: "https://pub.dev" source: hosted - version: "3.0.7" + version: "3.0.8" csslib: dependency: transitive description: @@ -281,6 +393,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.2" + cupertino_icons: + dependency: transitive + description: + name: cupertino_icons + sha256: b7cc2390aac296c083bea762859413eb1cf5b630c70e0c7e4d831018f762a8b2 + url: "https://pub.dev" + source: hosted + version: "2.0.0" cupertino_ui: dependency: transitive description: @@ -289,14 +409,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.2" + dart_earcut: + dependency: transitive + description: + name: dart_earcut + sha256: e485001bfc05dcbc437d7bfb666316182e3522d4c3f9668048e004d0eb2ce43b + url: "https://pub.dev" + source: hosted + version: "1.2.0" + dart_polylabel2: + dependency: transitive + description: + name: dart_polylabel2 + sha256: "7eeab15ce72894e4bdba6a8765712231fc81be0bd95247de4ad9966abc57adc6" + url: "https://pub.dev" + source: hosted + version: "1.0.0" dart_style: dependency: transitive description: name: dart_style - sha256: "82ade9fc4273f29ed673e33166944465225b4f7fc5d4aaef48605cc751c18fc1" + sha256: a0e4f65339b31eb6a9e6a12e14b4682a48d46fbc54a82f4a702396fbdbac63a7 url: "https://pub.dev" source: hosted - version: "3.1.13" + version: "3.1.14" dbus: dependency: transitive description: @@ -313,22 +449,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.0" - dynamic_polls: - dependency: "direct main" - description: - name: dynamic_polls - sha256: "58cd1fafbbaba6b485a61692aa3bd33ded6f0f61734543b6c754511c362d8ae1" - url: "https://pub.dev" - source: hosted - version: "0.0.8" - encrypt: - dependency: transitive - description: - name: encrypt - sha256: "62d9aa4670cc2a8798bab89b39fc71b6dfbacf615de6cf5001fb39f7e4a996a2" - url: "https://pub.dev" - source: hosted - version: "5.0.3" equatable: dependency: transitive description: @@ -414,10 +534,10 @@ packages: dependency: transitive description: name: file_selector_ios - sha256: "97269e5307a0ab813b1fa2430bada0a96e0afb74848417f8676f64ba5de0051c" + sha256: "5b42ec0ef7626124b4624ea244341e9df780406793c204e89fa68a2e71af115c" url: "https://pub.dev" source: hosted - version: "0.5.3+6" + version: "0.5.3+7" file_selector_linux: dependency: transitive description: @@ -430,10 +550,10 @@ packages: dependency: transitive description: name: file_selector_macos - sha256: d57c62362766b5e7ae739448650b66c6aab7a68ba7ecc65e04018652645ae0f4 + sha256: d785431f1910aac8a50e5c492cae912320158030a88703c67b9ef7f1f96fd7ba url: "https://pub.dev" source: hosted - version: "0.9.5+1" + version: "0.9.5+2" file_selector_platform_interface: dependency: transitive description: @@ -479,22 +599,27 @@ packages: url: "https://pub.dev" source: hosted version: "0.9.1" + flutter_driver: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" flutter_file_dialog: dependency: "direct main" description: name: flutter_file_dialog - sha256: "5d270d69b6a5fdf45bdb88ebcf590e073dd89dfb45526ac83a64524ba57303b5" + sha256: "3765fca2a6babe983730a3105e9d652d852fe463c44bb7713344f11bec40d393" url: "https://pub.dev" source: hosted - version: "3.3.3" + version: "3.3.6" flutter_hooks: dependency: "direct main" description: name: flutter_hooks - sha256: "8ae1f090e5f4ef5cfa6670ce1ab5dddadd33f3533a7f9ba19d9f958aa2a89f42" + sha256: b4f6eb8f13fc92523023a47d4a2e541b17827535334941f9a974f10da0797a7e url: "https://pub.dev" source: hosted - version: "0.21.3+1" + version: "0.21.4" flutter_launcher_icons: dependency: "direct dev" description: @@ -503,14 +628,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.14.4" - flutter_linkify: - dependency: "direct main" - description: - name: flutter_linkify - sha256: "74669e06a8f358fee4512b4320c0b80e51cffc496607931de68d28f099254073" - url: "https://pub.dev" - source: hosted - version: "6.0.0" flutter_lints: dependency: "direct dev" description: @@ -523,47 +640,55 @@ packages: dependency: "direct main" description: name: flutter_local_notifications - sha256: "357be7ff996dc272e2037c69c1bdd5d1bd21172219d55f8bd2e11aeea602e6d3" + sha256: "7d37d69ded3028af4f22531a0097a3baa478a384dff2e23e873707c93df3b704" url: "https://pub.dev" source: hosted - version: "22.3.1" + version: "23.0.3" flutter_local_notifications_linux: dependency: transitive description: name: flutter_local_notifications_linux - sha256: "9ca97e63776f29ab1b955725c09999fc2c150523269db150c39274f2a43c5a8b" + sha256: bcbcf3c15e33b6866805092308f5f6ef27e1191874f6a92ef59213a0812a79a2 url: "https://pub.dev" source: hosted - version: "8.0.1" + version: "9.0.0" flutter_local_notifications_platform_interface: dependency: transitive description: name: flutter_local_notifications_platform_interface - sha256: "43c3761d916c9bd3d5c7ebbc44d82f4990329840c0c5d62ad5260cc1b5d399bd" + sha256: "4a49db4ce3d633ebc85c85b5fa959572600ec10bd097419c454579444308a0a0" url: "https://pub.dev" source: hosted - version: "12.2.0" + version: "13.0.0" flutter_local_notifications_web: dependency: transitive description: name: flutter_local_notifications_web - sha256: "516afaf97a2d1e67a036c6617321b00d205d72f7a67b6eccf936cd565f985878" + sha256: ef117694fbfcd82308ab0e324cfc9282fa50c192e24ec54a58173ae327ebc544 url: "https://pub.dev" source: hosted - version: "1.0.0" + version: "2.0.0" flutter_local_notifications_windows: dependency: transitive description: name: flutter_local_notifications_windows - sha256: "6f43bdd03b171b7a90f22647506fea33e2bb12294b7c7c7a3d690e960a382945" + sha256: "8e80ac29433c71e267493b397457e3a8430c5c1d9c76bb58a6971c016cdba3d7" url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "4.0.1" flutter_localizations: dependency: "direct main" description: flutter source: sdk version: "0.0.0" + flutter_map: + dependency: "direct main" + description: + name: flutter_map + sha256: "9bbe5472f66ae648d2ca2efbce97fcaa04e71261fabd3e062f26728222d7f767" + url: "https://pub.dev" + source: hosted + version: "8.3.2" flutter_plugin_android_lifecycle: dependency: transitive description: @@ -576,20 +701,20 @@ packages: dependency: "direct main" description: name: flutter_riverpod - sha256: "2b7f9d2a3c730ac1a98221b420cef966b990fca7ab546ede324642ca57a533e3" + sha256: "2ae1a93a868ae5f2d5358f521a4bfae0da7a3bfe77a60515ab5c28953b50557f" url: "https://pub.dev" source: hosted - version: "3.4.3" + version: "3.5.0" flutter_svg: dependency: "direct main" description: name: flutter_svg - sha256: "35882981abcbfb8c15b286f0cd690ff25bac12d95eff3e25ee207f37d4c42e7f" + sha256: "4565a66f0a968f2e1ab4197854686990258aadab9572eb80a7655053a01dc302" url: "https://pub.dev" source: hosted - version: "2.3.0" + version: "2.5.0" flutter_test: - dependency: transitive + dependency: "direct dev" description: flutter source: sdk version: "0.0.0" @@ -609,19 +734,20 @@ packages: fluttertagger: dependency: "direct main" description: - name: fluttertagger - sha256: "04514674b41a063b97901aedf6970d0675b828bd723a0fb9f9dba89b91953382" - url: "https://pub.dev" - source: hosted + path: "." + ref: HEAD + resolved-ref: "78a5099499728917e7595f738f3b369b47804dc5" + url: "https://github.com/Henry-Hiles/fluttertagger" + source: git version: "2.3.2" freezed: dependency: "direct dev" description: name: freezed - sha256: "3af98c92d7d4dd182ea1393193e69a840fcbaee1f66f1158bd20504e5f3f6f4f" + sha256: cb910646cb09265d49077b63b600ef1f5a718c1d6031836432237ddeabae1b12 url: "https://pub.dev" source: hosted - version: "4.0.2" + version: "4.0.3" freezed_annotation: dependency: "direct main" description: @@ -630,14 +756,11 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.0" - get_x_storage: + fuchsia_remote_debug_protocol: dependency: transitive - description: - name: get_x_storage - sha256: "597cd8f6ef8b01c747a6d95ff7b0310066f6c82ddf5565ca371f047f316fe43e" - url: "https://pub.dev" - source: hosted - version: "0.2.0" + description: flutter + source: sdk + version: "0.0.0" glob: dependency: transitive description: @@ -666,12 +789,12 @@ packages: dependency: "direct main" description: name: hooks_riverpod - sha256: d58e1e14aa112ca9c56d54effb7d0d717b2d3f96dad3cdd1fce16f8740450700 + sha256: bfafc8ca13e33e191fd3c3c2e920eed08918ef669e0b4df253b401fa78f82f47 url: "https://pub.dev" source: hosted - version: "3.4.3" + version: "3.5.0" html: - dependency: transitive + dependency: "direct main" description: name: html sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" @@ -690,10 +813,10 @@ packages: dependency: transitive description: name: http_multi_server - sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + sha256: "361668bdd71f0ae2dc6d17b75a593520f3c414af6534f9eed1aa72049dd71d18" url: "https://pub.dev" source: hosted - version: "3.2.2" + version: "3.2.3" http_parser: dependency: transitive description: @@ -714,10 +837,10 @@ packages: dependency: transitive description: name: image - sha256: "89ed75b2f8231fe676808c5564f9590d728024ded7ac782a7ed8474f1c95b72a" + sha256: bc13f61f0f5cb77936e78ae5dae3800f442718dac5d2bc4654f03c239230ed0c url: "https://pub.dev" source: hosted - version: "4.12.0" + version: "4.13.1" image_picker: dependency: "direct main" description: @@ -746,10 +869,10 @@ packages: dependency: transitive description: name: image_picker_ios - sha256: "4fb88d4350ffc208c2a09fc321db1f80282688716b8cfe10c8c80acc5ae8934a" + sha256: a4aeafbe049ad99882059f186862de6fd5296c708c5805277f6f684165268af1 url: "https://pub.dev" source: hosted - version: "0.8.13+10" + version: "0.8.13+16" image_picker_linux: dependency: transitive description: @@ -782,6 +905,11 @@ packages: url: "https://pub.dev" source: hosted version: "0.2.2" + integration_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" intl: dependency: "direct main" description: @@ -798,14 +926,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" - js: + jni: dependency: transitive description: - name: js - sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" + name: jni + sha256: "19764f78f6b9e0d40f6395b04649d1046eb57f5ccf05afce50cc63e5a82777b0" url: "https://pub.dev" source: hosted - version: "0.7.2" + version: "1.2.1" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "586594ad345b403bda8a794b0b8a9e34298238b86c2a7d7f15160b092fe9ef3d" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + jni_util: + dependency: transitive + description: + name: jni_util + sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" + url: "https://pub.dev" + source: hosted + version: "1.0.0" json_annotation: dependency: "direct main" description: @@ -818,10 +962,18 @@ packages: dependency: "direct dev" description: name: json_serializable - sha256: e45aefa0324f08c683caafbb94b72837aa6193c61822799c916e45f4a263113d + sha256: cc7822761b40be9237bcaae62b755ffe5453ceff96a0001f1f5f2439251c66f1 url: "https://pub.dev" source: hosted - version: "6.14.1" + version: "6.15.2" + latlong2: + dependency: "direct main" + description: + name: latlong2 + sha256: "84b776b100a84a684a0aaa3fa4dc2c9b1931c658de533701ee4e09bfa991f8dc" + url: "https://pub.dev" + source: hosted + version: "0.10.1" leak_tracker: dependency: transitive description: @@ -871,6 +1023,31 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.1" + location: + dependency: "direct main" + description: + path: "packages/location" + ref: "feat/optional-play-services" + resolved-ref: "1a2602a9f7b07906a1191730d5435f4b695547d3" + url: "https://github.com/Henry-Hiles/flutterlocation" + source: git + version: "10.2.0" + location_platform_interface: + dependency: transitive + description: + name: location_platform_interface + sha256: a47b6d790eeb7308147293aedec0efb3b62d9f1b10899679be04f91cff664821 + url: "https://pub.dev" + source: hosted + version: "7.1.0" + location_web: + dependency: transitive + description: + name: location_web + sha256: da3812c65ca683c6180790838f551de10122a4887ffbd569360c9cb2d85859b7 + url: "https://pub.dev" + source: hosted + version: "7.0.1" logging: dependency: transitive description: @@ -883,10 +1060,10 @@ packages: dependency: "direct main" description: name: m3e_buttons - sha256: dca780e813563754576194ed18e3f6a33422ed136c8d4ccfeca20909edddd728 + sha256: "25eac5e0afdb88673499c243a863fbf0bbb64c0073e9a8784c1937626a31e412" url: "https://pub.dev" source: hosted - version: "1.0.3" + version: "1.0.4" m3e_card_list: dependency: "direct main" description: @@ -912,6 +1089,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.12.20" + material_adaptive_sheets: + dependency: "direct main" + description: + name: material_adaptive_sheets + sha256: "9299e8dfa7459583516520db1fe0edec83ab306679c3cfd3d0848f666bc956e5" + url: "https://pub.dev" + source: hosted + version: "1.0.0" material_color_utilities: dependency: transitive description: @@ -924,18 +1109,18 @@ packages: dependency: "direct main" description: name: material_emoji_picker - sha256: "738e70a8d2f592be05dd9889037cc6098a63e0d8c48723125848865ab305f138" + sha256: "7da8621cc827b9f0327f05a3cb22fe638945bd6a278c7bcf9112673a1c2bff90" url: "https://pub.dev" source: hosted - version: "1.2.0" + version: "2.0.1+1" material_ui: dependency: "direct main" description: name: material_ui - sha256: "98ab9eda579ecae623e4b376c603035c5def78ce706f735f30bd632af5814695" + sha256: a6b19012df437a356cbc01f8ea22a105e07194c47c9a6009da0032a0ce35c4ab url: "https://pub.dev" source: hosted - version: "1.6.0" + version: "1.11.1" measure_size: dependency: "direct main" description: @@ -944,70 +1129,6 @@ packages: url: "https://pub.dev" source: hosted version: "5.0.2" - media_kit: - dependency: "direct main" - description: - name: media_kit - sha256: ae9e79597500c7ad6083a3c7b7b7544ddabfceacce7ae5c9709b0ec16a5d6643 - url: "https://pub.dev" - source: hosted - version: "1.2.6" - media_kit_libs_android_video: - dependency: transitive - description: - name: media_kit_libs_android_video - sha256: "3f6274e5ab2de512c286a25c327288601ee445ed8ac319e0ef0b66148bd8f76c" - url: "https://pub.dev" - source: hosted - version: "1.3.8" - media_kit_libs_ios_video: - dependency: transitive - description: - name: media_kit_libs_ios_video - sha256: b5382994eb37a4564c368386c154ad70ba0cc78dacdd3fb0cd9f30db6d837991 - url: "https://pub.dev" - source: hosted - version: "1.1.4" - media_kit_libs_linux: - dependency: transitive - description: - name: media_kit_libs_linux - sha256: "2b473399a49ec94452c4d4ae51cfc0f6585074398d74216092bf3d54aac37ecf" - url: "https://pub.dev" - source: hosted - version: "1.2.1" - media_kit_libs_macos_video: - dependency: transitive - description: - name: media_kit_libs_macos_video - sha256: f26aa1452b665df288e360393758f84b911f70ffb3878032e1aabba23aa1032d - url: "https://pub.dev" - source: hosted - version: "1.1.4" - media_kit_libs_video: - dependency: "direct main" - description: - name: media_kit_libs_video - sha256: "2b235b5dac79c6020e01eef5022c6cc85fedc0df1738aadc6ea489daa12a92a9" - url: "https://pub.dev" - source: hosted - version: "1.0.7" - media_kit_libs_windows_video: - dependency: transitive - description: - name: media_kit_libs_windows_video - sha256: dff76da2778729ab650229e6b4ec6ec111eb5151431002cbd7ea304ff1f112ab - url: "https://pub.dev" - source: hosted - version: "1.0.11" - media_kit_video: - dependency: "direct main" - description: - name: media_kit_video - sha256: afaa509e7b7e0bf247557a3a740cde903a52c34ace9810f94500e127bd7b043d - url: "https://pub.dev" - source: hosted - version: "2.0.1" meta: dependency: transitive description: @@ -1016,6 +1137,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.0" + mgrs_dart: + dependency: transitive + description: + name: mgrs_dart + sha256: "385e7168ecc77eb545220223c49eef8ab249da7bf57f22781c40a04d23fb196f" + url: "https://pub.dev" + source: hosted + version: "3.0.0" mime: dependency: "direct main" description: @@ -1032,39 +1161,47 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + multi_state_switch: + dependency: "direct main" + description: + name: multi_state_switch + sha256: "501890f46d33d6cba6a84eb8f1689dba180a264ce3373fa689f75f4887d822fd" + url: "https://pub.dev" + source: hosted + version: "1.1.0" native_toolchain_c: dependency: transitive description: name: native_toolchain_c - sha256: "90eaad8059ebc2004a63810a4696ea9acdb02473e47ed3b6b3bafb100ac77e31" + sha256: "120b6fc66acd8a5ddeaeb1e59b78836bb3ec9919bd9d9dfb1e2401985710c2c0" url: "https://pub.dev" source: hosted - version: "0.19.5" + version: "0.19.6" native_toolchain_cmake: dependency: "direct overridden" description: path: "." - ref: "quad/fix/native-aarch64" - resolved-ref: ecc5b48feab382d2bd2dfe70321c692213ee5218 - url: "https://github.com/Henry-Hiles/native_toolchain_cmake" + ref: HEAD + resolved-ref: d77984a36a16be22e911850de2cd2050610ff4ed + url: "https://github.com/rainyl/native_toolchain_cmake" source: git version: "0.3.2" nativeapi: dependency: transitive description: name: nativeapi - sha256: c4625e81f5ce2f4a9044c0ec1bdb38355119ffcf89e24eb20ae9fc5027a01e59 + sha256: "118045bb549cb6fabad472a3a22a537e7310bbf20097350f5027808b4a5853ce" url: "https://pub.dev" source: hosted - version: "0.5.2" + version: "0.5.10" nativeapi_flutter: dependency: transitive description: name: nativeapi_flutter - sha256: "4feaa68cb5c4fc3b2eeaee1a25e56e2d092178e1c59516d9db5dd34940dcf36c" + sha256: "357a405c69212f5157da1bd3be183a53c2b841d0de0eb51f4a3947913712aec4" url: "https://pub.dev" source: hosted - version: "0.5.2" + version: "0.5.10" navigation_rail_m3e: dependency: "direct main" description: @@ -1078,10 +1215,10 @@ packages: dependency: transitive description: name: objective_c - sha256: "5c80c2ad6e2c0397de5db38c6d653e69616a3397e13aa7633bf39eb668f2041b" + sha256: c965d264fd4b0b4dd402dce9d049b70656bf98d3ca108b9bc55d2544ceadbe5e url: "https://pub.dev" source: hosted - version: "9.6.2" + version: "9.6.4" package_config: dependency: transitive description: @@ -1109,11 +1246,12 @@ packages: pasteboard: dependency: "direct main" description: - name: pasteboard - sha256: fedbe8da188d2f713aa8b01260737342e6e1087534a3ab26e1a719f8d3e8f32f - url: "https://pub.dev" - source: hosted - version: "0.5.0" + path: "packages/pasteboard" + ref: HEAD + resolved-ref: e79a0ecc741b80575f38465c02eba9c553e12479 + url: "https://github.com/Henry-Hiles/flutter-plugins" + source: git + version: "0.6.1" path: dependency: "direct main" description: @@ -1139,13 +1277,13 @@ packages: source: hosted version: "2.1.6" path_provider_android: - dependency: "direct overridden" + dependency: transitive description: name: path_provider_android - sha256: "149441ca6e4f38193b2e004c0ca6376a3d11f51fa5a77552d8bd4d2b0c0912ba" + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" url: "https://pub.dev" source: hosted - version: "2.2.23" + version: "2.3.1" path_provider_foundation: dependency: transitive description: @@ -1202,14 +1340,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.8" - pointycastle: - dependency: transitive - description: - name: pointycastle - sha256: "4be0097fcf3fd3e8449e53730c631200ebc7b88016acecab2b0da2f0149222fe" - url: "https://pub.dev" - source: hosted - version: "3.9.1" pool: dependency: transitive description: @@ -1222,10 +1352,10 @@ packages: dependency: transitive description: name: posix - sha256: bc1bad54ad2b735816e31f8d4600cfde6c7839975085ddfbca48b6c9f7c4044e + sha256: "613646d076944f3acc125830af935b48d4b8a57a388691547bbfd25b434f4d63" url: "https://pub.dev" source: hosted - version: "6.5.2" + version: "6.5.4" process: dependency: transitive description: @@ -1234,6 +1364,14 @@ packages: url: "https://pub.dev" source: hosted version: "5.0.6" + proj4dart: + dependency: transitive + description: + name: proj4dart + sha256: ddcedc1f7876e62717de43ab3491e2829bdad0b028261805f94aa080967e5859 + url: "https://pub.dev" + source: hosted + version: "3.0.0" pub_semver: dependency: transitive description: @@ -1246,10 +1384,10 @@ packages: dependency: transitive description: name: pubspec_parse - sha256: c38b81cbf34450b67e0265d73433569d12e34782e30ed769c9cc99c9d5f2e796 + sha256: "9ac81c01ffd6a9cf9b2713288834fbaaf6aebde05ffdf02d380e68b8e06f27d8" url: "https://pub.dev" source: hosted - version: "1.6.0" + version: "1.7.0" quiver: dependency: transitive description: @@ -1270,42 +1408,26 @@ packages: dependency: transitive description: name: riverpod - sha256: "484dfc873ea4c4f4240e5635444fa066f87b07862b7279ebd004a2b71fba4b7a" + sha256: "24cbce92e87088cae0dd06caac3876c0b3abfd084901e7a93a3254d6daf4937d" url: "https://pub.dev" source: hosted - version: "3.4.3" + version: "3.5.0" riverpod_analyzer_utils: dependency: transitive description: name: riverpod_analyzer_utils - sha256: bb13cb3985815840cc103eda1027158358c5fdc00f308fc6f76574d0594107af + sha256: a9ac757dd927b8b52ee4d3c5f8b7ecba523e140a8df916a88d5d54fef5bff72f url: "https://pub.dev" source: hosted - version: "1.0.0-dev.12" + version: "1.0.0" riverpod_lint: dependency: "direct dev" description: name: riverpod_lint - sha256: "215cb3cd54a97e09bc3512535fa4e8bedd3bf2a06dc2ae015ac8e0050fc71bd1" + sha256: "948ad74ce14bac286be014483891fb65a5584a353b0f77dd7d493a8f7880cd41" url: "https://pub.dev" source: hosted - version: "3.1.9" - rxdart: - dependency: transitive - description: - name: rxdart - sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" - url: "https://pub.dev" - source: hosted - version: "0.28.0" - safe_local_storage: - dependency: transitive - description: - name: safe_local_storage - sha256: "494b982d5edb71030650ea463d939670e91b232b588323dc75229d2c5f23e7b7" - url: "https://pub.dev" - source: hosted - version: "2.0.6" + version: "3.2.0" shared_preferences: dependency: "direct main" description: @@ -1318,18 +1440,18 @@ packages: dependency: transitive description: name: shared_preferences_android - sha256: "1e12aafe408aa50da80edfd679a2a6bf63ba7ab37c7fa98286da459a757b3399" + sha256: "137dedccacb394b8f470d6c9b435ffc3d33faaa6ce2949c4f54a61007d64396d" url: "https://pub.dev" source: hosted - version: "2.4.28" + version: "2.5.5" shared_preferences_foundation: dependency: transitive description: name: shared_preferences_foundation - sha256: "2ec3934efa51e46117f23031cc141b8fc878e8525b94ec1ea4f7f586cf1b47ea" + sha256: "89435cb71ecb1ad1bf29ef73a381f871a06f433d4182b7e2ba7243b02b2c544b" url: "https://pub.dev" source: hosted - version: "2.5.7" + version: "2.6.2" shared_preferences_linux: dependency: transitive description: @@ -1339,7 +1461,7 @@ packages: source: hosted version: "2.4.1" shared_preferences_platform_interface: - dependency: transitive + dependency: "direct dev" description: name: shared_preferences_platform_interface sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" @@ -1366,10 +1488,10 @@ packages: dependency: transitive description: name: shelf - sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + sha256: e75e9cf311d7fd712048038cc17c25199c38536c20330d53e7db058b543d5a48 url: "https://pub.dev" source: hosted - version: "1.4.2" + version: "1.4.3" shelf_web_socket: dependency: transitive description: @@ -1378,6 +1500,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.0" + simple_sparse_list: + dependency: transitive + description: + name: simple_sparse_list + sha256: aa648fd240fa39b49dcd11c19c266990006006de6699a412de485695910fbc1f + url: "https://pub.dev" + source: hosted + version: "0.1.4" sky_engine: dependency: transitive description: flutter @@ -1387,18 +1517,18 @@ packages: dependency: transitive description: name: source_gen - sha256: "11b6047da8e4eb6c643ccac3d0fda3f9c9e11651695f7da24a85ade8aff15a44" + sha256: "833ea7d15b5be79949d3d6c077da0267a0bd93c16897b36a771395a91e63086e" url: "https://pub.dev" source: hosted - version: "4.3.0" + version: "4.3.1" source_helper: dependency: transitive description: name: source_helper - sha256: "5e6f216fdf6376c9f3852381ae037499797a3385377d388b011dac98d303c67c" + sha256: "279126bce72de3f2b7d4756408a4157988cf6bb4815be551bf55851aa00e9984" url: "https://pub.dev" source: hosted - version: "1.3.13" + version: "1.4.0" source_span: dependency: transitive description: @@ -1455,14 +1585,22 @@ packages: url: "https://pub.dev" source: hosted version: "0.4.1" + sync_http: + dependency: transitive + description: + name: sync_http + sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961" + url: "https://pub.dev" + source: hosted + version: "0.3.1" synchronized: dependency: transitive description: name: synchronized - sha256: "397b146f97613b83d84bdccb439bc8d0f3aebb6c1d14a9641e6f24201c490b2d" + sha256: a77637ebe1460f3b48cac89a790d2eb634f0a8593cab0d3f340c6db174ba9b94 url: "https://pub.dev" source: hosted - version: "3.4.2" + version: "3.6.1+1" term_glyph: dependency: transitive description: @@ -1491,10 +1629,10 @@ packages: dependency: "direct main" description: name: timezone - sha256: "981d1020d6ef8fe1e7b3de5054e5b25579ae7c403d7734adc508ffc47668e9cb" + sha256: "9f4e5a1a0e4fef7dd3424842c0575db01bfb7a11730e8d55753fcd5c5c98767b" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "0.11.2" typed_data: dependency: transitive description: @@ -1503,6 +1641,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + unicode: + dependency: transitive + description: + name: unicode + sha256: a6f7bcfc8ea1d5ce1f6c0b1c39117a9919f4953edd9fd7a64090a9796c499b57 + url: "https://pub.dev" + source: hosted + version: "1.1.9" unifiedpush: dependency: "direct main" description: @@ -1553,22 +1699,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.0" - universal_platform: - dependency: transitive - description: - name: universal_platform - sha256: "64e16458a0ea9b99260ceb5467a214c1f298d647c659af1bff6d3bf82536b1ec" - url: "https://pub.dev" - source: hosted - version: "1.1.0" - uri_parser: - dependency: transitive - description: - name: uri_parser - sha256: "051c62e5f693de98ca9f130ee707f8916e2266945565926be3ff20659f7853ce" - url: "https://pub.dev" - source: hosted - version: "3.0.2" url_launcher: dependency: "direct main" description: @@ -1581,10 +1711,10 @@ packages: dependency: transitive description: name: url_launcher_android - sha256: "611e87fb320b70d1dd721dc46af89c98aceccea9b31fde49e084591414e0c610" + sha256: b8073b1e5173d63afe1a18985a75896d72f759d3bc1817eb1ae8d26e8527cceb url: "https://pub.dev" source: hosted - version: "6.3.33" + version: "6.3.35" url_launcher_ios: dependency: transitive description: @@ -1610,7 +1740,7 @@ packages: source: hosted version: "3.2.6" url_launcher_platform_interface: - dependency: transitive + dependency: "direct dev" description: name: url_launcher_platform_interface sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" @@ -1645,42 +1775,50 @@ packages: dependency: transitive description: name: vector_graphics - sha256: "9d0e3b9cb16542ad660daee871e726a10d13a93b7b5391677c3160e8f5e83935" + sha256: "06081e4f2d8f17c306aa58989520694b463ad411bc7c7b93e76afa3e41ca17ac" url: "https://pub.dev" source: hosted - version: "1.2.3" + version: "1.3.1" vector_graphics_codec: dependency: transitive description: name: vector_graphics_codec - sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146" + sha256: "023f3afd1b08d040406e7ccc324f5173c04762a59e374f29d04cef00a4940742" url: "https://pub.dev" source: hosted - version: "1.1.13" + version: "1.2.0" vector_graphics_compiler: dependency: transitive description: name: vector_graphics_compiler - sha256: "4dca4feb77dc3ec7f6e27e49c53241eb8217f55e4f9b12599a27f8903bca5682" + sha256: "4c9d2e7121eea8b4f160e6e435900a0ae7214cfc97c2d6cf84c25532b789b50d" url: "https://pub.dev" source: hosted - version: "1.3.0" + version: "1.3.4" vector_math: dependency: transitive description: name: vector_math - sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d" + sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc url: "https://pub.dev" source: hosted - version: "2.4.3" + version: "2.4.4" + visibility_detector: + dependency: transitive + description: + name: visibility_detector + sha256: dd5cc11e13494f432d15939c3aa8ae76844c42b723398643ce9addb88a5ed420 + url: "https://pub.dev" + source: hosted + version: "0.4.0+2" vm_service: dependency: transitive description: name: vm_service - sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0" + sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" url: "https://pub.dev" source: hosted - version: "15.3.0" + version: "15.4.0" wakelock_plus: dependency: transitive description: @@ -1709,10 +1847,10 @@ packages: dependency: transitive description: name: web - sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b url: "https://pub.dev" source: hosted - version: "1.1.1" + version: "1.1.2" web_socket: dependency: transitive description: @@ -1732,12 +1870,19 @@ packages: webcrypto: dependency: "direct overridden" description: - path: "." - ref: "fix/apple-x86_64-fiat-asm-upstream" - resolved-ref: e50fcce3d0c30627b11ffc74eb964b1073d42620 - url: "https://github.com/DavidClaudeAI/webcrypto.dart" - source: git - version: "0.6.2-wip" + name: webcrypto + sha256: bdfa2b11696f2bac02834649d9e07d24a5154e527feec21ed1bdf81b31f982df + url: "https://pub.dev" + source: hosted + version: "0.6.2" + webdriver: + dependency: transitive + description: + name: webdriver + sha256: "28b82ec894fed45dd71c23ba62d1af973ed97dd59a4f5790a4d38b0b13e5657e" + url: "https://pub.dev" + source: hosted + version: "3.2.0" webpush_encryption: dependency: transitive description: @@ -1757,12 +1902,19 @@ packages: window_manager: dependency: "direct main" description: - path: "." - ref: HEAD - resolved-ref: "80acd536a1ea1c121c36e32d30e638a295087ed1" - url: "https://github.com/leanflutter/window_manager" - source: git + name: window_manager + sha256: bdd6b1a2c1ce50f3bba7ffbaa0d5dc5feb6b6a24fd20269da4de90244f77a471 + url: "https://pub.dev" + source: hosted version: "0.6.0" + wkt_parser: + dependency: transitive + description: + name: wkt_parser + sha256: "8a555fc60de3116c00aad67891bcab20f81a958e4219cc106e3c037aa3937f13" + url: "https://pub.dev" + source: hosted + version: "2.0.0" xdg_desktop_portal: dependency: "direct main" description: @@ -1806,4 +1958,4 @@ packages: version: "2.2.4" sdks: dart: "3.13.3" - flutter: ">=3.47.0" + flutter: "3.47.4" diff --git a/pubspec.yaml b/pubspec.yaml index 11c4808..dd21cb7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: nexus description: "A simple and user-friendly Matrix client" -version: 1.0.0 +version: 1.1.3+101030999 publish_to: none flutter: @@ -17,19 +17,15 @@ flutter: environment: sdk: 3.13.3 + flutter: 3.47.4 dependency_overrides: - path_provider_android: 2.2.23 # Pinned to avoid JNI dynamic_color: 2.1.0 - code_assets: 2.1.0 # webcrypto requires ^1.0.0, but works with 2.x - webcrypto: - git: - url: https://github.com/DavidClaudeAI/webcrypto.dart - ref: fix/apple-x86_64-fiat-asm-upstream # Uses build hooks and fixes macOS x86_64, unreleased + code_assets: 2.2.0 # webcrypto requires ^1.0.0, but works with 2.x + webcrypto: 0.6.2 native_toolchain_cmake: git: - url: https://github.com/Henry-Hiles/native_toolchain_cmake - ref: quad/fix/native-aarch64 # Fixes native aarch64 linux builds + url: https://github.com/rainyl/native_toolchain_cmake # Fixes native aarch64 linux builds, unreleased m3e_design: git: url: https://github.com/Henry-Hiles/material_3_expressive @@ -48,21 +44,22 @@ dependency_overrides: url: https://codeberg.org/Henry-Hiles/flutter-connector ref: quad/nexus path: unifiedpush_platform_interface + pasteboard: + git: + url: https://github.com/Henry-Hiles/flutter-plugins # FileTransfer portal support on Linux, unreleased + path: packages/pasteboard linkify: git: url: https://github.com/appelladev/linkify ref: fix/consecutive-periods-loose-url - window_manager: - git: - url: https://github.com/leanflutter/window_manager dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter - flutter_riverpod: 3.4.3 - hooks_riverpod: 3.4.3 + flutter_riverpod: 3.5.0 + hooks_riverpod: 3.5.0 intl: 0.20.3 fast_immutable_collections: 11.2.1 path_provider: 2.1.6 @@ -72,30 +69,28 @@ dependencies: path: 1.9.1 dynamic_color: 2.1.0 collection: 1.19.1 - window_manager: 0.5.2 + window_manager: 0.6.0 color_hash: 1.0.1 flutter_widget_from_html_core: 0.18.0-beta.1 - flutter_svg: 2.3.0 + flutter_svg: 2.5.0 json_annotation: 4.12.0 shared_preferences: 2.5.6 - fluttertagger: 2.3.2 - dynamic_polls: 0.0.8 - flutter_hooks: 0.21.3+1 + fluttertagger: + git: + url: https://github.com/Henry-Hiles/fluttertagger # Fixes the last tag search being dropped from formattedText + flutter_hooks: 0.21.4 ffi: 2.2.0 hooks: 2.2.0 - code_assets: 2.1.0 + code_assets: 2.2.0 ffigen: 23.0.0 timeago: 3.7.1 http: 1.6.0 - flutter_linkify: 6.0.0 linkify: 5.0.0 + html: 0.15.7 flutter_blurhash: 0.9.1 super_sliver_list: 0.4.1 - media_kit: 1.2.6 - media_kit_video: 2.0.1 - media_kit_libs_video: 1.0.7 measure_size: 5.0.2 - m3e_buttons: 1.0.3 + m3e_buttons: 1.0.4 m3e_design: 0.2.1 navigation_rail_m3e: git: @@ -106,27 +101,45 @@ dependencies: package_info_plus: 10.2.2 app_links: 7.2.2 file_selector: 1.1.0 - material_ui: 1.6.0 + material_ui: 1.11.1 + multi_state_switch: 1.1.0 unifiedpush: 6.2.0 unifiedpush_storage_shared_preferences: 1.0.0 - flutter_local_notifications: 22.3.1 - timezone: 0.11.1 - material_emoji_picker: 1.2.0 + flutter_local_notifications: 23.0.3 + timezone: 0.11.2 + material_emoji_picker: 2.0.1+1 + material_adaptive_sheets: 1.0.0 xdg_desktop_portal: git: url: https://github.com/Henry-Hiles/xdg_desktop_portal.dart ref: quad/nexus - pasteboard: 0.5.0 - flutter_file_dialog: 3.3.3 + pasteboard: 0.6.0 + flutter_file_dialog: 3.3.6 mime: 2.1.0 - avif_native: 0.1.1 + avif_native: 0.2.0 + flutter_map: 8.3.2 + latlong2: 0.10.1 + location: + git: + url: https://github.com/Henry-Hiles/flutterlocation # Adds an option to leave out proprietary Google Play services, unreleased + ref: feat/optional-play-services + path: packages/location + better_player: 1.38.0 + audioplayers: 6.8.1 dev_dependencies: - build_runner: 2.16.2 + flutter_test: + sdk: flutter + integration_test: + sdk: flutter + app_links_platform_interface: 2.0.4 + url_launcher_platform_interface: 2.3.2 + shared_preferences_platform_interface: 2.4.2 + build_runner: 2.17.1 flutter_lints: 6.0.0 - freezed: 4.0.2 - riverpod_lint: 3.1.9 + freezed: 4.0.3 + riverpod_lint: 3.2.0 flutter_launcher_icons: 0.14.4 - json_serializable: 6.14.1 + json_serializable: 6.15.2 flutter_launcher_icons: image_path: assets/icon.png diff --git a/scripts/build_avif_native.sh b/scripts/build_avif_native.sh new file mode 100644 index 0000000..e94f87c --- /dev/null +++ b/scripts/build_avif_native.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "${PUB_CACHE:-$HOME/.pub-cache}"/hosted/pub.dev/avif_native-* + +bash tool/native/build_unix.sh android-arm64 decode-dav1d + +library=dist/android-arm64/decode-dav1d/libavif_native.so +jq --arg path "../$library" --arg hash "$(sha256sum "$library" | cut -d " " -f 1)" \ + '.artifacts["android-arm64-decode-dav1d"] |= {path: $path, librarySha256: $hash, fileName}' \ + native/manifest.json > manifest.json +mv manifest.json native/manifest.json diff --git a/scripts/release.sh b/scripts/release.sh new file mode 100755 index 0000000..01e2683 --- /dev/null +++ b/scripts/release.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail + +version=${1:?usage: $0 , e.g. 1.2.0 or 1.2.0-beta1} +[[ $version =~ ^([0-9]+)\.([0-9]{1,2})\.([0-9]{1,2})(-[a-z]+([0-9]{1,3}))?$ ]] || + { echo "invalid version: $version" >&2; exit 1; } +prerelease=${BASH_REMATCH[5]:-} + +code=$((10#${BASH_REMATCH[1]} * 100000000 + 10#${BASH_REMATCH[2]} * 1000000 + 10#${BASH_REMATCH[3]} * 10000 + 10#${prerelease:-999})) + +cd "$(dirname "$0")/.." +git diff --quiet HEAD || { echo "commit or stash your changes first" >&2; exit 1; } +! git rev-parse -q --verify "refs/tags/v$version" > /dev/null || { echo "v$version already exists" >&2; exit 1; } + +sed -i "s/^version: .*/version: $version+$code/" pubspec.yaml +sed -i "s/^AppVersion=.*/AppVersion=$version/" windows/installer.iss +if [[ $prerelease ]]; then + release="" +else + release="" + sed -i "s|refs/tags/v[^\"]*\"|refs/tags/v$version\"|" README.md +fi +sed -i "s|^\( *\)|&\n\1 $release|" linux/nexus.federated.nexus.metainfo.xml + +git commit -qam "prepare v$version" +git tag "v$version" +echo "Tagged v$version ($code). Push with: git push origin HEAD v$version" diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 7dc1c3c..b63c950 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -7,24 +7,27 @@ #include "generated_plugin_registrant.h" #include +#include +#include #include #include -#include -#include +#include #include #include void RegisterPlugins(flutter::PluginRegistry* registry) { AppLinksPluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("AppLinksPluginCApi")); + AudioplayersWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin")); + BetterPlayerWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("BetterPlayerWindowsPlugin")); DynamicColorPluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("DynamicColorPluginCApi")); FileSelectorWindowsRegisterWithRegistrar( registry->GetRegistrarForPlugin("FileSelectorWindows")); - MediaKitLibsWindowsVideoPluginCApiRegisterWithRegistrar( - registry->GetRegistrarForPlugin("MediaKitLibsWindowsVideoPluginCApi")); - MediaKitVideoPluginCApiRegisterWithRegistrar( - registry->GetRegistrarForPlugin("MediaKitVideoPluginCApi")); + LocationPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("LocationPlugin")); PasteboardPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("PasteboardPlugin")); UrlLauncherWindowsRegisterWithRegistrar( diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index 68413e7..b6e3eef 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -4,16 +4,18 @@ list(APPEND FLUTTER_PLUGIN_LIST app_links + audioplayers_windows + better_player_windows dynamic_color file_selector_windows - media_kit_libs_windows_video - media_kit_video + location pasteboard url_launcher_windows ) list(APPEND FLUTTER_FFI_PLUGIN_LIST flutter_local_notifications_windows + jni ) set(PLUGIN_BUNDLED_LIBRARIES) diff --git a/windows/installer.iss b/windows/installer.iss index 22f4dcf..e1a08c0 100644 --- a/windows/installer.iss +++ b/windows/installer.iss @@ -1,6 +1,6 @@ [Setup] AppName=Nexus -AppVersion=1.0.0 +AppVersion=1.1.3 DefaultDirName={pf}\Nexus DefaultGroupName=Nexus OutputDir=dist @@ -18,4 +18,6 @@ Name: "{commondesktop}\Nexus"; Filename: "{app}\nexus.exe" [Registry] Root: HKCU; Subkey: "Software\Classes\nexus.federated.nexus"; ValueType: string; ValueName: "URL Protocol"; ValueData: "" -Root: HKCU; Subkey: "Software\Classes\nexus.federated.nexus\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\nexus.exe"" ""%1""" \ No newline at end of file +Root: HKCU; Subkey: "Software\Classes\nexus.federated.nexus\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\nexus.exe"" ""%1""" +Root: HKCU; Subkey: "Software\Classes\matrix"; ValueType: string; ValueName: "URL Protocol"; ValueData: "" +Root: HKCU; Subkey: "Software\Classes\matrix\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\nexus.exe"" ""%1"""