mirror of
https://github.com/bulwarkmail/native.git
synced 2026-11-01 16:05:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e574fd9e11 | ||
|
|
dfa278f7a8 | ||
|
|
4eeda34d95 | ||
|
|
22ad291202 | ||
|
|
f040a48e2f | ||
|
|
c29cbcd549 | ||
|
|
bf67b97176 | ||
|
|
a2484f3508 | ||
|
|
82997e27e4 | ||
|
|
802e1e1c71 | ||
|
|
2427bdbd79 | ||
|
|
05e2af23dd | ||
|
|
42f18a78b2 | ||
|
|
406d2c208a | ||
|
|
6f712bf43f | ||
|
|
844cb703c8 | ||
|
|
11e5963149 | ||
|
|
07438e010e | ||
|
|
3e33efb71f | ||
|
|
376ee3d678 | ||
|
|
6f19cdbd17 | ||
|
|
6985a7d5f6 | ||
|
|
8231a55acb | ||
|
|
1b0740eab4 | ||
|
|
c5e509274d | ||
|
|
1bf5920b04 | ||
|
|
2547c6f199 | ||
|
|
69e27a386c | ||
|
|
7390096567 | ||
|
|
58c642f27b | ||
|
|
b1d1e84666 | ||
|
|
55484453a1 | ||
|
|
b525c52870 | ||
|
|
b64afb462f | ||
|
|
b92f85a236 | ||
|
|
643d704b74 | ||
|
|
9e383c3616 | ||
|
|
1543db49d1 | ||
|
|
910e5418e9 | ||
|
|
a019d9e775 | ||
|
|
e6d47b6a16 | ||
|
|
b10f61a642 | ||
|
|
752aa719d8 | ||
|
|
5884a18979 | ||
|
|
3ccc83e7ce | ||
|
|
5dc4ea1a45 |
@@ -0,0 +1,274 @@
|
||||
name: Release iOS (TestFlight)
|
||||
|
||||
# The iOS project is NOT committed - unlike android/, which is hand-maintained,
|
||||
# ios/ is gitignored and generated fresh by `expo prebuild` on every run. Keep
|
||||
# any native iOS change in app.config.js (or a config plugin), never in ios/.
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
upload_to_testflight:
|
||||
description: "Upload the build to TestFlight (off = build the IPA only)"
|
||||
type: boolean
|
||||
required: false
|
||||
default: true
|
||||
|
||||
concurrency:
|
||||
group: release-ios-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: macos-latest
|
||||
timeout-minutes: 90
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
EXPO_NO_TELEMETRY: "1"
|
||||
# App Store Connect refuses a CFBundleVersion it has already seen for this
|
||||
# marketing version, so every run needs a fresh, increasing number.
|
||||
IOS_BUILD_NUMBER: ${{ github.run_number }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
- name: Show toolchain versions
|
||||
run: |
|
||||
xcodebuild -version
|
||||
pod --version
|
||||
|
||||
- name: Cache CocoaPods
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/Library/Caches/CocoaPods
|
||||
~/.cocoapods/repos
|
||||
key: pods-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
|
||||
restore-keys: pods-${{ runner.os }}-
|
||||
|
||||
- name: Install JS dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Generate the iOS project
|
||||
run: npx expo prebuild --platform ios --clean
|
||||
|
||||
- name: Check for signing credentials
|
||||
id: creds
|
||||
env:
|
||||
CERT: ${{ secrets.IOS_DIST_CERT_BASE64 }}
|
||||
ASC_KEY: ${{ secrets.APP_STORE_CONNECT_PRIVATE_KEY }}
|
||||
TEAM: ${{ secrets.APPLE_TEAM_ID }}
|
||||
PROFILE: ${{ secrets.IOS_PROVISIONING_PROFILE_BASE64 }}
|
||||
run: |
|
||||
if [ -n "$CERT" ] && [ -n "$ASC_KEY" ] && [ -n "$TEAM" ] && [ -n "$PROFILE" ]; then
|
||||
echo "signed=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "signed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "::notice::Signing secrets are not configured - compiling without signing. No IPA will be produced."
|
||||
fi
|
||||
|
||||
- name: Resolve workspace and scheme
|
||||
id: xcode
|
||||
run: |
|
||||
WORKSPACE=$(ls -d ios/*.xcworkspace | head -1)
|
||||
SCHEME=$(basename "$WORKSPACE" .xcworkspace)
|
||||
echo "workspace=$WORKSPACE" >> "$GITHUB_OUTPUT"
|
||||
echo "scheme=$SCHEME" >> "$GITHUB_OUTPUT"
|
||||
echo "Using workspace $WORKSPACE, scheme $SCHEME"
|
||||
|
||||
# ── Unsigned path: a compile check only, so the workflow is still useful
|
||||
# on forks and before the Apple secrets exist.
|
||||
- name: Build without signing
|
||||
if: steps.creds.outputs.signed != 'true'
|
||||
run: |
|
||||
xcodebuild build \
|
||||
-workspace "${{ steps.xcode.outputs.workspace }}" \
|
||||
-scheme "${{ steps.xcode.outputs.scheme }}" \
|
||||
-configuration Release \
|
||||
-destination 'generic/platform=iOS' \
|
||||
CODE_SIGNING_ALLOWED=NO \
|
||||
CODE_SIGNING_REQUIRED=NO \
|
||||
CODE_SIGN_IDENTITY=""
|
||||
|
||||
# ── Signed path ────────────────────────────────────────────
|
||||
- name: Import the distribution certificate
|
||||
if: steps.creds.outputs.signed == 'true'
|
||||
env:
|
||||
CERT_BASE64: ${{ secrets.IOS_DIST_CERT_BASE64 }}
|
||||
CERT_PASSWORD: ${{ secrets.IOS_DIST_CERT_PASSWORD }}
|
||||
run: |
|
||||
KEYCHAIN="$RUNNER_TEMP/build.keychain-db"
|
||||
# Ephemeral runner, ephemeral keychain - this password protects nothing
|
||||
# beyond the life of the job.
|
||||
KEYCHAIN_PASSWORD=$(uuidgen)
|
||||
security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN"
|
||||
security set-keychain-settings -lut 21600 "$KEYCHAIN"
|
||||
security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN"
|
||||
|
||||
echo "$CERT_BASE64" | base64 -d > "$RUNNER_TEMP/dist.p12"
|
||||
security import "$RUNNER_TEMP/dist.p12" -k "$KEYCHAIN" -P "$CERT_PASSWORD" \
|
||||
-T /usr/bin/codesign -T /usr/bin/security -f pkcs12
|
||||
rm -f "$RUNNER_TEMP/dist.p12"
|
||||
|
||||
# Without this, codesign triggers an interactive keychain prompt that
|
||||
# nothing can answer on a headless runner.
|
||||
security set-key-partition-list -S apple-tool:,apple:,codesign: \
|
||||
-s -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN" > /dev/null
|
||||
|
||||
# Put our keychain first in the search list, keeping the login one so
|
||||
# Xcode can still reach Apple's intermediate certificates.
|
||||
security list-keychains -d user -s "$KEYCHAIN" $(security list-keychains -d user | sed 's/"//g')
|
||||
security find-identity -v -p codesigning "$KEYCHAIN"
|
||||
|
||||
- name: Install the App Store Connect API key
|
||||
if: steps.creds.outputs.signed == 'true'
|
||||
env:
|
||||
ASC_KEY_BASE64: ${{ secrets.APP_STORE_CONNECT_PRIVATE_KEY }}
|
||||
ASC_KEY_ID: ${{ secrets.APP_STORE_CONNECT_KEY_ID }}
|
||||
run: |
|
||||
# altool looks the key up by ID in this directory.
|
||||
mkdir -p ~/private_keys
|
||||
echo "$ASC_KEY_BASE64" | base64 -d > ~/private_keys/AuthKey_${ASC_KEY_ID}.p8
|
||||
chmod 600 ~/private_keys/AuthKey_${ASC_KEY_ID}.p8
|
||||
|
||||
- name: Install the provisioning profile
|
||||
if: steps.creds.outputs.signed == 'true'
|
||||
id: profile
|
||||
env:
|
||||
PROFILE_BASE64: ${{ secrets.IOS_PROVISIONING_PROFILE_BASE64 }}
|
||||
run: |
|
||||
PROFILE="$RUNNER_TEMP/profile.mobileprovision"
|
||||
echo "$PROFILE_BASE64" | base64 -d > "$PROFILE"
|
||||
|
||||
# A .mobileprovision is a CMS-signed plist, so it has to be decoded
|
||||
# before anything inside it can be read.
|
||||
PLIST=$(security cms -D -i "$PROFILE")
|
||||
UUID=$(echo "$PLIST" | plutil -extract UUID raw -)
|
||||
NAME=$(echo "$PLIST" | plutil -extract Name raw -)
|
||||
# application-identifier is "TEAMID.bundle.id" - deriving the bundle ID
|
||||
# from the profile keeps ExportOptions honest if app.config.js changes.
|
||||
APP_ID=$(echo "$PLIST" | plutil -extract Entitlements.application-identifier raw -)
|
||||
BUNDLE_ID="${APP_ID#*.}"
|
||||
EXPIRY=$(echo "$PLIST" | plutil -extract ExpirationDate raw -)
|
||||
|
||||
# Xcode moved the profile directory in 16; write both so this does not
|
||||
# silently stop working on a runner image bump.
|
||||
mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles
|
||||
mkdir -p ~/Library/Developer/Xcode/UserData/Provisioning\ Profiles
|
||||
cp "$PROFILE" ~/Library/MobileDevice/Provisioning\ Profiles/"$UUID".mobileprovision
|
||||
cp "$PROFILE" ~/Library/Developer/Xcode/UserData/Provisioning\ Profiles/"$UUID".mobileprovision
|
||||
|
||||
echo "uuid=$UUID" >> "$GITHUB_OUTPUT"
|
||||
echo "name=$NAME" >> "$GITHUB_OUTPUT"
|
||||
echo "bundle_id=$BUNDLE_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "Profile '$NAME' ($UUID) for $BUNDLE_ID, expires $EXPIRY"
|
||||
|
||||
- name: Archive
|
||||
if: steps.creds.outputs.signed == 'true'
|
||||
env:
|
||||
TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
# Manual signing, deliberately. Automatic signing always signs the
|
||||
# archive with a *development* identity and relies on -exportArchive to
|
||||
# re-sign it for distribution afterwards - which needs a development
|
||||
# certificate and a registered device that a CI-only TestFlight
|
||||
# pipeline has no reason to own. Naming the App Store profile up front
|
||||
# skips that dance entirely.
|
||||
xcodebuild archive \
|
||||
-workspace "${{ steps.xcode.outputs.workspace }}" \
|
||||
-scheme "${{ steps.xcode.outputs.scheme }}" \
|
||||
-configuration Release \
|
||||
-destination 'generic/platform=iOS' \
|
||||
-archivePath "$RUNNER_TEMP/Bulwark.xcarchive" \
|
||||
CODE_SIGN_STYLE=Manual \
|
||||
DEVELOPMENT_TEAM="$TEAM_ID" \
|
||||
CODE_SIGN_IDENTITY="Apple Distribution" \
|
||||
PROVISIONING_PROFILE_SPECIFIER="${{ steps.profile.outputs.uuid }}"
|
||||
|
||||
# Signing failures report a symptom ("no profiles found") rather than the
|
||||
# setting that caused it, and a re-run costs ~30 minutes. Dump the
|
||||
# resolved values instead of guessing twice.
|
||||
- name: Dump signing settings
|
||||
if: failure() && steps.creds.outputs.signed == 'true'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
echo "── identities in the keychain ──"
|
||||
security find-identity -v -p codesigning || true
|
||||
echo "── resolved build settings ──"
|
||||
xcodebuild -workspace "${{ steps.xcode.outputs.workspace }}" \
|
||||
-scheme "${{ steps.xcode.outputs.scheme }}" \
|
||||
-configuration Release -showBuildSettings 2>/dev/null \
|
||||
| grep -Ei 'CODE_SIGN|PROVISIONING|DEVELOPMENT_TEAM|PRODUCT_BUNDLE_ID' | sort -u || true
|
||||
|
||||
- name: Export the IPA
|
||||
if: steps.creds.outputs.signed == 'true'
|
||||
id: export
|
||||
env:
|
||||
TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
PROFILE_NAME: ${{ steps.profile.outputs.name }}
|
||||
BUNDLE_ID: ${{ steps.profile.outputs.bundle_id }}
|
||||
run: |
|
||||
cat > "$RUNNER_TEMP/ExportOptions.plist" <<PLIST
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>method</key><string>app-store</string>
|
||||
<key>teamID</key><string>${TEAM_ID}</string>
|
||||
<key>signingStyle</key><string>manual</string>
|
||||
<key>signingCertificate</key><string>Apple Distribution</string>
|
||||
<key>provisioningProfiles</key>
|
||||
<dict>
|
||||
<key>${BUNDLE_ID}</key><string>${PROFILE_NAME}</string>
|
||||
</dict>
|
||||
<key>uploadSymbols</key><true/>
|
||||
<key>destination</key><string>export</string>
|
||||
</dict>
|
||||
</plist>
|
||||
PLIST
|
||||
|
||||
xcodebuild -exportArchive \
|
||||
-archivePath "$RUNNER_TEMP/Bulwark.xcarchive" \
|
||||
-exportPath "$RUNNER_TEMP/export" \
|
||||
-exportOptionsPlist "$RUNNER_TEMP/ExportOptions.plist"
|
||||
|
||||
VERSION=$(cat VERSION | tr -d '[:space:]')
|
||||
SRC=$(ls "$RUNNER_TEMP"/export/*.ipa | head -1)
|
||||
DEST="bulwark-mobile-${VERSION}-${GITHUB_SHA::7}.ipa"
|
||||
cp "$SRC" "$DEST"
|
||||
echo "path=$DEST" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: steps.creds.outputs.signed == 'true'
|
||||
with:
|
||||
name: ${{ steps.export.outputs.path }}
|
||||
path: ${{ steps.export.outputs.path }}
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload to TestFlight
|
||||
# The IPA is not attached to the GitHub release: without an Apple device
|
||||
# provisioned for it, it is not installable, and TestFlight is the only
|
||||
# distribution channel for it.
|
||||
if: >-
|
||||
steps.creds.outputs.signed == 'true' &&
|
||||
(github.event_name == 'release' || inputs.upload_to_testflight)
|
||||
env:
|
||||
ASC_KEY_ID: ${{ secrets.APP_STORE_CONNECT_KEY_ID }}
|
||||
ASC_ISSUER_ID: ${{ secrets.APP_STORE_CONNECT_ISSUER_ID }}
|
||||
run: |
|
||||
IPA="${{ steps.export.outputs.path }}"
|
||||
# Validate first - it catches missing Info.plist keys and entitlement
|
||||
# mistakes in seconds, instead of via a rejection email 20 minutes later.
|
||||
xcrun altool --validate-app --type ios --file "$IPA" \
|
||||
--apiKey "$ASC_KEY_ID" --apiIssuer "$ASC_ISSUER_ID"
|
||||
xcrun altool --upload-app --type ios --file "$IPA" \
|
||||
--apiKey "$ASC_KEY_ID" --apiIssuer "$ASC_ISSUER_ID"
|
||||
echo "::notice::Uploaded build ${IOS_BUILD_NUMBER} to App Store Connect. Processing usually takes 5-30 minutes before it appears in TestFlight."
|
||||
@@ -1,9 +1,9 @@
|
||||
<div align="center">
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/bulwarkmail/webmail/refs/heads/main//public/branding/Bulwark_Logo_with_Lettering_White_and_Color.svg" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/bulwarkmail/webmail/refs/heads/main//public/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg" />
|
||||
<img src="https://raw.githubusercontent.com/bulwarkmail/webmail/refs/heads/main//public/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg" alt="Bulwark Webmail" width="280" />
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/bulwarkmail/webmail/refs/heads/main/public/branding/Bulwark_Logo_with_Lettering_White_and_Color.svg" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/bulwarkmail/webmail/refs/heads/main/public/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg" />
|
||||
<img src="https://raw.githubusercontent.com/bulwarkmail/webmail/refs/heads/main/public/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg" alt="Bulwark Webmail" width="280" />
|
||||
</picture>
|
||||
|
||||
</div>
|
||||
@@ -26,10 +26,10 @@ React Native (Expo SDK 54) client for [Bulwark Webmail](https://github.com/bulwa
|
||||
|
||||
## What's missing or rough
|
||||
|
||||
- iOS build is untested
|
||||
- iOS builds, but push notifications and client certificates are Android-only so far
|
||||
- Filters & rules, S/MIME, plugins, themes, file storage - UI stubs only
|
||||
- Calendar editing is partial; contacts editing is basic
|
||||
- No Play Store distribution yet (sideload APK from Releases)
|
||||
- No Play Store distribution yet (sideload APK from Releases); iOS ships via TestFlight
|
||||
|
||||
## Run locally
|
||||
|
||||
@@ -41,6 +41,7 @@ npx expo start
|
||||
Then press `a` for Android, `i` for iOS, or scan the QR with Expo Go.
|
||||
|
||||
For a release APK build see [.github/workflows/release-android.yml](.github/workflows/release-android.yml).
|
||||
For iOS builds and TestFlight distribution see [docs/ios-release.md](docs/ios-release.md).
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -16,6 +16,12 @@ if (!COMMIT) {
|
||||
}
|
||||
COMMIT = COMMIT.slice(0, 7);
|
||||
|
||||
// App Store Connect rejects a build whose CFBundleVersion it has already seen
|
||||
// for this CFBundleShortVersionString, so this has to advance on every upload
|
||||
// even when VERSION does not. CI passes the workflow run number; local builds
|
||||
// fall back to 1 (never uploaded).
|
||||
const IOS_BUILD_NUMBER = process.env.IOS_BUILD_NUMBER || '1';
|
||||
|
||||
module.exports = {
|
||||
expo: {
|
||||
name: 'Bulwark Mobile',
|
||||
@@ -33,6 +39,14 @@ module.exports = {
|
||||
},
|
||||
ios: {
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: 'org.bulwarkmail.mobile',
|
||||
buildNumber: IOS_BUILD_NUMBER,
|
||||
config: {
|
||||
// The app only speaks HTTPS/TLS and uses platform crypto, which is
|
||||
// exempt. Declaring it here skips the manual export-compliance
|
||||
// questionnaire that otherwise blocks every TestFlight build.
|
||||
usesNonExemptEncryption: false,
|
||||
},
|
||||
},
|
||||
android: {
|
||||
adaptiveIcon: {
|
||||
@@ -55,6 +69,19 @@ module.exports = {
|
||||
{
|
||||
cameraPermission:
|
||||
'Bulwark Mail uses the camera to scan sign-in QR codes shown in webmail.',
|
||||
// QR scanning never records audio; leaving the mic entry in would be
|
||||
// an unexplained permission in App Review.
|
||||
microphonePermission: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
'expo-image-picker',
|
||||
{
|
||||
photosPermission:
|
||||
'Bulwark Mail needs access to your photos so you can attach them to emails and set contact photos.',
|
||||
// Only launchImageLibraryAsync is used - no in-app capture.
|
||||
cameraPermission: false,
|
||||
microphonePermission: false,
|
||||
},
|
||||
],
|
||||
],
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
# iOS builds and TestFlight
|
||||
|
||||
The iOS app is built by [.github/workflows/release-ios.yml](../.github/workflows/release-ios.yml)
|
||||
on a GitHub-hosted macOS runner and uploaded straight to TestFlight. macOS runner
|
||||
minutes are free for this repository because it is public.
|
||||
|
||||
Unlike `android/`, which is committed and hand-maintained, **`ios/` is gitignored
|
||||
and regenerated by `expo prebuild` on every run.** Never commit it, and never fix
|
||||
anything by editing it - native iOS changes belong in `app.config.js` or a config
|
||||
plugin, or they will be silently thrown away on the next build.
|
||||
|
||||
Without the secrets below the workflow still runs, but only as an unsigned
|
||||
compile check; no IPA is produced.
|
||||
|
||||
## One-time Apple setup
|
||||
|
||||
You need an active Apple Developer Program membership ($99/yr). Everything here
|
||||
can be done from Windows - no Mac required.
|
||||
|
||||
### 1. Team ID
|
||||
|
||||
developer.apple.com → Account → Membership details. A 10-character string like
|
||||
`A1B2C3D4E5`.
|
||||
|
||||
### 2. Distribution certificate
|
||||
|
||||
Apple issues certificates against a certificate signing request. Keychain Access
|
||||
is the usual way to make one, but OpenSSL works and does not need a Mac:
|
||||
|
||||
```bash
|
||||
openssl genrsa -out dist.key 2048
|
||||
openssl req -new -key dist.key -out dist.csr \
|
||||
-subj "/emailAddress=you@bulwarkmail.org/CN=Bulwark Mail/C=DE"
|
||||
```
|
||||
|
||||
Upload `dist.csr` at developer.apple.com → Certificates → **+** → **Apple
|
||||
Distribution**, download the resulting `distribution.cer`, then bundle the cert
|
||||
and its private key into a `.p12`:
|
||||
|
||||
```bash
|
||||
openssl x509 -inform DER -in distribution.cer -out dist.pem
|
||||
openssl pkcs12 -export -inkey dist.key -in dist.pem -out dist.p12 \
|
||||
-passout pass:CHOOSE_A_PASSWORD
|
||||
```
|
||||
|
||||
**On OpenSSL 3.x, add `-legacy` to that last command.** OpenSSL 3 defaults to
|
||||
AES-256-CBC, which macOS `security import` refuses to read, and the workflow then
|
||||
fails at the import step. OpenSSL 1.x has no `-legacy` flag and already writes
|
||||
the format macOS wants - passing it there is an error. Check with `openssl
|
||||
version` first; Git Bash on Windows currently ships 1.1.1.
|
||||
|
||||
Keep `dist.key` somewhere safe - you cannot re-download it, and losing it means
|
||||
revoking the certificate and starting over.
|
||||
|
||||
### 3. App Store Connect API key
|
||||
|
||||
App Store Connect → Users and Access → Integrations → App Store Connect API →
|
||||
**+**, with the **App Manager** role. Download the `.p8` (**one download only**)
|
||||
and note the **Key ID** and the **Issuer ID** shown above the key list.
|
||||
|
||||
The key authenticates the TestFlight upload.
|
||||
|
||||
### 4. App ID, then app record
|
||||
|
||||
These live on two different Apple sites and have to be done in this order.
|
||||
|
||||
**developer.apple.com** → Certificates, Identifiers & Profiles → Identifiers →
|
||||
**+** → App IDs → App. Explicit bundle ID `org.bulwarkmail.mobile`, matching
|
||||
`ios.bundleIdentifier` in [app.config.js](../app.config.js). Leave every
|
||||
capability off: push is not implemented on iOS, and sign-in uses the custom
|
||||
`bulwarkmobile://` scheme rather than universal links, so no Associated Domains.
|
||||
|
||||
**appstoreconnect.apple.com** → Apps → **+** → New App. Platform iOS, any SKU.
|
||||
The bundle ID here is a dropdown populated from the identifiers above, which is
|
||||
why the App ID has to be registered first. The app name must be unique across
|
||||
the entire App Store.
|
||||
|
||||
The TestFlight upload is rejected if the app record does not exist - and that
|
||||
failure lands at the very end of a ~30 minute build.
|
||||
|
||||
### 5. App Store provisioning profile
|
||||
|
||||
developer.apple.com → Profiles → **+** → Distribution → **App Store Connect**.
|
||||
Pick the App ID from step 4 and the distribution certificate from step 2, name it
|
||||
`Bulwark Mobile App Store`, and download the `.mobileprovision`.
|
||||
|
||||
The build signs **manually** and this profile is not optional. Automatic signing
|
||||
would be less to maintain, but `xcodebuild archive` under automatic signing always
|
||||
signs with a *development* identity and leans on `-exportArchive` to re-sign for
|
||||
distribution afterwards. That needs a development certificate and at least one
|
||||
registered device - neither of which a CI-only TestFlight pipeline has any reason
|
||||
to own, and Apple will not issue a development profile without a device. Naming
|
||||
the App Store profile up front avoids the whole problem.
|
||||
|
||||
The profile expires when the certificate does (2027-08-01). Regenerate it here and
|
||||
update the secret when that happens.
|
||||
|
||||
## Repository secrets
|
||||
|
||||
Settings → Secrets and variables → Actions:
|
||||
|
||||
| Secret | Value |
|
||||
| --- | --- |
|
||||
| `APPLE_TEAM_ID` | The 10-character team ID from step 1 |
|
||||
| `IOS_DIST_CERT_BASE64` | `dist.p12` from step 2, base64-encoded |
|
||||
| `IOS_DIST_CERT_PASSWORD` | The password you chose for `dist.p12` |
|
||||
| `APP_STORE_CONNECT_KEY_ID` | Key ID from step 3 |
|
||||
| `APP_STORE_CONNECT_ISSUER_ID` | Issuer ID from step 3 |
|
||||
| `APP_STORE_CONNECT_PRIVATE_KEY` | The `.p8` from step 3, base64-encoded |
|
||||
| `IOS_PROVISIONING_PROFILE_BASE64` | The `.mobileprovision` from step 5, base64-encoded |
|
||||
|
||||
To base64-encode a file:
|
||||
|
||||
```powershell
|
||||
# PowerShell
|
||||
[Convert]::ToBase64String([IO.File]::ReadAllBytes('dist.p12')) | Set-Clipboard
|
||||
```
|
||||
|
||||
```bash
|
||||
# bash
|
||||
base64 -w0 dist.p12
|
||||
```
|
||||
|
||||
## Running a build
|
||||
|
||||
Publishing a GitHub release triggers the iOS workflow alongside the Android one.
|
||||
You can also run it by hand from the Actions tab, with an
|
||||
`upload_to_testflight` toggle if you only want the IPA as a workflow artifact.
|
||||
|
||||
The IPA is deliberately not attached to the GitHub release: unlike the APK, it is
|
||||
not installable outside TestFlight.
|
||||
|
||||
`CFBundleVersion` comes from the workflow run number via the `IOS_BUILD_NUMBER`
|
||||
env var. App Store Connect rejects a build number it has already seen for a given
|
||||
version, so never re-run a workflow expecting a re-upload to succeed - the run
|
||||
number advances on its own, so just start a new run.
|
||||
|
||||
## After the upload
|
||||
|
||||
Processing takes roughly 5-30 minutes before the build shows up in TestFlight.
|
||||
Internal testers (up to 100, must be on your App Store Connect team) get it
|
||||
immediately. External testers (up to 10,000) need a Beta App Review, which takes
|
||||
about a day the first time and is usually waved through afterwards.
|
||||
|
||||
## What does not work on iOS yet
|
||||
|
||||
- **Push notifications.** The push path is a hand-written Android module talking
|
||||
to FCM (`BulwarkFcmModule`, `BulwarkMessagingService`). iOS needs an APNs key
|
||||
and an equivalent native module; until then `push-notifications.ts` short-
|
||||
circuits and the app polls like a device with push disabled.
|
||||
- **Client certificates.** `BulwarkClientCertModule` is Android-only.
|
||||
`secureFetch` falls back to plain `fetch`, so cert-authenticated servers will
|
||||
not connect.
|
||||
- **In-app updates.** Hidden on purpose - see `supportsSideloadUpdates` in
|
||||
[src/lib/platform-capabilities.ts](../src/lib/platform-capabilities.ts).
|
||||
Downloading and installing a binary is forbidden by App Store Review guideline
|
||||
2.5.2, so iOS updates come through TestFlight instead. The Updates settings
|
||||
pane is removed from the list on iOS; the version and commit are still shown
|
||||
under About & Data.
|
||||
@@ -497,6 +497,7 @@
|
||||
"drop_files": "Drop files to attach",
|
||||
"show_less": "Show less",
|
||||
"send_failed": "Failed to send email",
|
||||
"editor_unavailable": "Could not read the message content. Copy your text, then close and reopen the composer.",
|
||||
"continue_draft": "Continue draft",
|
||||
"close_draft_title": "Save or discard draft?",
|
||||
"close_draft_message": "You have unsaved changes. Would you like to save this as a draft or discard it?",
|
||||
|
||||
@@ -0,0 +1,953 @@
|
||||
<title>Bulwark Mobile — Sign-in redesign</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
|
||||
<svg width="0" height="0" style="position:absolute" aria-hidden="true">
|
||||
<defs>
|
||||
<symbol id="i-qr" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="3" width="7" height="7" rx="1" /><rect x="14" y="3" width="7" height="7" rx="1" />
|
||||
<rect x="3" y="14" width="7" height="7" rx="1" /><path d="M14 14h3v3h-3z" /><path d="M21 14v3M21 21h-4" />
|
||||
</symbol>
|
||||
<symbol id="i-mail" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="2" y="4" width="20" height="16" rx="2" /><path d="m2 7 10 6 10-6" />
|
||||
</symbol>
|
||||
<symbol id="i-chev" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="m9 18 6-6-6-6" />
|
||||
</symbol>
|
||||
<symbol id="i-back" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="m15 18-6-6 6-6" />
|
||||
</symbol>
|
||||
<symbol id="i-lock" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="4" y="10" width="16" height="11" rx="2" /><path d="M8 10V7a4 4 0 0 1 8 0v3" />
|
||||
</symbol>
|
||||
<symbol id="i-globe" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3a15 15 0 0 1 0 18M12 3a15 15 0 0 0 0 18" />
|
||||
</symbol>
|
||||
<symbol id="i-check" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="m4 12 5 5L20 6" />
|
||||
</symbol>
|
||||
<symbol id="i-alert" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="9" /><path d="M12 7v6M12 16.5v.5" />
|
||||
</symbol>
|
||||
<symbol id="i-x" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M6 6 18 18M18 6 6 18" />
|
||||
</symbol>
|
||||
<symbol id="i-eye" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M2 12s3.6-6.5 10-6.5S22 12 22 12s-3.6 6.5-10 6.5S2 12 2 12Z" /><circle cx="12" cy="12" r="2.6" />
|
||||
</symbol>
|
||||
<symbol id="i-shield" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M12 3 5 6v6c0 4.2 2.9 7.6 7 9 4.1-1.4 7-4.8 7-9V6l-7-3Z" />
|
||||
</symbol>
|
||||
<symbol id="i-plus" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M12 5v14M5 12h14" />
|
||||
</symbol>
|
||||
<symbol id="i-key" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="7.5" cy="15.5" r="4.5" /><path d="m10.8 12.2 8-8M17 6l2.5 2.5M14.5 8.5 17 11" />
|
||||
</symbol>
|
||||
</defs>
|
||||
</svg>
|
||||
|
||||
<style>
|
||||
:root {
|
||||
--page-bg: #fbfbfc;
|
||||
--page-panel: #f0f3f8;
|
||||
--page-ink: #14171f;
|
||||
--page-ink-2: #545c6b;
|
||||
--page-ink-3: #8a919f;
|
||||
--page-rule: #e1e6ef;
|
||||
--accent: #2f6fed;
|
||||
--accent-soft: rgba(47, 111, 237, 0.09);
|
||||
|
||||
--app-bg: #ffffff;
|
||||
--app-surface: #f8fafc;
|
||||
--app-surface-2: #f1f5f9;
|
||||
--app-border: #e2e8f0;
|
||||
--app-text: #0f172a;
|
||||
--app-text-2: #64748b;
|
||||
--app-muted: #94a3b8;
|
||||
--app-primary: #3b82f6;
|
||||
--app-primary-bg: #dbeafe;
|
||||
--app-error: #ef4444;
|
||||
--app-error-bg: #fee2e2;
|
||||
--app-success: #16a34a;
|
||||
|
||||
--frame: #d5dae5;
|
||||
--frame-shadow: rgba(20, 26, 40, 0.14);
|
||||
|
||||
--serif: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, "Times New Roman", serif;
|
||||
--sans: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Helvetica Neue", Arial, sans-serif;
|
||||
--mono: ui-monospace, "Cascadia Mono", "SF Mono", Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--page-bg: #0a0b0d;
|
||||
--page-panel: #111319;
|
||||
--page-ink: #eef1f6;
|
||||
--page-ink-2: #a4adbb;
|
||||
--page-ink-3: #6e7684;
|
||||
--page-rule: #22262f;
|
||||
--accent: #74aaff;
|
||||
--accent-soft: rgba(116, 170, 255, 0.12);
|
||||
|
||||
--app-bg: #09090b;
|
||||
--app-surface: #18181b;
|
||||
--app-surface-2: #1f1f23;
|
||||
--app-border: #27272a;
|
||||
--app-text: #fafafa;
|
||||
--app-text-2: #a1a1aa;
|
||||
--app-muted: #71717a;
|
||||
--app-primary: #3b82f6;
|
||||
--app-primary-bg: #172554;
|
||||
--app-error: #ef4444;
|
||||
--app-error-bg: #450a0a;
|
||||
--app-success: #22c55e;
|
||||
|
||||
--frame: #2b303a;
|
||||
--frame-shadow: rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
}
|
||||
|
||||
:root[data-theme="light"] {
|
||||
--page-bg: #fbfbfc; --page-panel: #f0f3f8; --page-ink: #14171f; --page-ink-2: #545c6b;
|
||||
--page-ink-3: #8a919f; --page-rule: #e1e6ef; --accent: #2f6fed; --accent-soft: rgba(47,111,237,0.09);
|
||||
--app-bg: #ffffff; --app-surface: #f8fafc; --app-surface-2: #f1f5f9; --app-border: #e2e8f0;
|
||||
--app-text: #0f172a; --app-text-2: #64748b; --app-muted: #94a3b8; --app-primary: #3b82f6;
|
||||
--app-primary-bg: #dbeafe; --app-error: #ef4444; --app-error-bg: #fee2e2; --app-success: #16a34a;
|
||||
--frame: #d5dae5; --frame-shadow: rgba(20,26,40,0.14);
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--page-bg: #0a0b0d; --page-panel: #111319; --page-ink: #eef1f6; --page-ink-2: #a4adbb;
|
||||
--page-ink-3: #6e7684; --page-rule: #22262f; --accent: #74aaff; --accent-soft: rgba(116,170,255,0.12);
|
||||
--app-bg: #09090b; --app-surface: #18181b; --app-surface-2: #1f1f23; --app-border: #27272a;
|
||||
--app-text: #fafafa; --app-text-2: #a1a1aa; --app-muted: #71717a; --app-primary: #3b82f6;
|
||||
--app-primary-bg: #172554; --app-error: #ef4444; --app-error-bg: #450a0a; --app-success: #22c55e;
|
||||
--frame: #2b303a; --frame-shadow: rgba(0,0,0,0.55);
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--page-bg);
|
||||
color: var(--page-ink);
|
||||
font-family: var(--serif);
|
||||
font-size: 17px;
|
||||
line-height: 1.6;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
.d-wrap { max-width: 1180px; margin: 0 auto; padding: 64px 28px 96px; }
|
||||
|
||||
/* ---------- document typography ---------- */
|
||||
.d-eyebrow {
|
||||
font-family: var(--mono); font-size: 11px; letter-spacing: 0.14em;
|
||||
text-transform: uppercase; color: var(--page-ink-3); margin: 0 0 18px;
|
||||
}
|
||||
.d-title {
|
||||
font-family: var(--sans); font-weight: 700; font-size: clamp(34px, 5vw, 52px);
|
||||
line-height: 1.04; letter-spacing: -0.028em; margin: 0; text-wrap: balance;
|
||||
}
|
||||
.d-deck {
|
||||
max-width: 62ch; margin: 22px 0 0; font-size: 19px; line-height: 1.62; color: var(--page-ink-2);
|
||||
}
|
||||
.d-deck strong { color: var(--page-ink); font-weight: 600; }
|
||||
|
||||
.d-section { margin-top: 84px; }
|
||||
.d-h2 {
|
||||
font-family: var(--sans); font-weight: 700; font-size: 25px; letter-spacing: -0.018em;
|
||||
margin: 0; text-wrap: balance;
|
||||
}
|
||||
.d-lede { max-width: 62ch; margin: 12px 0 0; color: var(--page-ink-2); }
|
||||
.d-rule { height: 1px; background: var(--page-rule); border: 0; margin: 26px 0 34px; }
|
||||
|
||||
.d-meta {
|
||||
display: flex; flex-wrap: wrap; gap: 8px 10px; margin-top: 30px;
|
||||
font-family: var(--mono); font-size: 11.5px; color: var(--page-ink-2);
|
||||
}
|
||||
.d-meta span {
|
||||
border: 1px solid var(--page-rule); border-radius: 999px; padding: 4px 11px; background: var(--page-panel);
|
||||
}
|
||||
|
||||
/* ---------- comparison ---------- */
|
||||
.d-compare {
|
||||
display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 1px;
|
||||
background: var(--page-rule); border: 1px solid var(--page-rule); border-radius: 12px; overflow: hidden;
|
||||
}
|
||||
.d-cell { background: var(--page-bg); padding: 20px 22px; }
|
||||
.d-cell dt {
|
||||
font-family: var(--mono); font-size: 10.5px; letter-spacing: 0.12em; text-transform: uppercase;
|
||||
color: var(--page-ink-3); margin: 0 0 10px;
|
||||
}
|
||||
.d-cell dd { margin: 0; font-family: var(--sans); font-size: 15px; line-height: 1.45; }
|
||||
.d-was { color: var(--page-ink-3); text-decoration: line-through; text-decoration-thickness: 1px; }
|
||||
.d-now { color: var(--page-ink); font-weight: 600; display: block; margin-top: 3px; }
|
||||
|
||||
/* ---------- filmstrip ---------- */
|
||||
.d-strip {
|
||||
display: flex; gap: 30px; overflow-x: auto; padding: 30px 26px 26px;
|
||||
background: var(--page-panel); border-radius: 16px; scroll-snap-type: x proximity;
|
||||
}
|
||||
.d-strip figure { margin: 0; scroll-snap-align: center; flex: 0 0 auto; width: 288px; }
|
||||
.d-strip figcaption { margin-top: 18px; }
|
||||
.d-step {
|
||||
font-family: var(--mono); font-size: 10.5px; letter-spacing: 0.12em; text-transform: uppercase;
|
||||
color: var(--accent); display: block; margin-bottom: 5px;
|
||||
}
|
||||
.d-step.is-alt { color: var(--page-ink-3); }
|
||||
.d-cap-title { font-family: var(--sans); font-weight: 650; font-size: 15.5px; letter-spacing: -0.01em; }
|
||||
.d-cap-body { font-size: 14.5px; line-height: 1.5; color: var(--page-ink-2); margin: 5px 0 0; }
|
||||
|
||||
/* ---------- notes ---------- */
|
||||
.d-notes { list-style: none; padding: 0; margin: 0; display: grid; gap: 22px; max-width: 74ch; }
|
||||
.d-notes li { display: grid; grid-template-columns: 26px 1fr; gap: 14px; align-items: start; }
|
||||
.d-notes svg { width: 18px; height: 18px; color: var(--accent); margin-top: 4px; }
|
||||
.d-note-h { font-family: var(--sans); font-weight: 650; font-size: 15.5px; }
|
||||
.d-note-b { color: var(--page-ink-2); font-size: 16px; }
|
||||
code {
|
||||
font-family: var(--mono); font-size: 0.85em; background: var(--accent-soft);
|
||||
color: var(--accent); padding: 1.5px 5px; border-radius: 4px;
|
||||
}
|
||||
|
||||
.d-foot {
|
||||
margin-top: 80px; padding-top: 22px; border-top: 1px solid var(--page-rule);
|
||||
font-family: var(--mono); font-size: 11.5px; color: var(--page-ink-3);
|
||||
}
|
||||
|
||||
/* ================= phone chrome ================= */
|
||||
.p {
|
||||
width: 288px; height: 600px; border-radius: 36px; background: var(--frame);
|
||||
padding: 8px; box-shadow: 0 18px 44px -18px var(--frame-shadow); position: relative;
|
||||
}
|
||||
.p-screen {
|
||||
width: 100%; height: 100%; border-radius: 29px; background: var(--app-bg); overflow: hidden;
|
||||
position: relative; font-family: var(--sans); color: var(--app-text); font-size: 14px; line-height: 1.4;
|
||||
display: flex; flex-direction: column;
|
||||
}
|
||||
.p-notch {
|
||||
position: absolute; top: 15px; left: 50%; transform: translateX(-50%); width: 74px; height: 5px;
|
||||
border-radius: 99px; background: var(--app-border); z-index: 6;
|
||||
}
|
||||
.p-pad { padding: 42px 24px 22px; flex: 1; display: flex; flex-direction: column; }
|
||||
.p-pad.is-centered { justify-content: center; }
|
||||
|
||||
/* ---- in-app primitives ---- */
|
||||
.s-logo {
|
||||
width: 56px; height: 56px; border-radius: 17px; background: var(--app-primary);
|
||||
display: grid; place-items: center; margin: 0 auto 16px; color: #fff;
|
||||
}
|
||||
.s-logo svg { width: 30px; height: 30px; }
|
||||
.s-brand { text-align: center; margin-bottom: 30px; }
|
||||
.s-brand h1 { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; margin: 0; }
|
||||
.s-brand p { font-size: 12.5px; color: var(--app-muted); margin: 5px 0 0; }
|
||||
|
||||
.s-h { font-size: 21px; font-weight: 700; letter-spacing: -0.022em; margin: 0; line-height: 1.22; }
|
||||
.s-sub { font-size: 13px; color: var(--app-text-2); margin: 8px 0 0; line-height: 1.45; }
|
||||
|
||||
.s-tile {
|
||||
display: flex; align-items: center; gap: 13px; width: 100%; text-align: left;
|
||||
border: 1px solid var(--app-border); background: var(--app-surface);
|
||||
border-radius: 14px; padding: 14px 15px; color: inherit;
|
||||
}
|
||||
.s-tile.is-primary { background: var(--app-primary); border-color: var(--app-primary); color: #fff; }
|
||||
.s-tile-ico { width: 22px; height: 22px; flex: 0 0 22px; opacity: 0.95; }
|
||||
.s-tile-txt { flex: 1; min-width: 0; }
|
||||
.s-tile-t { font-size: 14.5px; font-weight: 600; letter-spacing: -0.005em; }
|
||||
.s-tile-d { font-size: 11.5px; opacity: 0.72; margin-top: 2px; }
|
||||
.s-tile-chev { width: 16px; height: 16px; opacity: 0.5; }
|
||||
|
||||
.s-stack { display: flex; flex-direction: column; gap: 10px; }
|
||||
|
||||
.s-field { margin-top: 20px; }
|
||||
.s-label { font-size: 12px; font-weight: 600; color: var(--app-text-2); margin-bottom: 7px; }
|
||||
.s-input {
|
||||
border: 1px solid var(--app-border); background: var(--app-bg); border-radius: 10px;
|
||||
height: 42px; padding: 0 13px; display: flex; align-items: center; gap: 8px; font-size: 14px;
|
||||
}
|
||||
.s-input.is-focus { border-color: var(--app-primary); box-shadow: 0 0 0 3px var(--app-primary-bg); }
|
||||
.s-input.is-error { border-color: var(--app-error); }
|
||||
.s-input .s-ph { color: var(--app-muted); }
|
||||
.s-input svg { width: 17px; height: 17px; color: var(--app-muted); flex: 0 0 17px; }
|
||||
.s-caret {
|
||||
width: 1.5px; height: 17px; background: var(--app-primary); display: inline-block;
|
||||
animation: blink 1.05s steps(1) infinite;
|
||||
}
|
||||
@keyframes blink { 50% { opacity: 0; } }
|
||||
@media (prefers-reduced-motion: reduce) { .s-caret { animation: none; } }
|
||||
|
||||
.s-hint { font-size: 11.5px; color: var(--app-muted); margin-top: 8px; line-height: 1.45; }
|
||||
.s-hint.is-error { color: var(--app-error); }
|
||||
|
||||
.s-btn {
|
||||
height: 46px; border-radius: 12px; background: var(--app-primary); color: #fff;
|
||||
display: grid; place-items: center; font-size: 15px; font-weight: 600; margin-top: 20px;
|
||||
}
|
||||
.s-btn.is-off { background: var(--app-surface-2); color: var(--app-muted); }
|
||||
.s-btn.is-quiet {
|
||||
background: transparent; color: var(--app-text); border: 1px solid var(--app-border); font-weight: 500;
|
||||
}
|
||||
.s-link { text-align: center; font-size: 13px; color: var(--app-primary); margin-top: 16px; font-weight: 500; }
|
||||
.s-link.is-muted { color: var(--app-muted); font-weight: 400; }
|
||||
|
||||
.s-back { width: 22px; height: 22px; color: var(--app-text-2); margin-bottom: 22px; }
|
||||
.s-foot {
|
||||
text-align: center; font-size: 11px; color: var(--app-muted); padding: 0 0 8px; line-height: 1.6;
|
||||
}
|
||||
|
||||
.s-card {
|
||||
border: 1px solid var(--app-border); background: var(--app-surface); border-radius: 14px;
|
||||
padding: 15px; display: flex; align-items: center; gap: 12px; margin-top: 22px;
|
||||
}
|
||||
.s-card-ico {
|
||||
width: 38px; height: 38px; border-radius: 11px; background: var(--app-primary-bg);
|
||||
color: var(--app-primary); display: grid; place-items: center; flex: 0 0 38px;
|
||||
}
|
||||
.s-card-ico svg { width: 19px; height: 19px; }
|
||||
.s-card-t { font-size: 14.5px; font-weight: 600; }
|
||||
.s-card-d { font-size: 11.5px; color: var(--app-text-2); margin-top: 2px; display: flex; align-items: center; gap: 5px; }
|
||||
.s-dot { width: 5px; height: 5px; border-radius: 99px; background: var(--app-success); display: inline-block; }
|
||||
|
||||
.s-note {
|
||||
display: flex; gap: 9px; align-items: flex-start; margin-top: 16px;
|
||||
font-size: 11.5px; color: var(--app-text-2); line-height: 1.5;
|
||||
}
|
||||
.s-note svg { width: 15px; height: 15px; flex: 0 0 15px; margin-top: 1px; color: var(--app-muted); }
|
||||
|
||||
.s-banner {
|
||||
display: flex; gap: 9px; align-items: flex-start; border-radius: 11px; padding: 11px 12px;
|
||||
background: var(--app-error-bg); font-size: 12px; line-height: 1.45; margin-top: 18px;
|
||||
}
|
||||
.s-banner svg { width: 15px; height: 15px; flex: 0 0 15px; margin-top: 1px; color: var(--app-error); }
|
||||
|
||||
.s-divider { display: flex; align-items: center; gap: 12px; margin: 18px 0; }
|
||||
.s-divider::before, .s-divider::after { content: ""; height: 1px; flex: 1; background: var(--app-border); }
|
||||
.s-divider span { font-size: 11.5px; color: var(--app-muted); }
|
||||
|
||||
/* progress rows (setting up) */
|
||||
.s-prog { display: flex; align-items: center; gap: 11px; padding: 11px 0; font-size: 13.5px; }
|
||||
.s-prog .s-tick {
|
||||
width: 20px; height: 20px; border-radius: 99px; background: var(--app-success);
|
||||
color: #fff; display: grid; place-items: center; flex: 0 0 20px;
|
||||
}
|
||||
.s-prog .s-tick svg { width: 11px; height: 11px; }
|
||||
.s-prog .s-spin {
|
||||
width: 20px; height: 20px; border-radius: 99px; flex: 0 0 20px;
|
||||
border: 2px solid var(--app-border); border-top-color: var(--app-primary); animation: spin 0.9s linear infinite;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { .s-prog .s-spin { animation: none; } }
|
||||
.s-prog.is-pending { color: var(--app-muted); }
|
||||
|
||||
/* account rows (add mode) */
|
||||
.s-acct { display: flex; align-items: center; gap: 11px; padding: 11px 0; }
|
||||
.s-av {
|
||||
width: 34px; height: 34px; border-radius: 99px; display: grid; place-items: center;
|
||||
font-size: 13px; font-weight: 600; color: #fff; flex: 0 0 34px;
|
||||
}
|
||||
.s-acct-t { font-size: 14px; font-weight: 550; }
|
||||
.s-acct-d { font-size: 11.5px; color: var(--app-muted); }
|
||||
|
||||
/* scanner — deliberately always dark, it's a camera view */
|
||||
.p-screen.is-camera { background: #0b0d10; color: #fff; }
|
||||
.s-cam { position: absolute; inset: 0; background:
|
||||
radial-gradient(120% 80% at 50% 30%, #2a3038 0%, #14171c 55%, #0b0d10 100%); }
|
||||
.s-cam-grid { position: absolute; inset: 0; opacity: 0.18; background-image:
|
||||
linear-gradient(rgba(255,255,255,0.5) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(255,255,255,0.5) 1px, transparent 1px); background-size: 34px 34px; }
|
||||
.s-reticle { position: absolute; top: 168px; left: 50%; transform: translateX(-50%); width: 176px; height: 176px; }
|
||||
.s-reticle i {
|
||||
position: absolute; width: 34px; height: 34px; border: 3px solid #fff; border-radius: 4px;
|
||||
}
|
||||
.s-reticle i:nth-child(1) { top: 0; left: 0; border-right: 0; border-bottom: 0; }
|
||||
.s-reticle i:nth-child(2) { top: 0; right: 0; border-left: 0; border-bottom: 0; }
|
||||
.s-reticle i:nth-child(3) { bottom: 0; left: 0; border-right: 0; border-top: 0; }
|
||||
.s-reticle i:nth-child(4) { bottom: 0; right: 0; border-left: 0; border-top: 0; }
|
||||
.s-qr {
|
||||
position: absolute; inset: 22px; border-radius: 6px; background: #fff;
|
||||
display: grid; grid-template-columns: repeat(9, 1fr); grid-template-rows: repeat(9, 1fr); padding: 8px; gap: 2px;
|
||||
}
|
||||
.s-qr b { background: #0b0d10; border-radius: 1px; }
|
||||
.s-cam-top {
|
||||
position: absolute; top: 40px; left: 0; right: 0; display: flex; align-items: center;
|
||||
justify-content: space-between; padding: 0 20px; z-index: 3;
|
||||
}
|
||||
.s-cam-top svg { width: 22px; height: 22px; color: #fff; }
|
||||
.s-cam-copy { position: absolute; left: 0; right: 0; bottom: 46px; text-align: center; padding: 0 30px; z-index: 3; }
|
||||
.s-cam-copy p { margin: 0; font-size: 13px; line-height: 1.5; color: rgba(255,255,255,0.82); }
|
||||
.s-cam-copy .s-cam-h { font-size: 15.5px; font-weight: 600; color: #fff; margin-bottom: 6px; }
|
||||
.s-cam-copy .s-cam-link { margin-top: 18px; font-size: 13px; font-weight: 500; color: #8ab4ff; }
|
||||
|
||||
/* browser handoff sheet */
|
||||
.s-sheet {
|
||||
position: absolute; inset: 26px 0 0; background: var(--app-bg); border-radius: 18px 18px 0 0;
|
||||
box-shadow: 0 -8px 40px rgba(0,0,0,0.35); display: flex; flex-direction: column; overflow: hidden;
|
||||
}
|
||||
.s-sheet-bar {
|
||||
display: flex; align-items: center; gap: 9px; padding: 13px 15px;
|
||||
border-bottom: 1px solid var(--app-border); font-size: 12.5px; color: var(--app-text-2);
|
||||
}
|
||||
.s-sheet-bar svg { width: 13px; height: 13px; color: var(--app-success); }
|
||||
.s-sheet-bar .s-url { flex: 1; color: var(--app-text); font-weight: 550; }
|
||||
.s-sheet-bar .s-done { color: var(--app-primary); font-weight: 600; }
|
||||
.s-sheet-body { padding: 30px 24px; flex: 1; }
|
||||
.s-scrim { position: absolute; inset: 0; background: rgba(4,6,10,0.5); }
|
||||
.s-web-brand { display: flex; align-items: center; gap: 9px; margin-bottom: 24px; }
|
||||
.s-web-brand .s-web-mark {
|
||||
width: 28px; height: 28px; border-radius: 9px; background: var(--app-primary);
|
||||
color: #fff; display: grid; place-items: center;
|
||||
}
|
||||
.s-web-brand .s-web-mark svg { width: 16px; height: 16px; }
|
||||
.s-web-brand b { font-size: 14.5px; letter-spacing: -0.01em; }
|
||||
|
||||
/* the "before" screen is intentionally cramped */
|
||||
.s-old-field { margin-bottom: 13px; }
|
||||
</style>
|
||||
|
||||
<div class="d-wrap">
|
||||
|
||||
<p class="d-eyebrow">Bulwark Mobile · sign-in redesign</p>
|
||||
<h1 class="d-title">Three fields nobody knows the answer to</h1>
|
||||
<p class="d-deck">
|
||||
The current sign-in screen opens with a <strong>Server URL</strong> field. Most people don't know their
|
||||
JMAP endpoint, and the two paths that don't require knowing it — the webmail handoff and the QR code — sit
|
||||
below a divider, greyed out until the URL is filled in anyway. This proposes an entry screen that leads with
|
||||
the easy paths and asks for a server only when we genuinely can't work it out.
|
||||
</p>
|
||||
|
||||
<div class="d-meta">
|
||||
<span>src/screens/LoginScreen.tsx</span>
|
||||
<span>expo · react-native</span>
|
||||
<span>light + dark, both shown</span>
|
||||
</div>
|
||||
|
||||
<section class="d-section">
|
||||
<h2 class="d-h2">What changes</h2>
|
||||
<hr class="d-rule" />
|
||||
<dl class="d-compare">
|
||||
<div class="d-cell">
|
||||
<dt>To reach the inbox</dt>
|
||||
<dd><span class="d-was">3 fields typed</span><span class="d-now">1 field, or none with a code</span></dd>
|
||||
</div>
|
||||
<div class="d-cell">
|
||||
<dt>Server URL</dt>
|
||||
<dd><span class="d-was">Asked first, always</span><span class="d-now">Looked up from the address</span></dd>
|
||||
</div>
|
||||
<div class="d-cell">
|
||||
<dt>Password in the app</dt>
|
||||
<dd><span class="d-was">Default path</span><span class="d-now">Fallback only</span></dd>
|
||||
</div>
|
||||
<div class="d-cell">
|
||||
<dt>QR sign-in</dt>
|
||||
<dd><span class="d-was">Ghost button, disabled</span><span class="d-now">First option offered</span></dd>
|
||||
</div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section class="d-section">
|
||||
<h2 class="d-h2">Today</h2>
|
||||
<p class="d-lede">
|
||||
Everything at once, in the least helpful order. The webmail handoff is the safer route — it never puts a
|
||||
password into the app — but it's disabled until you've supplied the server, so it can't rescue anyone who's stuck.
|
||||
</p>
|
||||
<hr class="d-rule" />
|
||||
|
||||
<div class="d-strip">
|
||||
<figure>
|
||||
<div class="p">
|
||||
<div class="p-notch"></div>
|
||||
<div class="p-screen">
|
||||
<div class="p-pad is-centered">
|
||||
<div class="s-brand">
|
||||
<div class="s-logo"><svg><use href="#i-shield" /></svg></div>
|
||||
<h1>Bulwark Mail</h1>
|
||||
<p>Secure. Private. Yours.</p>
|
||||
</div>
|
||||
|
||||
<div class="s-old-field">
|
||||
<div class="s-label">Server URL</div>
|
||||
<div class="s-input"><span class="s-ph">https://mail.example.com</span></div>
|
||||
</div>
|
||||
<div class="s-old-field">
|
||||
<div class="s-label">Email or Username</div>
|
||||
<div class="s-input"><span class="s-ph">you@example.com</span></div>
|
||||
</div>
|
||||
<div class="s-old-field">
|
||||
<div class="s-label">Password</div>
|
||||
<div class="s-input">
|
||||
<span class="s-ph" style="flex:1">Enter your password</span>
|
||||
<svg><use href="#i-eye" /></svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="s-btn is-off" style="margin-top:12px">Sign In</div>
|
||||
|
||||
<div class="s-divider"><span>or continue with</span></div>
|
||||
<div class="s-stack">
|
||||
<div class="s-btn is-quiet" style="margin-top:0;opacity:0.45">Sign in via webmail</div>
|
||||
<div class="s-link is-muted" style="margin-top:2px;opacity:0.45">Scan QR code</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="s-foot">Bulwark Mobile v1.4.0<br /><span style="color:var(--app-primary)">Privacy Policy</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>
|
||||
<span class="d-step is-alt">Current build</span>
|
||||
<span class="d-cap-title">One screen, six controls</span>
|
||||
<p class="d-cap-body">
|
||||
The two disabled controls at the bottom are the ones that would have helped. Nothing tells you where
|
||||
to find a server URL, and nothing happens if you don't have one.
|
||||
</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="d-section">
|
||||
<h2 class="d-h2">Proposed flow</h2>
|
||||
<p class="d-lede">
|
||||
One question per screen, cheapest question first. The screens below are the happy path, left to right.
|
||||
</p>
|
||||
<hr class="d-rule" />
|
||||
|
||||
<div class="d-strip">
|
||||
|
||||
<!-- 1 · welcome -->
|
||||
<figure>
|
||||
<div class="p">
|
||||
<div class="p-notch"></div>
|
||||
<div class="p-screen">
|
||||
<div class="p-pad is-centered">
|
||||
<div class="s-brand">
|
||||
<div class="s-logo"><svg><use href="#i-shield" /></svg></div>
|
||||
<h1>Bulwark Mail</h1>
|
||||
<p>Secure. Private. Yours.</p>
|
||||
</div>
|
||||
|
||||
<div class="s-stack">
|
||||
<div class="s-tile is-primary">
|
||||
<svg class="s-tile-ico"><use href="#i-qr" /></svg>
|
||||
<span class="s-tile-txt">
|
||||
<span class="s-tile-t">Scan a sign-in code</span>
|
||||
<span class="s-tile-d">Already signed in on the web? Fastest way in.</span>
|
||||
</span>
|
||||
<svg class="s-tile-chev"><use href="#i-chev" /></svg>
|
||||
</div>
|
||||
<div class="s-tile">
|
||||
<svg class="s-tile-ico"><use href="#i-mail" /></svg>
|
||||
<span class="s-tile-txt">
|
||||
<span class="s-tile-t">Use my email address</span>
|
||||
<span class="s-tile-d">We'll find your mail server</span>
|
||||
</span>
|
||||
<svg class="s-tile-chev"><use href="#i-chev" /></svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="s-link is-muted">Enter server details manually</div>
|
||||
</div>
|
||||
<div class="s-foot">Bulwark Mobile v1.4.0<br /><span style="color:var(--app-primary)">Privacy Policy</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>
|
||||
<span class="d-step">Step 1</span>
|
||||
<span class="d-cap-title">Pick a way in</span>
|
||||
<p class="d-cap-body">
|
||||
Two live options instead of six mixed ones. Each tile says what it costs you before you tap it.
|
||||
Manual setup stays reachable in one tap — it just isn't the greeting.
|
||||
</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
<!-- 2 · email -->
|
||||
<figure>
|
||||
<div class="p">
|
||||
<div class="p-notch"></div>
|
||||
<div class="p-screen">
|
||||
<div class="p-pad">
|
||||
<svg class="s-back"><use href="#i-back" /></svg>
|
||||
<h2 class="s-h">What's your email address?</h2>
|
||||
<p class="s-sub">That's usually all we need — we'll look up the mail server for you.</p>
|
||||
|
||||
<div class="s-field">
|
||||
<div class="s-input is-focus">
|
||||
<svg><use href="#i-mail" /></svg>
|
||||
<span>ada@example.com</span><span class="s-caret"></span>
|
||||
</div>
|
||||
<p class="s-hint">Works with Bulwark, Stalwart, and any JMAP mail server.</p>
|
||||
</div>
|
||||
|
||||
<div class="s-btn">Continue</div>
|
||||
<div style="flex:1"></div>
|
||||
<div class="s-link is-muted">I know my server address</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>
|
||||
<span class="d-step">Step 2</span>
|
||||
<span class="d-cap-title">One field, keyboard already up</span>
|
||||
<p class="d-cap-body">
|
||||
Autofocus with the email keyboard, autocorrect off. The button stays enabled and validates on tap,
|
||||
so nobody is left staring at a dead grey button wondering which field is wrong.
|
||||
</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
<!-- 3 · found server -->
|
||||
<figure>
|
||||
<div class="p">
|
||||
<div class="p-notch"></div>
|
||||
<div class="p-screen">
|
||||
<div class="p-pad">
|
||||
<svg class="s-back"><use href="#i-back" /></svg>
|
||||
<h2 class="s-h">Found your mail server</h2>
|
||||
<p class="s-sub">Next you'll sign in on your provider's own page.</p>
|
||||
|
||||
<div class="s-card">
|
||||
<span class="s-card-ico"><svg><use href="#i-globe" /></svg></span>
|
||||
<span>
|
||||
<span class="s-card-t">mail.example.com</span>
|
||||
<span class="s-card-d"><i class="s-dot"></i> JMAP · secure connection</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="s-note">
|
||||
<svg><use href="#i-lock" /></svg>
|
||||
<span>Your password is typed on your provider's page, never into this app. Bulwark stores a token it can revoke.</span>
|
||||
</div>
|
||||
|
||||
<div class="s-btn">Continue</div>
|
||||
<div class="s-link">Use a different server</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>
|
||||
<span class="d-step">Step 3</span>
|
||||
<span class="d-cap-title">Confirm before the browser opens</span>
|
||||
<p class="d-cap-body">
|
||||
A browser jump with no warning feels like a bug. Naming the server first — and saying why the
|
||||
password isn't asked for here — turns the detour into a security feature.
|
||||
</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
<!-- 4 · handoff -->
|
||||
<figure>
|
||||
<div class="p">
|
||||
<div class="p-notch"></div>
|
||||
<div class="p-screen">
|
||||
<div class="p-pad is-centered" style="opacity:0.5">
|
||||
<div class="s-brand">
|
||||
<div class="s-logo"><svg><use href="#i-shield" /></svg></div>
|
||||
<h1>Bulwark Mail</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div class="s-scrim"></div>
|
||||
<div class="s-sheet">
|
||||
<div class="s-sheet-bar">
|
||||
<svg><use href="#i-lock" /></svg>
|
||||
<span class="s-url">mail.example.com</span>
|
||||
<span class="s-done">Done</span>
|
||||
</div>
|
||||
<div class="s-sheet-body">
|
||||
<div class="s-web-brand">
|
||||
<span class="s-web-mark"><svg><use href="#i-shield" /></svg></span>
|
||||
<b>Sign in to Bulwark</b>
|
||||
</div>
|
||||
<div class="s-label">Email</div>
|
||||
<div class="s-input"><span>ada@example.com</span></div>
|
||||
<div class="s-label" style="margin-top:14px">Password</div>
|
||||
<div class="s-input is-focus">
|
||||
<span style="flex:1">••••••••••</span><svg><use href="#i-eye" /></svg>
|
||||
</div>
|
||||
<div class="s-btn">Sign in</div>
|
||||
<div class="s-divider"><span>or</span></div>
|
||||
<div class="s-tile" style="padding:11px 13px">
|
||||
<svg class="s-tile-ico"><use href="#i-key" /></svg>
|
||||
<span class="s-tile-txt"><span class="s-tile-t">Continue with passkey</span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>
|
||||
<span class="d-step">Step 4</span>
|
||||
<span class="d-cap-title">The provider's page, in a sheet</span>
|
||||
<p class="d-cap-body">
|
||||
This is the existing <code>runWebmailHandoff</code> flow, unchanged. It already supports whatever
|
||||
the server offers — password, OAuth, passkeys, SSO — which the in-app form never will.
|
||||
</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
<!-- 5 · setting up -->
|
||||
<figure>
|
||||
<div class="p">
|
||||
<div class="p-notch"></div>
|
||||
<div class="p-screen">
|
||||
<div class="p-pad is-centered">
|
||||
<div style="text-align:center;margin-bottom:26px">
|
||||
<span class="s-av" style="width:60px;height:60px;font-size:22px;background:var(--app-primary);margin:0 auto 14px">AL</span>
|
||||
<h2 class="s-h" style="font-size:20px">Welcome back, Ada</h2>
|
||||
<p class="s-sub">ada@example.com</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div class="s-prog">
|
||||
<span class="s-tick"><svg><use href="#i-check" /></svg></span> Mailboxes
|
||||
</div>
|
||||
<div class="s-prog">
|
||||
<span class="s-tick"><svg><use href="#i-check" /></svg></span> Recent mail
|
||||
</div>
|
||||
<div class="s-prog is-pending">
|
||||
<span class="s-spin"></span> Contacts and calendars
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>
|
||||
<span class="d-step">Step 5</span>
|
||||
<span class="d-cap-title">Land on progress, not a spinner</span>
|
||||
<p class="d-cap-body">
|
||||
The first sync is the slowest moment in the app. Naming what's arriving makes the wait legible, and
|
||||
the inbox opens as soon as mailboxes land — the rest fills in behind it.
|
||||
</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="d-section">
|
||||
<h2 class="d-h2">When it doesn't go smoothly</h2>
|
||||
<p class="d-lede">
|
||||
Self-hosted servers, typo'd passwords, and second accounts are the normal case for this audience, not the
|
||||
exception. These four screens carry most of the redesign's weight.
|
||||
</p>
|
||||
<hr class="d-rule" />
|
||||
|
||||
<div class="d-strip">
|
||||
|
||||
<!-- scanner -->
|
||||
<figure>
|
||||
<div class="p">
|
||||
<div class="p-notch"></div>
|
||||
<div class="p-screen is-camera">
|
||||
<div class="s-cam"><div class="s-cam-grid"></div></div>
|
||||
<div class="s-cam-top">
|
||||
<svg><use href="#i-x" /></svg>
|
||||
<span style="font-size:12.5px;opacity:0.8">Sign-in code</span>
|
||||
<span style="width:22px"></span>
|
||||
</div>
|
||||
<div class="s-reticle">
|
||||
<i></i><i></i><i></i><i></i>
|
||||
<div class="s-qr">
|
||||
<b></b><b></b><b></b><b style="background:transparent"></b><b></b><b style="background:transparent"></b><b></b><b></b><b></b>
|
||||
<b></b><b style="background:transparent"></b><b></b><b></b><b style="background:transparent"></b><b></b><b></b><b style="background:transparent"></b><b></b>
|
||||
<b></b><b></b><b></b><b style="background:transparent"></b><b></b><b></b><b></b><b></b><b></b>
|
||||
<b style="background:transparent"></b><b></b><b style="background:transparent"></b><b></b><b></b><b style="background:transparent"></b><b></b><b style="background:transparent"></b><b></b>
|
||||
<b></b><b></b><b></b><b></b><b style="background:transparent"></b><b></b><b></b><b></b><b style="background:transparent"></b>
|
||||
<b></b><b style="background:transparent"></b><b></b><b style="background:transparent"></b><b></b><b></b><b style="background:transparent"></b><b></b><b></b>
|
||||
<b></b><b></b><b></b><b></b><b></b><b style="background:transparent"></b><b></b><b></b><b></b>
|
||||
<b></b><b style="background:transparent"></b><b></b><b style="background:transparent"></b><b></b><b></b><b></b><b style="background:transparent"></b><b></b>
|
||||
<b></b><b></b><b></b><b></b><b style="background:transparent"></b><b></b><b></b><b></b><b></b>
|
||||
</div>
|
||||
</div>
|
||||
<div class="s-cam-copy">
|
||||
<p class="s-cam-h">Open Bulwark on your computer</p>
|
||||
<p>Settings → Devices → Add phone shows a code. Point the camera at it.</p>
|
||||
<p class="s-cam-link">Type the code instead</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>
|
||||
<span class="d-step">Path A</span>
|
||||
<span class="d-cap-title">The scanner tells you where the code is</span>
|
||||
<p class="d-cap-body">
|
||||
A scanner with no instructions is a dead end for anyone who hasn't seen the webmail's Devices page.
|
||||
Redeeming a paired code skips the browser entirely — see <code>redeemPairingCode</code>.
|
||||
</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
<!-- discovery failed -->
|
||||
<figure>
|
||||
<div class="p">
|
||||
<div class="p-notch"></div>
|
||||
<div class="p-screen">
|
||||
<div class="p-pad">
|
||||
<svg class="s-back"><use href="#i-back" /></svg>
|
||||
<h2 class="s-h">Where does your mail live?</h2>
|
||||
<p class="s-sub">We couldn't find a server for <b>example.org</b>. If you self-host, the address is the one you use for webmail.</p>
|
||||
|
||||
<div class="s-field">
|
||||
<div class="s-label">Server address</div>
|
||||
<div class="s-input is-focus">
|
||||
<svg><use href="#i-globe" /></svg>
|
||||
<span>mail.example.org</span><span class="s-caret"></span>
|
||||
</div>
|
||||
<p class="s-hint">Same address you type in the browser. We'll add <b>https://</b>.</p>
|
||||
</div>
|
||||
|
||||
<div class="s-btn">Continue</div>
|
||||
<div style="flex:1"></div>
|
||||
<div class="s-note">
|
||||
<svg><use href="#i-qr" /></svg>
|
||||
<span>Not sure? Scan a sign-in code from the webmail instead — it carries the address with it.</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>
|
||||
<span class="d-step is-alt">Path B</span>
|
||||
<span class="d-cap-title">Ask for the server people know</span>
|
||||
<p class="d-cap-body">
|
||||
Not the JMAP session URL — the webmail address they type every day. The scheme is added for them, and
|
||||
a trailing slash or full <code>/jmap</code> path is accepted and trimmed.
|
||||
</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
<!-- password fallback + error -->
|
||||
<figure>
|
||||
<div class="p">
|
||||
<div class="p-notch"></div>
|
||||
<div class="p-screen">
|
||||
<div class="p-pad">
|
||||
<svg class="s-back"><use href="#i-back" /></svg>
|
||||
<h2 class="s-h">Sign in to mail.example.org</h2>
|
||||
<p class="s-sub">This server doesn't support the browser sign-in, so we'll ask here.</p>
|
||||
|
||||
<div class="s-field" style="margin-top:18px">
|
||||
<div class="s-label">Email or username</div>
|
||||
<div class="s-input"><span>ada@example.org</span></div>
|
||||
</div>
|
||||
|
||||
<div class="s-field" style="margin-top:14px">
|
||||
<div class="s-label">Password</div>
|
||||
<div class="s-input is-error">
|
||||
<span style="flex:1">••••••••</span><svg><use href="#i-eye" /></svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="s-banner">
|
||||
<svg><use href="#i-alert" /></svg>
|
||||
<span><b>That password didn't work.</b> If your account has two-factor sign-in, you'll need an app password from the webmail.</span>
|
||||
</div>
|
||||
|
||||
<div class="s-btn">Sign in</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>
|
||||
<span class="d-step is-alt">Path C</span>
|
||||
<span class="d-cap-title">Errors that name the likely cause</span>
|
||||
<p class="d-cap-body">
|
||||
The store's raw error string is replaced with mapped copy per failure: wrong credentials, unreachable
|
||||
host, bad certificate, 2FA-needs-an-app-password. Each says what to do next.
|
||||
</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
<!-- add account -->
|
||||
<figure>
|
||||
<div class="p">
|
||||
<div class="p-notch"></div>
|
||||
<div class="p-screen">
|
||||
<div class="p-pad">
|
||||
<div style="display:flex;justify-content:flex-end"><svg class="s-back" style="margin-bottom:14px"><use href="#i-x" /></svg></div>
|
||||
<h2 class="s-h">Add another account</h2>
|
||||
<p class="s-sub">You're signed in to these already.</p>
|
||||
|
||||
<div style="margin-top:16px">
|
||||
<div class="s-acct">
|
||||
<span class="s-av" style="background:#3b82f6">AL</span>
|
||||
<span><span class="s-acct-t">Ada Lovelace</span><span class="s-acct-d">ada@example.com</span></span>
|
||||
</div>
|
||||
<div class="s-acct">
|
||||
<span class="s-av" style="background:#a855f7">AL</span>
|
||||
<span><span class="s-acct-t">Work</span><span class="s-acct-d">a.lovelace@analytical.co</span></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="s-divider"><span>add</span></div>
|
||||
|
||||
<div class="s-stack">
|
||||
<div class="s-tile">
|
||||
<svg class="s-tile-ico"><use href="#i-plus" /></svg>
|
||||
<span class="s-tile-txt">
|
||||
<span class="s-tile-t">Another account on example.com</span>
|
||||
<span class="s-tile-d">Server already known</span>
|
||||
</span>
|
||||
<svg class="s-tile-chev"><use href="#i-chev" /></svg>
|
||||
</div>
|
||||
<div class="s-tile">
|
||||
<svg class="s-tile-ico"><use href="#i-mail" /></svg>
|
||||
<span class="s-tile-txt"><span class="s-tile-t">A different provider</span></span>
|
||||
<svg class="s-tile-chev"><use href="#i-chev" /></svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption>
|
||||
<span class="d-step is-alt">Add mode</span>
|
||||
<span class="d-cap-title">Reuse what we already know</span>
|
||||
<p class="d-cap-body">
|
||||
<code>isAddMode</code> currently shows the same blank three-field form. Most second accounts live on
|
||||
the same server as the first, so offer that first and skip discovery entirely.
|
||||
</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="d-section">
|
||||
<h2 class="d-h2">Notes for the build</h2>
|
||||
<hr class="d-rule" />
|
||||
<ul class="d-notes">
|
||||
<li>
|
||||
<svg><use href="#i-globe" /></svg>
|
||||
<div>
|
||||
<div class="d-note-h">Discovery is three cheap probes, in order</div>
|
||||
<p class="d-note-b">
|
||||
From <code>ada@example.com</code>: try <code>https://example.com/.well-known/jmap</code>, then
|
||||
<code>https://mail.example.com/.well-known/jmap</code>, then the same host the last account used.
|
||||
First 200 wins. Budget the whole thing at two seconds and fall through to Path B on timeout — a
|
||||
slow lookup must never be worse than the manual form.
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<svg><use href="#i-shield" /></svg>
|
||||
<div>
|
||||
<div class="d-note-h">Nothing new on the wire</div>
|
||||
<p class="d-note-b">
|
||||
Every screen drives an existing store action — <code>loginViaWebmail</code>,
|
||||
<code>loginViaPairing</code>, <code>login</code>. The redesign is routing and copy; the auth
|
||||
surface, the state machine, and <code>parseQrLoginPayload</code> stay as they are.
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<svg><use href="#i-alert" /></svg>
|
||||
<div>
|
||||
<div class="d-note-h">Back must always work</div>
|
||||
<p class="d-note-b">
|
||||
A multi-step flow earns a hardware-back handler on Android. Every step goes back one, and step 1
|
||||
leaves the flow — never a trapped screen with a filled-in field you can't clear.
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<svg><use href="#i-key" /></svg>
|
||||
<div>
|
||||
<div class="d-note-h">Let the OS help</div>
|
||||
<p class="d-note-b">
|
||||
<code>autoComplete="email"</code> and <code>textContentType="username"</code> on the address field,
|
||||
<code>"password"</code> on the fallback field, so the platform password manager offers to fill and
|
||||
save. The current screen sets neither.
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<p class="d-foot">Mockup · repos/react-native/mockups/login.html · static HTML, no interaction wired up</p>
|
||||
</div>
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "bulwark-mobile",
|
||||
"version": "0.1.45",
|
||||
"version": "0.1.56",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "bulwark-mobile",
|
||||
"version": "0.1.45",
|
||||
"version": "0.1.56",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@react-native-async-storage/async-storage": "2.2.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "bulwark-mobile",
|
||||
"version": "0.1.45",
|
||||
"version": "0.1.56",
|
||||
"license": "AGPL-3.0-only",
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -42,10 +42,10 @@ describe('calendar operations', () => {
|
||||
});
|
||||
|
||||
describe('queryEvents', () => {
|
||||
it('should send a CalendarEvent/query without server-side filter', async () => {
|
||||
// Stalwart rejects inCalendars/after/before, so we fetch unfiltered and
|
||||
// filter client-side. Asserting on the absence of `filter` keeps that
|
||||
// contract pinned.
|
||||
it('should filter via singular inCalendar conditions (Stalwart-compatible)', async () => {
|
||||
// Stalwart rejects the draft's plural `inCalendars` filter (and
|
||||
// after/before); calendars are restricted via singular `inCalendar`
|
||||
// conditions and date filtering stays client-side.
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['CalendarEvent/query', { ids: ['ev1', 'ev2'] }, '0']],
|
||||
});
|
||||
@@ -55,13 +55,42 @@ describe('calendar operations', () => {
|
||||
|
||||
const call = mockRequest.mock.calls[0][0][0];
|
||||
expect(call[0]).toBe('CalendarEvent/query');
|
||||
expect(call[1].filter).toBeUndefined();
|
||||
expect(call[1].filter).toEqual({ inCalendar: 'cal-1' });
|
||||
expect(call[1].accountId).toBe('acc-1');
|
||||
});
|
||||
|
||||
it('should OR multiple calendars and respect the target account', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['CalendarEvent/query', { ids: [] }, '0']],
|
||||
});
|
||||
|
||||
await queryEvents(['cal-1', 'cal-2'], '', '', 'acc-shared');
|
||||
|
||||
const call = mockRequest.mock.calls[0][0][0];
|
||||
expect(call[1].filter).toEqual({
|
||||
operator: 'OR',
|
||||
conditions: [{ inCalendar: 'cal-1' }, { inCalendar: 'cal-2' }],
|
||||
});
|
||||
expect(call[1].accountId).toBe('acc-shared');
|
||||
});
|
||||
|
||||
it('should omit the filter when no calendars are given', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['CalendarEvent/query', { ids: [] }, '0']],
|
||||
});
|
||||
|
||||
await queryEvents([], '', '');
|
||||
|
||||
const call = mockRequest.mock.calls[0][0][0];
|
||||
expect(call[1].filter).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getEvents', () => {
|
||||
it('should fetch events by id with expected properties', async () => {
|
||||
it('should fetch events by id with singular JSCalendar 2.0 recurrence properties', async () => {
|
||||
// Stalwart (calcard) names the property `recurrenceRule` (singular,
|
||||
// single object) — requesting the RFC 8984 plural form returns no
|
||||
// recurrence data and repeating events vanish from the grid (#13).
|
||||
const events = [{ id: 'ev1', title: 'Meeting', start: '2026-03-29T10:00:00' }];
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['CalendarEvent/get', { list: events }, '0']],
|
||||
@@ -73,7 +102,48 @@ describe('calendar operations', () => {
|
||||
const call = mockRequest.mock.calls[0][0][0];
|
||||
expect(call[1].properties).toContain('title');
|
||||
expect(call[1].properties).toContain('start');
|
||||
expect(call[1].properties).toContain('recurrenceRules');
|
||||
expect(call[1].properties).toContain('recurrenceRule');
|
||||
expect(call[1].properties).toContain('excludedRecurrenceRule');
|
||||
expect(call[1].properties).not.toContain('recurrenceRules');
|
||||
expect(call[1].properties).not.toContain('excludedRecurrenceRules');
|
||||
});
|
||||
|
||||
it('should normalize a singular recurrenceRule object to the plural array form', async () => {
|
||||
const events = [{
|
||||
id: 'ev1',
|
||||
title: 'Every 5 weeks',
|
||||
start: '2026-03-02T10:00:00',
|
||||
recurrenceRule: { '@type': 'RecurrenceRule', frequency: 'weekly', interval: 5 },
|
||||
excludedRecurrenceRule: { frequency: 'weekly', interval: 10 },
|
||||
}];
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['CalendarEvent/get', { list: events }, '0']],
|
||||
});
|
||||
|
||||
const [event] = await getEvents(['ev1']);
|
||||
expect(event.recurrenceRules).toEqual([
|
||||
{ '@type': 'RecurrenceRule', frequency: 'weekly', interval: 5 },
|
||||
]);
|
||||
expect(event.excludedRecurrenceRules).toEqual([
|
||||
{ frequency: 'weekly', interval: 10 },
|
||||
]);
|
||||
expect(event).not.toHaveProperty('recurrenceRule');
|
||||
expect(event).not.toHaveProperty('excludedRecurrenceRule');
|
||||
});
|
||||
|
||||
it('should keep an array-valued recurrenceRule as-is (JMAP-created events)', async () => {
|
||||
const events = [{
|
||||
id: 'ev1',
|
||||
title: 'Weekly',
|
||||
start: '2026-03-02T10:00:00',
|
||||
recurrenceRule: [{ frequency: 'weekly', interval: 2 }],
|
||||
}];
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['CalendarEvent/get', { list: events }, '0']],
|
||||
});
|
||||
|
||||
const [event] = await getEvents(['ev1']);
|
||||
expect(event.recurrenceRules).toEqual([{ frequency: 'weekly', interval: 2 }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -89,10 +159,39 @@ describe('calendar operations', () => {
|
||||
'cal-1',
|
||||
);
|
||||
|
||||
expect(result).toEqual(created);
|
||||
// The /set response echoes only server-set properties; the return value
|
||||
// merges them over the submitted payload.
|
||||
expect(result).toEqual({
|
||||
id: 'ev-new',
|
||||
title: 'Lunch',
|
||||
start: '2026-03-30T12:00:00',
|
||||
duration: 'PT1H',
|
||||
calendarIds: { 'cal-1': true },
|
||||
});
|
||||
const call = mockRequest.mock.calls[0][0][0];
|
||||
expect(call[1].create['new-event'].calendarIds).toEqual({ 'cal-1': true });
|
||||
});
|
||||
|
||||
it('should send recurrence as a singular cleaned object', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['CalendarEvent/set', { created: { 'new-event': { id: 'ev-new' } } }, '0']],
|
||||
});
|
||||
|
||||
const result = await createEvent(
|
||||
{
|
||||
title: 'Series',
|
||||
start: '2026-03-30T12:00:00',
|
||||
recurrenceRules: [{ frequency: 'weekly', interval: 5, until: null as unknown as string }],
|
||||
},
|
||||
'cal-1',
|
||||
);
|
||||
|
||||
const sent = mockRequest.mock.calls[0][0][0][1].create['new-event'];
|
||||
expect(sent.recurrenceRule).toEqual({ frequency: 'weekly', interval: 5 });
|
||||
expect(sent).not.toHaveProperty('recurrenceRules');
|
||||
// The returned event exposes the internal plural form again.
|
||||
expect(result.recurrenceRules).toEqual([{ frequency: 'weekly', interval: 5 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateEvent', () => {
|
||||
@@ -106,6 +205,23 @@ describe('calendar operations', () => {
|
||||
const call = mockRequest.mock.calls[0][0][0];
|
||||
expect(call[1].update).toEqual({ ev1: { title: 'Updated Meeting' } });
|
||||
});
|
||||
|
||||
it('should convert recurrenceRules updates to the singular property', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['CalendarEvent/set', { updated: {} }, '0']],
|
||||
});
|
||||
|
||||
await updateEvent('ev1', { recurrenceRules: [{ frequency: 'monthly' }] });
|
||||
expect(mockRequest.mock.calls[0][0][0][1].update).toEqual({
|
||||
ev1: { recurrenceRule: { frequency: 'monthly' } },
|
||||
});
|
||||
|
||||
// Empty array means "remove recurrence" — sent as an explicit null.
|
||||
await updateEvent('ev1', { recurrenceRules: [] });
|
||||
expect(mockRequest.mock.calls[1][0][0][1].update).toEqual({
|
||||
ev1: { recurrenceRule: null },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteEvents', () => {
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('../jmap-client', () => ({
|
||||
jmapClient: {
|
||||
accountId: 'acc-1',
|
||||
request: vi.fn(),
|
||||
hasCapability: vi.fn(),
|
||||
currentSession: null as unknown,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../blob', () => ({
|
||||
getDownloadUrl: vi.fn(
|
||||
(blobId: string, _name?: string, _type?: string, accountId?: string) =>
|
||||
`https://dl/${accountId ?? 'own'}/${blobId}`,
|
||||
),
|
||||
uploadBlob: vi.fn(),
|
||||
uploadBytes: vi.fn(),
|
||||
}));
|
||||
|
||||
import { jmapClient } from '../jmap-client';
|
||||
import { CAPABILITIES } from '../types';
|
||||
import {
|
||||
createFolder,
|
||||
deleteFileNodes,
|
||||
getAllFileNodesAcrossAccounts,
|
||||
getFileNodeDownloadUrl,
|
||||
getPrincipals,
|
||||
isCrossAccountId,
|
||||
isFolder,
|
||||
setFileNodeShare,
|
||||
} from '../files';
|
||||
|
||||
const mockRequest = jmapClient.request as ReturnType<typeof vi.fn>;
|
||||
const mockHasCapability = jmapClient.hasCapability as ReturnType<typeof vi.fn>;
|
||||
|
||||
function setSession(session: unknown) {
|
||||
(jmapClient as { currentSession: unknown }).currentSession = session;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockHasCapability.mockImplementation(
|
||||
(urn: string) => urn === CAPABILITIES.FILES || urn === CAPABILITIES.PRINCIPALS,
|
||||
);
|
||||
setSession({
|
||||
primaryAccounts: { [CAPABILITIES.FILES]: 'acc-1' },
|
||||
accounts: {
|
||||
'acc-1': { name: 'me@example.com', isPersonal: true },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
describe('isFolder', () => {
|
||||
it('treats blob-less nodes as folders and anything with a blob as a file', () => {
|
||||
// #379: a blob-marked node — even the legacy type:'d' dir markers — is a
|
||||
// 0-byte file that nothing can be parented under.
|
||||
expect(isFolder({ blobId: null })).toBe(true);
|
||||
expect(isFolder({ blobId: undefined })).toBe(true);
|
||||
expect(isFolder({ blobId: 'blob-1' })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createFolder', () => {
|
||||
it('creates a real container node: no blobId/type/size, parentId set', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['FileNode/set', { created: { 'new-dir': { id: 'f1' } } }, '0']],
|
||||
});
|
||||
|
||||
await createFolder('Docs', 'parent-1');
|
||||
|
||||
const [method, args] = mockRequest.mock.calls[0][0][0];
|
||||
expect(method).toBe('FileNode/set');
|
||||
expect(args.create['new-dir']).toEqual({ name: 'Docs', parentId: 'parent-1' });
|
||||
});
|
||||
|
||||
it('omits parentId at the root', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['FileNode/set', { created: { 'new-dir': { id: 'f1' } } }, '0']],
|
||||
});
|
||||
|
||||
await createFolder('Docs', null);
|
||||
|
||||
const args = mockRequest.mock.calls[0][0][0][1];
|
||||
expect(args.create['new-dir']).toEqual({ name: 'Docs' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteFileNodes', () => {
|
||||
it('lets the server cascade into folder children', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['FileNode/set', { destroyed: ['f1'] }, '0']],
|
||||
});
|
||||
|
||||
await deleteFileNodes(['f1']);
|
||||
|
||||
const args = mockRequest.mock.calls[0][0][0][1];
|
||||
expect(args.destroy).toEqual(['f1']);
|
||||
expect(args.onDestroyRemoveChildren).toBe(true);
|
||||
});
|
||||
|
||||
it('throws when the server refuses a destroy', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [
|
||||
['FileNode/set', { notDestroyed: { f1: { description: 'forbidden' } } }, '0'],
|
||||
],
|
||||
});
|
||||
|
||||
await expect(deleteFileNodes(['f1'])).rejects.toThrow('forbidden');
|
||||
});
|
||||
});
|
||||
|
||||
describe('setFileNodeShare', () => {
|
||||
it('patches shareWith/{principalId} and requests the principals:owner capability', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['FileNode/set', { updated: { 'node-1': null } }, '0']],
|
||||
});
|
||||
const rights = {
|
||||
mayRead: true, mayAddChildren: false, mayRename: false,
|
||||
mayDelete: false, mayModifyContent: false, mayShare: false,
|
||||
};
|
||||
|
||||
await setFileNodeShare('node-1', 'principal-2', rights);
|
||||
|
||||
const [calls, using] = mockRequest.mock.calls[0];
|
||||
expect(calls[0][1].update['node-1']).toEqual({ 'shareWith/principal-2': rights });
|
||||
expect(using).toContain(CAPABILITIES.PRINCIPALS_OWNER);
|
||||
});
|
||||
|
||||
it('sends null rights to revoke access', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['FileNode/set', { updated: { 'node-1': null } }, '0']],
|
||||
});
|
||||
|
||||
await setFileNodeShare('node-1', 'principal-2', null);
|
||||
|
||||
const args = mockRequest.mock.calls[0][0][0][1];
|
||||
expect(args.update['node-1']).toEqual({ 'shareWith/principal-2': null });
|
||||
});
|
||||
|
||||
it('throws when the server rejects or does not confirm the update', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [
|
||||
['FileNode/set', { notUpdated: { 'node-1': { description: 'no mayShare right' } } }, '0'],
|
||||
],
|
||||
});
|
||||
await expect(setFileNodeShare('node-1', 'p2', null)).rejects.toThrow('no mayShare right');
|
||||
|
||||
mockRequest.mockResolvedValue({ methodResponses: [['FileNode/set', {}, '0']] });
|
||||
await expect(setFileNodeShare('node-1', 'p2', null)).rejects.toThrow(
|
||||
'Server did not confirm the share update',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAllFileNodesAcrossAccounts', () => {
|
||||
it('namespaces ids of nodes from other principals and tags them isShared', async () => {
|
||||
setSession({
|
||||
primaryAccounts: { [CAPABILITIES.FILES]: 'acc-1' },
|
||||
accounts: {
|
||||
'acc-1': { name: 'me@example.com', isPersonal: true },
|
||||
'acc-2': { name: 'Team', isPersonal: false },
|
||||
},
|
||||
});
|
||||
mockRequest
|
||||
.mockResolvedValueOnce({
|
||||
methodResponses: [
|
||||
['FileNode/get', { list: [{ id: 'own-1', name: 'mine.txt', parentId: null, blobId: 'b1' }] }, '0'],
|
||||
],
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
methodResponses: [
|
||||
['FileNode/get', {
|
||||
list: [
|
||||
{ id: 's1', name: 'Shared Folder', parentId: null, blobId: null },
|
||||
{ id: 's2', name: 'inside.txt', parentId: 's1', blobId: 'b2' },
|
||||
],
|
||||
}, '0'],
|
||||
],
|
||||
});
|
||||
|
||||
const nodes = await getAllFileNodesAcrossAccounts();
|
||||
|
||||
expect(nodes).toHaveLength(3);
|
||||
const own = nodes.find((n) => n.id === 'own-1')!;
|
||||
expect(own.isShared).toBe(false);
|
||||
expect(isCrossAccountId(own.id)).toBe(false);
|
||||
|
||||
const folder = nodes.find((n) => n.name === 'Shared Folder')!;
|
||||
expect(folder.id).toBe('acc-2:s1');
|
||||
expect(folder.isShared).toBe(true);
|
||||
expect(folder.accountId).toBe('acc-2');
|
||||
expect(folder.accountName).toBe('Team');
|
||||
|
||||
// parentId is namespaced the same way so child lookups keep working.
|
||||
const child = nodes.find((n) => n.name === 'inside.txt')!;
|
||||
expect(child.parentId).toBe('acc-2:s1');
|
||||
});
|
||||
|
||||
it('skips personal accounts without the filenode capability', async () => {
|
||||
setSession({
|
||||
primaryAccounts: { [CAPABILITIES.FILES]: 'acc-1' },
|
||||
accounts: {
|
||||
'acc-1': { name: 'me@example.com', isPersonal: true },
|
||||
'acc-3': { name: 'other personal', isPersonal: true },
|
||||
},
|
||||
});
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [['FileNode/get', { list: [] }, '0']],
|
||||
});
|
||||
|
||||
await getAllFileNodesAcrossAccounts();
|
||||
|
||||
expect(mockRequest).toHaveBeenCalledTimes(1);
|
||||
expect(mockRequest.mock.calls[0][0][0][1].accountId).toBe('acc-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFileNodeDownloadUrl', () => {
|
||||
it('routes shared blobs to the owning account', () => {
|
||||
const url = getFileNodeDownloadUrl({
|
||||
id: 'acc-2:s2', name: 'inside.txt', type: 'text/plain',
|
||||
blobId: 'b2', accountId: 'acc-2',
|
||||
});
|
||||
expect(url).toBe('https://dl/acc-2/b2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPrincipals', () => {
|
||||
it('queries then gets via back-reference', async () => {
|
||||
mockRequest.mockResolvedValue({
|
||||
methodResponses: [
|
||||
['Principal/query', { ids: ['p1'] }, '0'],
|
||||
['Principal/get', { list: [{ id: 'p1', name: 'other', type: 'individual' }] }, '1'],
|
||||
],
|
||||
});
|
||||
|
||||
const principals = await getPrincipals();
|
||||
|
||||
expect(principals).toEqual([{ id: 'p1', name: 'other', type: 'individual' }]);
|
||||
const calls = mockRequest.mock.calls[0][0];
|
||||
expect(calls[0][0]).toBe('Principal/query');
|
||||
expect(calls[1][0]).toBe('Principal/get');
|
||||
expect(calls[1][1]['#ids']).toEqual({ resultOf: '0', name: 'Principal/query', path: '/ids' });
|
||||
});
|
||||
|
||||
it('returns empty when the server lacks the principals capability', async () => {
|
||||
mockHasCapability.mockReturnValue(false);
|
||||
expect(await getPrincipals()).toEqual([]);
|
||||
expect(mockRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+4
-1
@@ -116,12 +116,15 @@ export function getDownloadUrl(
|
||||
blobId: string,
|
||||
name?: string,
|
||||
type?: string,
|
||||
// Blobs of nodes shared by another principal live in the owner's account;
|
||||
// downloading them with our own accountId 404s.
|
||||
accountId?: string,
|
||||
): string {
|
||||
const session = jmapClient.currentSession;
|
||||
if (!session) throw new Error('Not connected');
|
||||
|
||||
return session.downloadUrl
|
||||
.replace('{accountId}', encodeURIComponent(jmapClient.accountId))
|
||||
.replace('{accountId}', encodeURIComponent(accountId ?? jmapClient.accountId))
|
||||
.replace('{blobId}', encodeURIComponent(blobId))
|
||||
.replace('{name}', encodeURIComponent(name ?? 'download'))
|
||||
.replace('{type}', encodeURIComponent(type ?? 'application/octet-stream'));
|
||||
|
||||
+212
-25
@@ -4,18 +4,127 @@ import type { Calendar, CalendarEvent } from './types';
|
||||
|
||||
const USING = [CAPABILITIES.CORE, CAPABILITIES.CALENDARS];
|
||||
|
||||
/**
|
||||
* IANA time zone of the device, sent as the `timeZone` argument on
|
||||
* CalendarEvent/query and CalendarEvent/get. Stalwart interprets LocalDateTime
|
||||
* filter values and computes utcStart/utcEnd for floating events in this zone,
|
||||
* defaulting to UTC when absent — which shifts range boundaries and
|
||||
* floating-event times for any user not in UTC. Stalwart ignores unparseable
|
||||
* values, so sending it is always safe.
|
||||
*/
|
||||
function getUserTimeZone(): string | undefined {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a CalendarEvent/query filter restricting results to the given
|
||||
* calendars. Stalwart implements the singular `inCalendar` condition (one
|
||||
* calendar id per condition), not the draft's plural `inCalendars` array —
|
||||
* sending the plural form fails the whole query with `unsupportedFilter`.
|
||||
* Multiple calendars are expressed as an OR of singular conditions.
|
||||
*/
|
||||
function buildInCalendarFilter(calendarIds: string[]): Record<string, unknown> {
|
||||
if (calendarIds.length === 1) {
|
||||
return { inCalendar: calendarIds[0] };
|
||||
}
|
||||
return {
|
||||
operator: 'OR',
|
||||
conditions: calendarIds.map((id) => ({ inCalendar: id })),
|
||||
};
|
||||
}
|
||||
|
||||
// Stalwart's calcard crate implements JSCalendar 2.0 (jscalendarbis) property
|
||||
// names: singular `recurrenceRule` / `excludedRecurrenceRule` holding a single
|
||||
// object, not RFC 8984's plural array forms. Requesting the plural names
|
||||
// returns no recurrence data at all, so recurring events silently render as
|
||||
// one-off events (#13). Request the singular names and normalize below.
|
||||
const CALENDAR_EVENT_PROPERTIES = [
|
||||
'id', '@type', 'uid', 'calendarIds', 'title', 'description',
|
||||
'start', 'duration', 'timeZone', 'showWithoutTime',
|
||||
'utcStart', 'utcEnd', 'status', 'freeBusyStatus',
|
||||
'participants', 'alerts', 'useDefaultAlerts', 'recurrenceRules',
|
||||
'recurrenceOverrides', 'excludedRecurrenceRules',
|
||||
'participants', 'alerts', 'useDefaultAlerts', 'recurrenceRule',
|
||||
'recurrenceOverrides', 'excludedRecurrenceRule', 'recurrenceId',
|
||||
'replyTo', 'organizerCalendarAddress', 'sequence',
|
||||
'locations', 'virtualLocations',
|
||||
'progress', 'due', 'priority', 'percentComplete',
|
||||
'links', 'created', 'updated',
|
||||
];
|
||||
|
||||
/**
|
||||
* Normalize Stalwart's singular recurrence property names to the RFC 8984
|
||||
* plural array forms the client uses internally. JSCalendar 2.0 defines
|
||||
* recurrenceRule as a single object, but Stalwart may also return an array
|
||||
* (for events created via JMAP), so both forms are handled. Mirrors webmail's
|
||||
* normalizeStalwartPropertyNames.
|
||||
*/
|
||||
export function normalizeRecurrenceProperties<T extends Partial<CalendarEvent>>(event: T): T {
|
||||
const raw = event as Record<string, unknown>;
|
||||
let patched = false;
|
||||
const updates: Partial<CalendarEvent> = {};
|
||||
|
||||
if ('recurrenceRule' in raw && !('recurrenceRules' in raw)) {
|
||||
const val = raw.recurrenceRule;
|
||||
if (val != null && !Array.isArray(val) && typeof val === 'object') {
|
||||
updates.recurrenceRules = [val] as CalendarEvent['recurrenceRules'];
|
||||
} else {
|
||||
updates.recurrenceRules = val as CalendarEvent['recurrenceRules'];
|
||||
}
|
||||
patched = true;
|
||||
}
|
||||
if ('excludedRecurrenceRule' in raw && !('excludedRecurrenceRules' in raw)) {
|
||||
const val = raw.excludedRecurrenceRule;
|
||||
if (val != null && !Array.isArray(val) && typeof val === 'object') {
|
||||
updates.excludedRecurrenceRules = [val] as CalendarEvent['excludedRecurrenceRules'];
|
||||
} else {
|
||||
updates.excludedRecurrenceRules = val as CalendarEvent['excludedRecurrenceRules'];
|
||||
}
|
||||
patched = true;
|
||||
}
|
||||
|
||||
if (!patched) return event;
|
||||
|
||||
const result = { ...event, ...updates } as T;
|
||||
delete (result as Record<string, unknown>).recurrenceRule;
|
||||
delete (result as Record<string, unknown>).excludedRecurrenceRule;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the client's plural recurrence arrays to the singular JSCalendar 2.0
|
||||
* properties Stalwart expects on write, dropping null rule fields. An empty
|
||||
* array (or null) becomes an explicit null so "remove recurrence" round-trips.
|
||||
* Mirrors webmail's cleanRecurrenceRules.
|
||||
*/
|
||||
function cleanRecurrenceRules(event: Record<string, unknown>): void {
|
||||
const keyMap: Record<string, string> = {
|
||||
recurrenceRules: 'recurrenceRule',
|
||||
excludedRecurrenceRules: 'excludedRecurrenceRule',
|
||||
};
|
||||
for (const [pluralKey, singularKey] of Object.entries(keyMap)) {
|
||||
const rules = event[pluralKey];
|
||||
if (rules === undefined) continue;
|
||||
delete event[pluralKey];
|
||||
if (!Array.isArray(rules)) {
|
||||
event[singularKey] = rules;
|
||||
continue;
|
||||
}
|
||||
if (rules.length === 0) {
|
||||
event[singularKey] = null;
|
||||
continue;
|
||||
}
|
||||
const rule = rules[0] as Record<string, unknown>;
|
||||
const cleaned: Record<string, unknown> = {};
|
||||
for (const [k, v] of Object.entries(rule)) {
|
||||
if (v !== null) cleaned[k] = v;
|
||||
}
|
||||
event[singularKey] = cleaned;
|
||||
}
|
||||
}
|
||||
|
||||
function methodResult<T = any>(res: any, index = 0): T {
|
||||
const entry = res?.methodResponses?.[index];
|
||||
if (!entry) throw new Error('JMAP: empty method response');
|
||||
@@ -26,48 +135,97 @@ function methodResult<T = any>(res: any, index = 0): T {
|
||||
return entry[1] as T;
|
||||
}
|
||||
|
||||
// Other session accounts that expose the calendars capability hold calendars
|
||||
// shared with the user (JMAP surfaces shared data under the sharer's account).
|
||||
function sharedCalendarAccountIds(): string[] {
|
||||
const session = jmapClient.currentSession;
|
||||
const primary = jmapClient.accountId;
|
||||
return Object.entries(session?.accounts ?? {})
|
||||
.filter(([id, info]) =>
|
||||
id !== primary && !!info.accountCapabilities?.[CAPABILITIES.CALENDARS])
|
||||
.map(([id]) => id);
|
||||
}
|
||||
|
||||
export async function getCalendars(): Promise<Calendar[]> {
|
||||
const accountId = jmapClient.accountId;
|
||||
const res = await jmapClient.request(
|
||||
[['Calendar/get', { accountId }, '0']],
|
||||
USING,
|
||||
);
|
||||
return methodResult<{ list: Calendar[] }>(res).list ?? [];
|
||||
const own = methodResult<{ list: Calendar[] }>(res).list ?? [];
|
||||
|
||||
// Calendars shared with the user live in other session accounts. Failures
|
||||
// there (revoked share, transient error) must not hide the user's own
|
||||
// calendars, so each shared account is fetched best-effort.
|
||||
const shared = await Promise.all(
|
||||
sharedCalendarAccountIds().map(async (sharedAccountId) => {
|
||||
try {
|
||||
const sharedRes = await jmapClient.request(
|
||||
[['Calendar/get', { accountId: sharedAccountId }, '0']],
|
||||
USING,
|
||||
);
|
||||
const list = methodResult<{ list: Calendar[] }>(sharedRes).list ?? [];
|
||||
// JMAP calendar ids are only unique within an account, so a shared
|
||||
// "default" calendar collides with the user's own "default". Namespace
|
||||
// the id (keeping the real id in originalId) so visibility toggles,
|
||||
// event-query routing, and create/default mutations don't cross wires.
|
||||
// Mirrors webmail's getAllCalendars.
|
||||
return list.map((cal) => ({
|
||||
...cal,
|
||||
id: `${sharedAccountId}:${cal.id}`,
|
||||
originalId: cal.id,
|
||||
accountId: sharedAccountId,
|
||||
isShared: true,
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}),
|
||||
);
|
||||
return [...own, ...shared.flat()];
|
||||
}
|
||||
|
||||
export async function queryEvents(
|
||||
_calendarIds: string[],
|
||||
calendarIds: string[],
|
||||
_after: string,
|
||||
_before: string,
|
||||
accountId?: string,
|
||||
): Promise<string[]> {
|
||||
// Stalwart rejects inCalendars/after/before filters on CalendarEvent/query.
|
||||
// Fetch all events in the account; calendar visibility + date filtering is
|
||||
// done client-side.
|
||||
const accountId = jmapClient.accountId;
|
||||
// Stalwart rejects after/before filters on CalendarEvent/query; date
|
||||
// filtering is done client-side. Calendars are restricted via the singular
|
||||
// `inCalendar` condition (the plural `inCalendars` fails the whole query
|
||||
// with unsupportedFilter on Stalwart).
|
||||
const account = accountId || jmapClient.accountId;
|
||||
const args: Record<string, unknown> = { accountId: account, limit: 1000 };
|
||||
const timeZone = getUserTimeZone();
|
||||
if (timeZone) args.timeZone = timeZone;
|
||||
if (calendarIds.length > 0) args.filter = buildInCalendarFilter(calendarIds);
|
||||
const res = await jmapClient.request(
|
||||
[['CalendarEvent/query', { accountId, limit: 1000 }, '0']],
|
||||
[['CalendarEvent/query', args, '0']],
|
||||
USING,
|
||||
);
|
||||
return methodResult<{ ids: string[] }>(res).ids ?? [];
|
||||
}
|
||||
|
||||
export async function getEvents(ids: string[]): Promise<CalendarEvent[]> {
|
||||
export async function getEvents(ids: string[], accountId?: string): Promise<CalendarEvent[]> {
|
||||
if (ids.length === 0) return [];
|
||||
const accountId = jmapClient.accountId;
|
||||
const account = accountId || jmapClient.accountId;
|
||||
const timeZone = getUserTimeZone();
|
||||
const batchSize = jmapClient.getMaxObjectsInGet();
|
||||
const all: CalendarEvent[] = [];
|
||||
for (let i = 0; i < ids.length; i += batchSize) {
|
||||
const batch = ids.slice(i, i + batchSize);
|
||||
const res = await jmapClient.request(
|
||||
[['CalendarEvent/get', {
|
||||
accountId,
|
||||
accountId: account,
|
||||
ids: batch,
|
||||
properties: CALENDAR_EVENT_PROPERTIES,
|
||||
...(timeZone ? { timeZone } : {}),
|
||||
}, '0']],
|
||||
USING,
|
||||
);
|
||||
const list = methodResult<{ list: CalendarEvent[] }>(res).list ?? [];
|
||||
all.push(...list);
|
||||
all.push(...list.map(normalizeRecurrenceProperties));
|
||||
}
|
||||
return all;
|
||||
}
|
||||
@@ -91,13 +249,14 @@ export async function createEvent(
|
||||
event: Partial<CalendarEvent>,
|
||||
calendarId: string,
|
||||
sendSchedulingMessages?: boolean,
|
||||
targetAccountId?: string,
|
||||
): Promise<CalendarEvent> {
|
||||
const accountId = jmapClient.accountId;
|
||||
const accountId = targetAccountId || jmapClient.accountId;
|
||||
const payload: Record<string, unknown> = { ...event, calendarIds: { [calendarId]: true } };
|
||||
cleanRecurrenceRules(payload);
|
||||
const res = await jmapClient.request(
|
||||
[['CalendarEvent/set', setArgs(accountId, {
|
||||
create: {
|
||||
'new-event': { ...event, calendarIds: { [calendarId]: true } },
|
||||
},
|
||||
create: { 'new-event': payload },
|
||||
}, sendSchedulingMessages), '0']],
|
||||
USING,
|
||||
);
|
||||
@@ -110,19 +269,24 @@ export async function createEvent(
|
||||
const err = result.notCreated?.['new-event'];
|
||||
throw new Error(err?.description || err?.type || 'Failed to create event');
|
||||
}
|
||||
return created;
|
||||
// The /set response echoes only server-set properties; merge them over the
|
||||
// submitted payload so the store's optimistic insert keeps recurrence data.
|
||||
return normalizeRecurrenceProperties({ ...payload, ...created } as CalendarEvent);
|
||||
}
|
||||
|
||||
// Batch-create many events in one CalendarEvent/set. Returns the number created.
|
||||
export async function batchCreateEvents(
|
||||
events: Partial<CalendarEvent>[],
|
||||
calendarId: string,
|
||||
targetAccountId?: string,
|
||||
): Promise<number> {
|
||||
if (events.length === 0) return 0;
|
||||
const accountId = jmapClient.accountId;
|
||||
const accountId = targetAccountId || jmapClient.accountId;
|
||||
const create: Record<string, Partial<CalendarEvent>> = {};
|
||||
events.forEach((e, i) => {
|
||||
create[`evt-${i}`] = { ...e, calendarIds: { [calendarId]: true } };
|
||||
const payload: Record<string, unknown> = { ...e, calendarIds: { [calendarId]: true } };
|
||||
cleanRecurrenceRules(payload);
|
||||
create[`evt-${i}`] = payload as Partial<CalendarEvent>;
|
||||
});
|
||||
const res = await jmapClient.request(
|
||||
[['CalendarEvent/set', { accountId, create }, '0']],
|
||||
@@ -136,10 +300,13 @@ export async function updateEvent(
|
||||
id: string,
|
||||
changes: Partial<CalendarEvent> | Record<string, unknown>,
|
||||
sendSchedulingMessages?: boolean,
|
||||
targetAccountId?: string,
|
||||
): Promise<void> {
|
||||
const accountId = jmapClient.accountId;
|
||||
const accountId = targetAccountId || jmapClient.accountId;
|
||||
const patch: Record<string, unknown> = { ...changes };
|
||||
cleanRecurrenceRules(patch);
|
||||
const res = await jmapClient.request(
|
||||
[['CalendarEvent/set', setArgs(accountId, { update: { [id]: changes } }, sendSchedulingMessages), '0']],
|
||||
[['CalendarEvent/set', setArgs(accountId, { update: { [id]: patch } }, sendSchedulingMessages), '0']],
|
||||
USING,
|
||||
);
|
||||
const result = methodResult<{ notUpdated?: Record<string, { description?: string; type?: string }> }>(res);
|
||||
@@ -150,8 +317,9 @@ export async function updateEvent(
|
||||
export async function deleteEvents(
|
||||
ids: string[],
|
||||
sendSchedulingMessages?: boolean,
|
||||
targetAccountId?: string,
|
||||
): Promise<void> {
|
||||
const accountId = jmapClient.accountId;
|
||||
const accountId = targetAccountId || jmapClient.accountId;
|
||||
await jmapClient.request(
|
||||
[['CalendarEvent/set', setArgs(accountId, { destroy: ids }, sendSchedulingMessages), '0']],
|
||||
USING,
|
||||
@@ -165,8 +333,9 @@ export async function rsvpEvent(
|
||||
participantId: string,
|
||||
status: 'accepted' | 'declined' | 'tentative',
|
||||
replyTo?: Record<string, string> | null,
|
||||
targetAccountId?: string,
|
||||
): Promise<void> {
|
||||
const accountId = jmapClient.accountId;
|
||||
const accountId = targetAccountId || jmapClient.accountId;
|
||||
// Escape per RFC 6901: ~ → ~0, / → ~1.
|
||||
const escaped = participantId.replace(/~/g, '~0').replace(/\//g, '~1');
|
||||
const patch: Record<string, unknown> = {
|
||||
@@ -198,7 +367,8 @@ export async function parseCalendarBlob(blobId: string): Promise<Partial<Calenda
|
||||
if (result.notFound?.includes(blobId)) throw new Error('Uploaded file not found');
|
||||
const parsed = result.parsed?.[blobId];
|
||||
if (!parsed) return [];
|
||||
return Array.isArray(parsed) ? parsed : [parsed];
|
||||
const list = Array.isArray(parsed) ? parsed : [parsed];
|
||||
return list.map(normalizeRecurrenceProperties);
|
||||
}
|
||||
|
||||
export async function createCalendar(
|
||||
@@ -225,6 +395,23 @@ export async function createCalendar(
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a calendar as the account default. `isDefault` is read-only in
|
||||
* Stalwart's Calendar/set — the default is changed via the
|
||||
* `onSuccessSetIsDefault` request argument instead.
|
||||
*/
|
||||
export async function setDefaultCalendar(
|
||||
calendarId: string,
|
||||
targetAccountId?: string,
|
||||
): Promise<void> {
|
||||
const accountId = targetAccountId || jmapClient.accountId;
|
||||
const res = await jmapClient.request(
|
||||
[['Calendar/set', { accountId, onSuccessSetIsDefault: calendarId }, '0']],
|
||||
USING,
|
||||
);
|
||||
methodResult(res);
|
||||
}
|
||||
|
||||
// Destroy a calendar. `onDestroyEvents: 'destroy'` removes its events too —
|
||||
// Stalwart otherwise refuses to delete a non-empty calendar.
|
||||
export async function deleteCalendar(id: string): Promise<void> {
|
||||
|
||||
+220
-131
@@ -1,188 +1,277 @@
|
||||
import { jmapClient } from './jmap-client';
|
||||
import { CAPABILITIES } from './types';
|
||||
import type { FileNode } from './types';
|
||||
import { getDownloadUrl, uploadBlob, uploadBytes } from './blob';
|
||||
import type { FileNode, FileNodeRights, Principal } from './types';
|
||||
import { getDownloadUrl, uploadBlob } from './blob';
|
||||
|
||||
const USING = [CAPABILITIES.CORE, CAPABILITIES.FILES];
|
||||
|
||||
// Stalwart and other JMAP servers use one of these strings on FileNode.type to
|
||||
// mark a directory; everything else is a MIME type.
|
||||
const DIRECTORY_TYPES = new Set([
|
||||
'd',
|
||||
'application/x-directory',
|
||||
'text/directory',
|
||||
'httpd/unix-directory',
|
||||
'inode/directory',
|
||||
]);
|
||||
|
||||
export function isDirectory(node: Pick<FileNode, 'type'>): boolean {
|
||||
const t = node.type;
|
||||
if (!t) return false;
|
||||
return DIRECTORY_TYPES.has(t) || t.includes('directory');
|
||||
// A FileNode is a folder (container) only when it has no blob content — the
|
||||
// server stores it with `file == null`. Sending a blobId/type/size on create
|
||||
// (as older builds did: type 'd' + an empty blob) makes a 0-byte FILE that
|
||||
// nothing can ever be parented under (#379). The webmail migrates those
|
||||
// legacy flat-named nodes into the real parentId hierarchy on load; this app
|
||||
// reads and writes only the real hierarchy.
|
||||
export function isFolder(node: Pick<FileNode, 'blobId'>): boolean {
|
||||
return node.blobId == null;
|
||||
}
|
||||
|
||||
// Stalwart rejects `/` in FileNode names, so the webmail (and now this app)
|
||||
// uses U+2215 DIVISION SLASH as the path separator inside the flat `name`
|
||||
// field. Hierarchy is encoded into the name — there is no `parentId` nesting.
|
||||
// e.g. a file inside the `Documents` folder is stored with
|
||||
// `name = "Documents∕report.pdf"`. The display name shown to the user
|
||||
// strips the prefix.
|
||||
export const PATH_SEP = '∕';
|
||||
// Stalwart omits shareWith/myRights from FileNode/get unless they are
|
||||
// requested explicitly, so the share sheet and indicators must name them here.
|
||||
const FILE_NODE_PROPERTIES = [
|
||||
'id', 'parentId', 'name', 'type', 'blobId', 'size', 'created', 'updated',
|
||||
'shareWith', 'myRights',
|
||||
];
|
||||
|
||||
// Path is a list of folder display names from root. [] is root,
|
||||
// ['Documents'] is inside Documents, ['Documents','sub'] is inside the
|
||||
// `sub` folder under Documents.
|
||||
export function pathToPrefix(path: readonly string[]): string {
|
||||
if (path.length === 0) return '';
|
||||
return path.join(PATH_SEP) + PATH_SEP;
|
||||
export function supportsSharing(): boolean {
|
||||
return jmapClient.hasCapability(CAPABILITIES.PRINCIPALS);
|
||||
}
|
||||
|
||||
// True when `node` is a direct child (not a descendant) of `prefix`.
|
||||
export function isDirectChildOfPrefix(node: Pick<FileNode, 'name'>, prefix: string): boolean {
|
||||
if (!node.name) return false;
|
||||
if (prefix === '') return !node.name.includes(PATH_SEP);
|
||||
if (!node.name.startsWith(prefix)) return false;
|
||||
const rest = node.name.slice(prefix.length);
|
||||
return rest.length > 0 && !rest.includes(PATH_SEP);
|
||||
function filesAccountId(): string {
|
||||
return (
|
||||
jmapClient.currentSession?.primaryAccounts?.[CAPABILITIES.FILES] ??
|
||||
jmapClient.accountId
|
||||
);
|
||||
}
|
||||
|
||||
export function nodeDisplayName(node: Pick<FileNode, 'name'>, prefix: string): string {
|
||||
return prefix && node.name.startsWith(prefix) ? node.name.slice(prefix.length) : node.name;
|
||||
function fileUsing(): string[] {
|
||||
const using: string[] = [CAPABILITIES.CORE];
|
||||
if (jmapClient.hasCapability(CAPABILITIES.FILES)) {
|
||||
using.push(CAPABILITIES.FILES);
|
||||
}
|
||||
// Required for shareWith/myRights on FileNode and for cross-account
|
||||
// (shared-with-me) FileNode/get.
|
||||
if (supportsSharing()) {
|
||||
using.push(CAPABILITIES.PRINCIPALS_OWNER);
|
||||
}
|
||||
return using;
|
||||
}
|
||||
|
||||
// Stalwart's FileNode/get does not support a parentId filter and some builds
|
||||
// omit `type` from the default property set. We fetch the whole tree and
|
||||
// filter client-side; properties are listed explicitly so `isDirectory()`
|
||||
// always has a value to look at.
|
||||
const FILE_NODE_PROPERTIES = ['id', 'parentId', 'name', 'type', 'blobId', 'size', 'created', 'updated'];
|
||||
// Nodes fetched from another principal's account are namespaced
|
||||
// "accountId:nodeId" so they can't collide with the primary account's ids.
|
||||
// JMAP ids never contain ':', so the separator unambiguously marks a shared
|
||||
// (cross-account) node.
|
||||
export function isCrossAccountId(id: string | null | undefined): boolean {
|
||||
return id != null && id.includes(':');
|
||||
}
|
||||
|
||||
// Fetch every FileNode in the account, files AND folders, to build the
|
||||
// hierarchy client-side from parentId links.
|
||||
//
|
||||
// IMPORTANT: this uses FileNode/get with ids:null (return-all), NOT
|
||||
// FileNode/query — Stalwart's query only returns leaf files and omits folder
|
||||
// nodes entirely, which would make every folder invisible.
|
||||
export async function getAllFileNodes(): Promise<FileNode[]> {
|
||||
const accountId = jmapClient.accountId;
|
||||
const accountId = filesAccountId();
|
||||
const res = await jmapClient.request(
|
||||
[['FileNode/get', { accountId, ids: null, properties: FILE_NODE_PROPERTIES }, '0']],
|
||||
USING,
|
||||
fileUsing(),
|
||||
);
|
||||
return (res.methodResponses[0][1].list ?? []) as FileNode[];
|
||||
const result = res.methodResponses[0];
|
||||
if (!result || result[0] === 'error') {
|
||||
throw new Error(result?.[1]?.description || 'FileNode list failed');
|
||||
}
|
||||
return (result[1].list ?? []) as FileNode[];
|
||||
}
|
||||
|
||||
export async function createFileNode(
|
||||
fileNode: Partial<FileNode>,
|
||||
): Promise<FileNode> {
|
||||
const accountId = jmapClient.accountId;
|
||||
const res = await jmapClient.request(
|
||||
[['FileNode/set', {
|
||||
accountId,
|
||||
create: { 'new-file': fileNode },
|
||||
}, '0']],
|
||||
USING,
|
||||
);
|
||||
const created = res.methodResponses[0][1].created?.['new-file'];
|
||||
if (!created) {
|
||||
const err = res.methodResponses[0][1].notCreated?.['new-file'];
|
||||
throw new Error(err?.description || 'Create failed');
|
||||
// Accounts (primary + shared/group) that can hold FileNodes: any non-primary
|
||||
// account that advertises the filenode capability or is non-personal, since
|
||||
// Stalwart doesn't always advertise capabilities on shared accounts.
|
||||
function filesCapableAccountIds(): string[] {
|
||||
const primaryId = filesAccountId();
|
||||
const accounts = jmapClient.currentSession?.accounts ?? {};
|
||||
const rest = Object.entries(accounts)
|
||||
.filter(([id, info]) =>
|
||||
id !== primaryId &&
|
||||
(info.accountCapabilities?.[CAPABILITIES.FILES] != null || !info.isPersonal))
|
||||
.map(([id]) => id);
|
||||
return [primaryId, ...rest];
|
||||
}
|
||||
|
||||
// Fetch every FileNode the logged-in user can see across all accessible
|
||||
// accounts. Nodes owned by another principal (shared with the user) are
|
||||
// tagged `isShared: true` with the owning accountId/accountName, and their
|
||||
// ids/parentIds are namespaced "accountId:nodeId". Mirrors the webmail's
|
||||
// listAllFileNodesAcrossAccounts.
|
||||
export async function getAllFileNodesAcrossAccounts(): Promise<FileNode[]> {
|
||||
const primaryId = filesAccountId();
|
||||
const accounts = jmapClient.currentSession?.accounts ?? {};
|
||||
const all: FileNode[] = [];
|
||||
|
||||
for (const accountId of filesCapableAccountIds()) {
|
||||
const isPrimary = accountId === primaryId;
|
||||
try {
|
||||
const res = await jmapClient.request(
|
||||
[['FileNode/get', { accountId, ids: null, properties: FILE_NODE_PROPERTIES }, '0']],
|
||||
fileUsing(),
|
||||
);
|
||||
const result = res.methodResponses[0];
|
||||
if (!result || result[0] === 'error') continue;
|
||||
for (const node of (result[1].list ?? []) as FileNode[]) {
|
||||
all.push({
|
||||
...node,
|
||||
id: isPrimary ? node.id : `${accountId}:${node.id}`,
|
||||
parentId: node.parentId == null
|
||||
? null
|
||||
: (isPrimary ? node.parentId : `${accountId}:${node.parentId}`),
|
||||
accountId,
|
||||
accountName: accounts[accountId]?.name || accountId,
|
||||
isShared: !isPrimary,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// A single unreachable shared account shouldn't hide the user's own
|
||||
// files; skip it and keep aggregating.
|
||||
}
|
||||
}
|
||||
return created;
|
||||
|
||||
return all;
|
||||
}
|
||||
|
||||
export async function createFolder(
|
||||
displayName: string,
|
||||
currentPath: readonly string[],
|
||||
name: string,
|
||||
parentId: string | null,
|
||||
): Promise<FileNode> {
|
||||
// Stalwart's FileNode/set rejects directory creates without a blobId
|
||||
// ("Missing blob id"), so we upload an empty blob first and reference it.
|
||||
// Mirrors the webmail's createFileDirectory.
|
||||
const blob = await uploadBytes(new Uint8Array(0), 'application/x-directory');
|
||||
const fullName = pathToPrefix(currentPath) + displayName;
|
||||
return createFileNode({ name: fullName, type: 'd', blobId: blob.blobId, size: 0 });
|
||||
const accountId = filesAccountId();
|
||||
const props: Record<string, unknown> = { name };
|
||||
if (parentId !== null) props.parentId = parentId;
|
||||
|
||||
const res = await jmapClient.request(
|
||||
[['FileNode/set', { accountId, create: { 'new-dir': props } }, '0']],
|
||||
fileUsing(),
|
||||
);
|
||||
const result = res.methodResponses[0][1];
|
||||
const created = result.created?.['new-dir'];
|
||||
if (!created) {
|
||||
const err = result.notCreated?.['new-dir'];
|
||||
throw new Error(err?.description || 'Create folder failed');
|
||||
}
|
||||
return { ...props, ...created } as FileNode;
|
||||
}
|
||||
|
||||
export async function updateFileNode(
|
||||
id: string,
|
||||
updates: Partial<Pick<FileNode, 'name' | 'parentId'>>,
|
||||
): Promise<void> {
|
||||
const accountId = jmapClient.accountId;
|
||||
const accountId = filesAccountId();
|
||||
const res = await jmapClient.request(
|
||||
[['FileNode/set', { accountId, update: { [id]: updates } }, '0']],
|
||||
USING,
|
||||
fileUsing(),
|
||||
);
|
||||
const notUpdated = res.methodResponses[0][1].notUpdated?.[id];
|
||||
if (notUpdated) throw new Error(notUpdated.description || 'Update failed');
|
||||
}
|
||||
|
||||
// Rename a node and, if it's a folder, cascade the rename to every descendant
|
||||
// so the encoded path stays consistent. The webmail does this same dance.
|
||||
export async function renameFileNode(
|
||||
node: FileNode,
|
||||
newDisplayName: string,
|
||||
currentPath: readonly string[],
|
||||
allNodes: readonly FileNode[],
|
||||
): Promise<void> {
|
||||
const prefix = pathToPrefix(currentPath);
|
||||
const oldServerName = node.name;
|
||||
const newServerName = prefix + newDisplayName;
|
||||
if (oldServerName === newServerName) return;
|
||||
|
||||
await updateFileNode(node.id, { name: newServerName });
|
||||
|
||||
if (isDirectory(node)) {
|
||||
const oldFolderPrefix = oldServerName + PATH_SEP;
|
||||
const newFolderPrefix = newServerName + PATH_SEP;
|
||||
for (const n of allNodes) {
|
||||
if (n.id === node.id) continue;
|
||||
if (n.name.startsWith(oldFolderPrefix)) {
|
||||
await updateFileNode(n.id, { name: newFolderPrefix + n.name.slice(oldFolderPrefix.length) });
|
||||
}
|
||||
}
|
||||
}
|
||||
export async function renameFileNode(id: string, newName: string): Promise<void> {
|
||||
await updateFileNode(id, { name: newName });
|
||||
}
|
||||
|
||||
export async function deleteFileNodes(ids: string[]): Promise<void> {
|
||||
if (ids.length === 0) return;
|
||||
const accountId = jmapClient.accountId;
|
||||
await jmapClient.request(
|
||||
[['FileNode/set', { accountId, destroy: ids }, '0']],
|
||||
USING,
|
||||
const accountId = filesAccountId();
|
||||
const res = await jmapClient.request(
|
||||
[['FileNode/set', {
|
||||
accountId,
|
||||
destroy: ids,
|
||||
// The server removes descendant nodes of destroyed folders.
|
||||
onDestroyRemoveChildren: true,
|
||||
}, '0']],
|
||||
fileUsing(),
|
||||
);
|
||||
}
|
||||
|
||||
// Delete `targets` and every descendant. Stalwart doesn't enforce parent
|
||||
// references, so we collect descendants by name-prefix and destroy them all
|
||||
// in one call. Without this, deleting a folder leaves its files orphaned and
|
||||
// still discoverable at the old encoded path.
|
||||
export async function deleteWithDescendants(
|
||||
targets: readonly FileNode[],
|
||||
allNodes: readonly FileNode[],
|
||||
): Promise<void> {
|
||||
const ids = new Set<string>();
|
||||
for (const node of targets) {
|
||||
ids.add(node.id);
|
||||
if (isDirectory(node)) {
|
||||
const folderPrefix = node.name + PATH_SEP;
|
||||
for (const n of allNodes) {
|
||||
if (n.name.startsWith(folderPrefix)) ids.add(n.id);
|
||||
}
|
||||
}
|
||||
const notDestroyed = res.methodResponses[0][1].notDestroyed as
|
||||
| Record<string, { description?: string }>
|
||||
| undefined;
|
||||
const failedIds = Object.keys(notDestroyed ?? {});
|
||||
if (failedIds.length > 0) {
|
||||
throw new Error(
|
||||
notDestroyed![failedIds[0]]?.description || `Failed to delete ${failedIds.length} item(s)`,
|
||||
);
|
||||
}
|
||||
await deleteFileNodes(Array.from(ids));
|
||||
}
|
||||
|
||||
export function getFileNodeDownloadUrl(node: FileNode): string {
|
||||
if (!node.blobId) throw new Error('Folders cannot be downloaded');
|
||||
return getDownloadUrl(node.blobId, node.name, node.type);
|
||||
return getDownloadUrl(node.blobId, node.name, node.type, node.accountId);
|
||||
}
|
||||
|
||||
export async function uploadFileNode(
|
||||
uri: string,
|
||||
displayName: string,
|
||||
name: string,
|
||||
mimeType: string,
|
||||
currentPath: readonly string[],
|
||||
parentId: string | null,
|
||||
): Promise<FileNode> {
|
||||
const accountId = filesAccountId();
|
||||
const blob = await uploadBlob(uri, mimeType);
|
||||
const fullName = pathToPrefix(currentPath) + displayName;
|
||||
return createFileNode({
|
||||
name: fullName,
|
||||
type: blob.type || mimeType || 'application/octet-stream',
|
||||
const type = blob.type || mimeType || 'application/octet-stream';
|
||||
const props: Record<string, unknown> = {
|
||||
name,
|
||||
// Stalwart caps the stored MIME type; very long types fail the create.
|
||||
type: type.length > 30 ? 'application/octet-stream' : type,
|
||||
blobId: blob.blobId,
|
||||
size: blob.size,
|
||||
});
|
||||
};
|
||||
if (parentId !== null) props.parentId = parentId;
|
||||
|
||||
const res = await jmapClient.request(
|
||||
[['FileNode/set', { accountId, create: { 'new-file': props } }, '0']],
|
||||
fileUsing(),
|
||||
);
|
||||
const result = res.methodResponses[0][1];
|
||||
const created = result.created?.['new-file'];
|
||||
if (!created) {
|
||||
const err = result.notCreated?.['new-file'];
|
||||
throw new Error(err?.description || 'Upload failed');
|
||||
}
|
||||
return { ...props, ...created } as FileNode;
|
||||
}
|
||||
|
||||
// ── Sharing (RFC 9670) ────────────────────────────────────
|
||||
|
||||
// Add, update, or remove a principal's rights on an owned FileNode (file or
|
||||
// folder). Pass rights: null to revoke. Stalwart applies it via a
|
||||
// `shareWith/{principalId}` patch on FileNode/set. Sharing a folder shares
|
||||
// its whole subtree — which is why this app must store real parentId
|
||||
// hierarchy rather than the legacy flat-name encoding.
|
||||
export async function setFileNodeShare(
|
||||
fileNodeId: string,
|
||||
principalId: string,
|
||||
rights: FileNodeRights | null,
|
||||
): Promise<void> {
|
||||
const accountId = filesAccountId();
|
||||
const res = await jmapClient.request(
|
||||
[['FileNode/set', {
|
||||
accountId,
|
||||
update: { [fileNodeId]: { [`shareWith/${principalId}`]: rights } },
|
||||
}, '0']],
|
||||
fileUsing(),
|
||||
);
|
||||
const result = res.methodResponses[0][1];
|
||||
if (result.notUpdated?.[fileNodeId]) {
|
||||
throw new Error(result.notUpdated[fileNodeId].description || 'Failed to update file share');
|
||||
}
|
||||
if (!result.updated || !(fileNodeId in result.updated)) {
|
||||
throw new Error('Server did not confirm the share update');
|
||||
}
|
||||
}
|
||||
|
||||
// List all principals visible to the user. Stalwart returns the full
|
||||
// directory regardless of `filter`, so callers filter client-side.
|
||||
export async function getPrincipals(): Promise<Principal[]> {
|
||||
if (!supportsSharing()) return [];
|
||||
const accountId = jmapClient.accountId;
|
||||
const res = await jmapClient.request(
|
||||
[
|
||||
['Principal/query', { accountId }, '0'],
|
||||
['Principal/get', {
|
||||
accountId,
|
||||
'#ids': { resultOf: '0', name: 'Principal/query', path: '/ids' },
|
||||
}, '1'],
|
||||
],
|
||||
[CAPABILITIES.CORE, CAPABILITIES.PRINCIPALS],
|
||||
);
|
||||
const getResp = res.methodResponses.find((r) => r[0] === 'Principal/get');
|
||||
return (getResp?.[1].list ?? []) as Principal[];
|
||||
}
|
||||
|
||||
// The principal id that represents the logged-in user (excluded from the
|
||||
// share picker — sharing with yourself is a no-op the server may reject).
|
||||
export function ownPrincipalId(): string {
|
||||
return filesAccountId();
|
||||
}
|
||||
|
||||
@@ -151,6 +151,7 @@ export class JMAPClient {
|
||||
|
||||
private async persistRefreshedTokens(next: OAuthTokens): Promise<void> {
|
||||
if (!this.credentials) return;
|
||||
if (this.credentials.accessToken === next.accessToken) return;
|
||||
this.credentials = {
|
||||
...this.credentials,
|
||||
accessToken: next.accessToken,
|
||||
|
||||
@@ -405,6 +405,7 @@ export interface VirtualLocation {
|
||||
}
|
||||
|
||||
export interface RecurrenceRule {
|
||||
'@type'?: 'RecurrenceRule';
|
||||
frequency: string;
|
||||
interval?: number;
|
||||
until?: string;
|
||||
@@ -419,6 +420,8 @@ export interface RecurrenceRule {
|
||||
bySecond?: number[];
|
||||
bySetPosition?: number[];
|
||||
firstDayOfWeek?: string;
|
||||
rscale?: string;
|
||||
skip?: string;
|
||||
}
|
||||
|
||||
export interface Alert {
|
||||
@@ -452,6 +455,9 @@ export interface CalendarEvent {
|
||||
excludedRecurrenceRules?: RecurrenceRule[];
|
||||
recurrenceId?: string;
|
||||
originalId?: string;
|
||||
// Client-only: the event's server-side calendarIds (raw, unprefixed), kept
|
||||
// when `calendarIds` is remapped to namespaced store ids for shared events.
|
||||
originalCalendarIds?: Record<string, boolean>;
|
||||
useDefaultAlerts?: boolean;
|
||||
alerts?: Record<string, Alert>;
|
||||
locations?: Record<string, EventLocation>;
|
||||
@@ -467,6 +473,12 @@ export interface CalendarEvent {
|
||||
color?: string;
|
||||
// Client-only: account the event/occurrence belongs to (for shared/virtual).
|
||||
localAccountId?: string;
|
||||
// Client-only: JMAP account the event was fetched from. Absent for the
|
||||
// primary account; set for events on calendars shared with the user so
|
||||
// mutations can be routed to the owning account.
|
||||
accountId?: string;
|
||||
// Client-only: true when the event lives on a calendar shared with the user.
|
||||
isShared?: boolean;
|
||||
}
|
||||
|
||||
export interface CalendarRights {
|
||||
@@ -492,6 +504,21 @@ export interface Calendar {
|
||||
isDefault?: boolean;
|
||||
sortOrder?: number;
|
||||
myRights?: CalendarRights;
|
||||
// Client-only: JMAP account the calendar was fetched from. Absent for the
|
||||
// primary account; set for calendars shared with the user.
|
||||
accountId?: string;
|
||||
// Client-only: the real JMAP id of a shared calendar, before its `id` was
|
||||
// namespaced as `${accountId}:${id}` to stay unique in the store. Mutations
|
||||
// and event queries must use this raw id against the owning account.
|
||||
originalId?: string;
|
||||
// Client-only: true when the calendar lives in another account (shared
|
||||
// with the user by its owner).
|
||||
isShared?: boolean;
|
||||
// Client-only: set when `color` has been replaced by the viewer's local
|
||||
// override for a shared calendar (see lib/calendar-utils). When true, the
|
||||
// override wins over per-event colors so the whole shared calendar paints
|
||||
// uniformly.
|
||||
colorIsLocalOverride?: boolean;
|
||||
}
|
||||
|
||||
// ─── Files (FileNode) ───────────────────────────────────
|
||||
@@ -505,6 +532,40 @@ export interface FileNode {
|
||||
size?: number;
|
||||
created?: string;
|
||||
updated?: string;
|
||||
// JMAP Sharing (RFC 9670). Populated only when the server advertises the
|
||||
// principals capability and the properties are requested explicitly. A node
|
||||
// is shared-out when `shareWith` has entries; `myRights` describes what the
|
||||
// viewer may do (always full rights on owned nodes).
|
||||
myRights?: FileNodeRights;
|
||||
shareWith?: Record<string, FileNodeRights> | null;
|
||||
// True when this node was fetched from another principal's account that was
|
||||
// shared with the logged-in user ("Shared with me").
|
||||
isShared?: boolean;
|
||||
// Owning account's JMAP id and display name, set when aggregating nodes
|
||||
// across accounts so blob downloads route to the right account.
|
||||
accountId?: string;
|
||||
accountName?: string;
|
||||
}
|
||||
|
||||
// FileNode rights as defined by Stalwart's JmapSharedObject implementation.
|
||||
export interface FileNodeRights {
|
||||
mayRead: boolean;
|
||||
mayAddChildren: boolean;
|
||||
mayRename: boolean;
|
||||
mayDelete: boolean;
|
||||
mayModifyContent: boolean;
|
||||
mayShare: boolean;
|
||||
}
|
||||
|
||||
// RFC 9670 principal — an entity (user, group, resource) that files and
|
||||
// calendars can be shared with. On Stalwart the principal id doubles as the
|
||||
// account id of that user/group.
|
||||
export interface Principal {
|
||||
id: string;
|
||||
type: 'individual' | 'group' | 'resource' | 'location' | 'other';
|
||||
name: string;
|
||||
description?: string | null;
|
||||
email?: string | null;
|
||||
}
|
||||
|
||||
// ─── Push / SSE ─────────────────────────────────────────
|
||||
@@ -538,4 +599,6 @@ export const CAPABILITIES = {
|
||||
SIEVE: 'urn:ietf:params:jmap:sieve',
|
||||
QUOTA: 'urn:ietf:params:jmap:quota',
|
||||
FILES: 'urn:ietf:params:jmap:filenode',
|
||||
PRINCIPALS: 'urn:ietf:params:jmap:principals',
|
||||
PRINCIPALS_OWNER: 'urn:ietf:params:jmap:principals:owner',
|
||||
} as const;
|
||||
|
||||
@@ -101,7 +101,10 @@ async function ensureFreshCredentials(
|
||||
tokenEndpoint: next.tokenEndpoint,
|
||||
clientId: next.clientId,
|
||||
};
|
||||
await jmapClient.setStoredCredentials(accountId, updated);
|
||||
const current = await jmapClient.getStoredCredentials(accountId);
|
||||
if (!current || current.accessToken !== updated.accessToken) {
|
||||
await jmapClient.setStoredCredentials(accountId, updated);
|
||||
}
|
||||
return updated;
|
||||
} catch {
|
||||
// Fall back to the existing (possibly expired) token; the request will
|
||||
|
||||
@@ -27,6 +27,15 @@ function arrayBufferToBase64(buffer: ArrayBuffer): string {
|
||||
interface EmailBodyViewProps {
|
||||
email: Email;
|
||||
senderEmail?: string;
|
||||
// The body is a native WebView, which on Android swallows horizontal touches
|
||||
// before the surrounding pager can see them. We detect a clear horizontal
|
||||
// swipe inside the page and report it here so the pager can change messages.
|
||||
onSwipe?: (direction: 'prev' | 'next') => void;
|
||||
// Pinch-zoom state from inside the page: `pinching` while two fingers are
|
||||
// down, `zoomed` while the content is scaled in. The hosts use it to freeze
|
||||
// the surrounding vertical scroll / horizontal pager so a zoom gesture can't
|
||||
// scroll the pane away or switch mails.
|
||||
onZoomChange?: (zoom: { pinching: boolean; zoomed: boolean }) => void;
|
||||
}
|
||||
|
||||
function extractHtmlBody(email: Email): string | null {
|
||||
@@ -177,6 +186,30 @@ const HEIGHT_REPORTER = `
|
||||
var padR = parseFloat(cs.paddingRight) || 0;
|
||||
return b.clientWidth - padL - padR;
|
||||
}
|
||||
// Shared zoom state, mutated by the pinch-zoom handler injected after this
|
||||
// script. "fit" is the shrink-to-fit scale, "scale" the user's pinch factor
|
||||
// on top of it, "tx" pans the zoomed overflow into view horizontally.
|
||||
// Vertical panning needs no state here: the height reports below carry the
|
||||
// scaled height, so the surrounding native ScrollView grows and scrolls.
|
||||
var Z = window.__rnZoom = window.__rnZoom || {
|
||||
scale: 1, tx: 0, pinching: false, fit: 1, layoutW: 0, avail: 0,
|
||||
};
|
||||
// Apply the combined fit × pinch transform using the cached layout numbers
|
||||
// (cheap — no reflow), clamping the pan so content edges pin to the viewport.
|
||||
function applyTransform(w) {
|
||||
var s = Z.fit * Z.scale;
|
||||
if (Z.scale > 1.001 || Z.fit < 0.999) {
|
||||
var minTx = Math.min(0, Z.avail - Z.layoutW * s);
|
||||
if (Z.tx < minTx) Z.tx = minTx;
|
||||
if (Z.tx > 0) Z.tx = 0;
|
||||
w.style.width = Z.layoutW + 'px';
|
||||
w.style.transform = 'translateX(' + Z.tx + 'px) scale(' + s + ')';
|
||||
} else {
|
||||
Z.tx = 0;
|
||||
w.style.width = '100%';
|
||||
w.style.transform = 'none';
|
||||
}
|
||||
}
|
||||
// Shrink-to-fit: emails authored at a fixed width (e.g. 600px tables) overflow
|
||||
// a phone viewport and force horizontal scrolling. Lay the content out at its
|
||||
// natural width, then scale the whole block down so its widest element fits
|
||||
@@ -189,18 +222,18 @@ const HEIGHT_REPORTER = `
|
||||
// (the widest unbreakable element) rather than a previously-scaled box.
|
||||
w.style.width = '100%';
|
||||
var content = w.scrollWidth;
|
||||
if (content > avail + 1) {
|
||||
var scale = avail / content;
|
||||
w.style.width = content + 'px';
|
||||
w.style.transform = 'scale(' + scale + ')';
|
||||
} else {
|
||||
w.style.transform = 'none';
|
||||
}
|
||||
Z.avail = avail;
|
||||
Z.layoutW = content > avail + 1 ? content : avail;
|
||||
Z.fit = avail / Z.layoutW;
|
||||
applyTransform(w);
|
||||
}
|
||||
function measure() {
|
||||
var w = ensureWrapper();
|
||||
if (!w) return 0;
|
||||
fitToWidth(w);
|
||||
// While a pinch is in flight only re-apply the transform — a full re-fit
|
||||
// resets the wrapper width and would thrash layout on every frame.
|
||||
if (Z.pinching) applyTransform(w);
|
||||
else fitToWidth(w);
|
||||
// getBoundingClientRect reflects the applied transform, so r.height is the
|
||||
// already-scaled visual height of the content.
|
||||
var r = w.getBoundingClientRect();
|
||||
@@ -270,11 +303,161 @@ const HEIGHT_REPORTER = `
|
||||
img.addEventListener('error', report);
|
||||
});
|
||||
} catch (e) {}
|
||||
// Hooks for the pinch-zoom handler script.
|
||||
window.__rnApplyZoom = function () { var w = ensureWrapper(); if (w) applyTransform(w); };
|
||||
window.__rnReport = report;
|
||||
true;
|
||||
})();
|
||||
`;
|
||||
|
||||
export default function EmailBodyView({ email, senderEmail }: EmailBodyViewProps) {
|
||||
// Detect a clear horizontal flick inside the WebView and report it. Uses
|
||||
// capture-phase, passive listeners so it never blocks vertical scrolling, text
|
||||
// selection, or link taps — it only reacts to a quick, horizontal-dominant
|
||||
// gesture on release. Guarded so re-injection (onLoadEnd) is a no-op.
|
||||
const SWIPE_DETECTOR = `
|
||||
(function () {
|
||||
if (window.__rnSwipeInit) return;
|
||||
window.__rnSwipeInit = true;
|
||||
var x0 = 0, y0 = 0, t0 = 0, tracking = false;
|
||||
document.addEventListener('touchstart', function (e) {
|
||||
if (e.touches.length !== 1) { tracking = false; return; }
|
||||
var t = e.touches[0];
|
||||
x0 = t.clientX; y0 = t.clientY; t0 = Date.now(); tracking = true;
|
||||
}, { passive: true, capture: true });
|
||||
document.addEventListener('touchend', function (e) {
|
||||
if (!tracking) return;
|
||||
tracking = false;
|
||||
// While the content is pinch-zoomed, horizontal flicks pan the zoomed
|
||||
// content — never switch mails.
|
||||
if (window.__rnZoom && (window.__rnZoom.pinching || window.__rnZoom.scale > 1.001)) return;
|
||||
var t = e.changedTouches[0];
|
||||
if (!t) return;
|
||||
var dx = t.clientX - x0, dy = t.clientY - y0, dt = Date.now() - t0;
|
||||
if (dt < 700 && Math.abs(dx) > 55 && Math.abs(dx) > Math.abs(dy) * 1.8) {
|
||||
if (window.ReactNativeWebView) {
|
||||
window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'swipe', dir: dx < 0 ? 'next' : 'prev' }));
|
||||
}
|
||||
}
|
||||
}, { passive: true, capture: true });
|
||||
true;
|
||||
})();
|
||||
`;
|
||||
|
||||
// Pinch zoom + pan for the email content, driven entirely in the page: native
|
||||
// WebView zoom can't work here because the WebView is auto-height inside a
|
||||
// native ScrollView (viewport meta pins it to scale 1). A two-finger pinch
|
||||
// scales the measured wrapper (on top of the shrink-to-fit scale the height
|
||||
// reporter maintains) anchored at the fingers' horizontal midpoint; while
|
||||
// zoomed, one-finger horizontal drags pan via translateX and vertical drags
|
||||
// still scroll the surrounding ScrollView, which sees the scaled height
|
||||
// through the regular height reports. Pinch moves call preventDefault so the
|
||||
// engine consumes the gesture and Android parents don't intercept it; `zoom`
|
||||
// messages let the RN side freeze the pane scroll / pager as a second guard.
|
||||
const PINCH_ZOOM = `
|
||||
(function () {
|
||||
if (window.__rnPinchInit) return;
|
||||
window.__rnPinchInit = true;
|
||||
var Z = window.__rnZoom = window.__rnZoom || {
|
||||
scale: 1, tx: 0, pinching: false, fit: 1, layoutW: 0, avail: 0,
|
||||
};
|
||||
var MAX_ZOOM = 4;
|
||||
var pinch = null; // { d0, s0, cx0, tx0 }
|
||||
var pan = null; // { x0, tx0 }
|
||||
var rafPending = false;
|
||||
|
||||
function post(msg) {
|
||||
if (window.ReactNativeWebView) {
|
||||
window.ReactNativeWebView.postMessage(JSON.stringify(msg));
|
||||
}
|
||||
}
|
||||
function apply() {
|
||||
if (window.__rnApplyZoom) window.__rnApplyZoom();
|
||||
}
|
||||
// Height reports are rAF-throttled during the gesture so the RN container
|
||||
// keeps up with the growing content without re-measuring on every move.
|
||||
function scheduleReport() {
|
||||
if (rafPending) return;
|
||||
rafPending = true;
|
||||
requestAnimationFrame(function () {
|
||||
rafPending = false;
|
||||
if (window.__rnReport) window.__rnReport();
|
||||
});
|
||||
}
|
||||
function dist(t0, t1) {
|
||||
var dx = t1.clientX - t0.clientX, dy = t1.clientY - t0.clientY;
|
||||
return Math.sqrt(dx * dx + dy * dy);
|
||||
}
|
||||
|
||||
document.addEventListener('touchstart', function (e) {
|
||||
if (e.touches.length === 2) {
|
||||
var t0 = e.touches[0], t1 = e.touches[1];
|
||||
pinch = {
|
||||
d0: dist(t0, t1) || 1,
|
||||
s0: Z.scale,
|
||||
cx0: (t0.clientX + t1.clientX) / 2,
|
||||
tx0: Z.tx,
|
||||
};
|
||||
pan = null;
|
||||
if (!Z.pinching) {
|
||||
Z.pinching = true;
|
||||
post({ type: 'zoom', pinching: true, scale: Z.scale });
|
||||
}
|
||||
e.preventDefault();
|
||||
} else if (e.touches.length === 1 && Z.scale > 1.001) {
|
||||
pan = { x0: e.touches[0].clientX, tx0: Z.tx };
|
||||
} else {
|
||||
pan = null;
|
||||
}
|
||||
}, { passive: false, capture: true });
|
||||
|
||||
document.addEventListener('touchmove', function (e) {
|
||||
if (pinch && e.touches.length === 2) {
|
||||
e.preventDefault();
|
||||
var t0 = e.touches[0], t1 = e.touches[1];
|
||||
var z = pinch.s0 * (dist(t0, t1) / pinch.d0);
|
||||
if (z < 1) z = 1;
|
||||
if (z > MAX_ZOOM) z = MAX_ZOOM;
|
||||
// Keep the content under the fingers' midpoint stationary horizontally:
|
||||
// the wrapper-local point that started under cx0 must map back to the
|
||||
// current midpoint at the new scale. (applyTransform clamps the result.)
|
||||
var cx = (t0.clientX + t1.clientX) / 2;
|
||||
var local = (pinch.cx0 - pinch.tx0) / (Z.fit * pinch.s0);
|
||||
Z.scale = z;
|
||||
Z.tx = cx - local * (Z.fit * z);
|
||||
apply();
|
||||
scheduleReport();
|
||||
} else if (pan && e.touches.length === 1 && Z.scale > 1.001) {
|
||||
// No preventDefault: vertical-dominant drags must keep scrolling the
|
||||
// native ScrollView around the WebView. Horizontal-dominant drags stay
|
||||
// inside the WebView and pan here.
|
||||
Z.tx = pan.tx0 + (e.touches[0].clientX - pan.x0);
|
||||
apply();
|
||||
}
|
||||
}, { passive: false, capture: true });
|
||||
|
||||
function onTouchEnd(e) {
|
||||
if (pinch && e.touches.length < 2) {
|
||||
pinch = null;
|
||||
// Snap back to the fitted layout when the pinch ends near scale 1.
|
||||
if (Z.scale < 1.02) { Z.scale = 1; Z.tx = 0; }
|
||||
Z.pinching = false;
|
||||
apply();
|
||||
if (window.__rnReport) window.__rnReport();
|
||||
post({ type: 'zoom', pinching: false, scale: Z.scale });
|
||||
// A finger left on screen continues as a pan.
|
||||
if (e.touches.length === 1 && Z.scale > 1.001) {
|
||||
pan = { x0: e.touches[0].clientX, tx0: Z.tx };
|
||||
}
|
||||
}
|
||||
if (e.touches.length === 0) pan = null;
|
||||
}
|
||||
document.addEventListener('touchend', onTouchEnd, { passive: true, capture: true });
|
||||
document.addEventListener('touchcancel', onTouchEnd, { passive: true, capture: true });
|
||||
true;
|
||||
})();
|
||||
`;
|
||||
|
||||
export default function EmailBodyView({ email, senderEmail, onSwipe, onZoomChange }: EmailBodyViewProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const externalContentPolicy = useSettingsStore((s) => s.externalContentPolicy);
|
||||
@@ -423,12 +606,30 @@ export default function EmailBodyView({ email, senderEmail }: EmailBodyViewProps
|
||||
const applyInversion =
|
||||
!!rawHtml && renderAsDark && !hasNativeDarkMode(rawHtml);
|
||||
const injectedJs = React.useMemo(
|
||||
() => (applyInversion ? DARK_REINVERT_SCRIPT + HEIGHT_REPORTER : HEIGHT_REPORTER),
|
||||
() =>
|
||||
(applyInversion ? DARK_REINVERT_SCRIPT + HEIGHT_REPORTER : HEIGHT_REPORTER)
|
||||
+ SWIPE_DETECTOR + PINCH_ZOOM,
|
||||
[applyInversion],
|
||||
);
|
||||
|
||||
const onMessage = (e: WebViewMessageEvent) => {
|
||||
const parsed = parseInt(e.nativeEvent.data, 10);
|
||||
const data = e.nativeEvent.data;
|
||||
// Swipe/zoom messages arrive as JSON; the height reporter posts a bare number.
|
||||
if (data.charCodeAt(0) === 123 /* '{' */) {
|
||||
try {
|
||||
const msg = JSON.parse(data);
|
||||
if (msg.type === 'swipe' && (msg.dir === 'prev' || msg.dir === 'next')) {
|
||||
onSwipe?.(msg.dir);
|
||||
} else if (msg.type === 'zoom') {
|
||||
onZoomChange?.({
|
||||
pinching: !!msg.pinching,
|
||||
zoomed: typeof msg.scale === 'number' && msg.scale > 1.01,
|
||||
});
|
||||
}
|
||||
} catch { /* ignore malformed */ }
|
||||
return;
|
||||
}
|
||||
const parsed = parseInt(data, 10);
|
||||
if (Number.isNaN(parsed) || parsed <= 0) return;
|
||||
setHeight((prev) => (Math.abs(parsed - prev) < 2 ? prev : parsed));
|
||||
};
|
||||
@@ -473,6 +674,10 @@ export default function EmailBodyView({ email, senderEmail }: EmailBodyViewProps
|
||||
injectedJavaScript={injectedJs}
|
||||
onMessage={onMessage}
|
||||
onLoadEnd={() => {
|
||||
// A (re)load resets the page's zoom state to 1 — drop any host-side
|
||||
// scroll locks so they can't go stale (e.g. cid images arriving
|
||||
// reload the source mid-zoom).
|
||||
onZoomChange?.({ pinching: false, zoomed: false });
|
||||
// Re-inject after load to cover Android cases where
|
||||
// `injectedJavaScript` runs too early to see the final layout. The
|
||||
// re-inversion pass guards itself (__rnDarkInvertDone) so running it
|
||||
@@ -482,6 +687,9 @@ export default function EmailBodyView({ email, senderEmail }: EmailBodyViewProps
|
||||
}, 50);
|
||||
}}
|
||||
scrollEnabled={false}
|
||||
// Native Android zoom would scale the viewport inside the fixed-size
|
||||
// container; pinch zoom is implemented in the page instead.
|
||||
setBuiltInZoomControls={false}
|
||||
showsVerticalScrollIndicator={false}
|
||||
showsHorizontalScrollIndicator={false}
|
||||
setSupportMultipleWindows={false}
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
View, Text, StyleSheet, ScrollView, Pressable, Modal, Animated, Easing,
|
||||
} from 'react-native';
|
||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
import { X, Check, Mail } from 'lucide-react-native';
|
||||
import { spacing, radius, typography, type ThemePalette } from '../theme/tokens';
|
||||
import { useColors } from '../theme/colors';
|
||||
import { useSheetDrag } from '../lib/use-sheet-drag';
|
||||
import type { Identity } from '../api/types';
|
||||
import { useLocaleStore } from '../stores/locale-store';
|
||||
|
||||
interface IdentitySheetProps {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
identities: Identity[];
|
||||
selectedIdentityId: string | null;
|
||||
onPick: (identity: Identity) => void;
|
||||
}
|
||||
|
||||
export function IdentitySheet({
|
||||
visible, onClose, identities, selectedIdentityId, onPick,
|
||||
}: IdentitySheetProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const insets = useSafeAreaInsets();
|
||||
const slideY = React.useRef(new Animated.Value(500)).current;
|
||||
const overlayOpacity = React.useRef(new Animated.Value(0)).current;
|
||||
const dragHandlers = useSheetDrag({ slideY, closedY: 500, onClose });
|
||||
const { t } = useLocaleStore();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (visible) {
|
||||
Animated.parallel([
|
||||
Animated.timing(slideY, { toValue: 0, duration: 220, easing: Easing.out(Easing.cubic), useNativeDriver: true }),
|
||||
Animated.timing(overlayOpacity, { toValue: 1, duration: 220, useNativeDriver: true }),
|
||||
]).start();
|
||||
} else {
|
||||
Animated.parallel([
|
||||
Animated.timing(slideY, { toValue: 500, duration: 180, easing: Easing.in(Easing.cubic), useNativeDriver: true }),
|
||||
Animated.timing(overlayOpacity, { toValue: 0, duration: 180, useNativeDriver: true }),
|
||||
]).start();
|
||||
}
|
||||
}, [visible, slideY, overlayOpacity]);
|
||||
|
||||
return (
|
||||
<Modal visible={visible} transparent animationType="none" onRequestClose={onClose} statusBarTranslucent>
|
||||
<Animated.View style={[styles.sheetOverlay, { opacity: overlayOpacity }]}>
|
||||
<Pressable style={styles.sheetOverlayPress} onPress={onClose} />
|
||||
</Animated.View>
|
||||
<Animated.View
|
||||
style={[
|
||||
styles.sheet,
|
||||
{ paddingBottom: Math.max(insets.bottom, spacing.md), transform: [{ translateY: slideY }] },
|
||||
]}
|
||||
>
|
||||
<View {...dragHandlers}>
|
||||
<View style={styles.sheetHandleHit}>
|
||||
<View style={styles.sheetHandle} />
|
||||
</View>
|
||||
<View style={styles.sheetHeader}>
|
||||
<Text style={styles.sheetTitle}>{t('email_composer.from', 'From')}</Text>
|
||||
<Pressable onPress={onClose} hitSlop={8} style={styles.sheetClose}>
|
||||
<X size={18} color={c.textSecondary} />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
<ScrollView style={styles.scrollList}>
|
||||
{identities.map((identity) => {
|
||||
const isSelected = identity.id === selectedIdentityId;
|
||||
return (
|
||||
<Pressable
|
||||
key={identity.id}
|
||||
onPress={() => {
|
||||
onPick(identity);
|
||||
onClose();
|
||||
}}
|
||||
style={({ pressed }) => [
|
||||
styles.identityRow,
|
||||
pressed && styles.identityRowPressed,
|
||||
]}
|
||||
>
|
||||
<View style={styles.iconWrap}>
|
||||
<Mail size={16} color={isSelected ? c.primary : c.textSecondary} />
|
||||
</View>
|
||||
<View style={styles.identityDetails}>
|
||||
{!!identity.name && (
|
||||
<Text style={styles.identityName} numberOfLines={1}>
|
||||
{identity.name}
|
||||
</Text>
|
||||
)}
|
||||
<Text style={[styles.identityEmail, !identity.name && styles.identityEmailOnly]} numberOfLines={1}>
|
||||
{identity.email}
|
||||
</Text>
|
||||
</View>
|
||||
{isSelected && (
|
||||
<View style={styles.checkWrap}>
|
||||
<Check size={16} color={c.primary} />
|
||||
</View>
|
||||
)}
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
</Animated.View>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
sheetOverlay: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
backgroundColor: 'rgba(0,0,0,0.5)',
|
||||
},
|
||||
sheetOverlayPress: { flex: 1 },
|
||||
sheet: {
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
maxHeight: '60%',
|
||||
backgroundColor: c.popover,
|
||||
borderTopLeftRadius: radius.lg,
|
||||
borderTopRightRadius: radius.lg,
|
||||
borderTopWidth: 1,
|
||||
borderColor: c.border,
|
||||
paddingTop: spacing.sm,
|
||||
},
|
||||
sheetHandleHit: {
|
||||
alignItems: 'center',
|
||||
paddingTop: spacing.xs,
|
||||
paddingBottom: spacing.sm,
|
||||
},
|
||||
sheetHandle: {
|
||||
width: 36,
|
||||
height: 4,
|
||||
borderRadius: 2,
|
||||
backgroundColor: c.border,
|
||||
},
|
||||
sheetHeader: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingBottom: spacing.sm,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: c.border,
|
||||
},
|
||||
sheetTitle: {
|
||||
...typography.bodySemibold,
|
||||
color: c.text,
|
||||
},
|
||||
sheetClose: {
|
||||
width: 28,
|
||||
height: 28,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
borderRadius: radius.xs,
|
||||
},
|
||||
scrollList: {
|
||||
paddingVertical: spacing.xs,
|
||||
},
|
||||
identityRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingVertical: spacing.md,
|
||||
minHeight: 52,
|
||||
},
|
||||
identityRowPressed: {
|
||||
backgroundColor: c.surfaceHover,
|
||||
},
|
||||
iconWrap: {
|
||||
marginRight: spacing.md,
|
||||
width: 28,
|
||||
height: 28,
|
||||
borderRadius: radius.xs,
|
||||
backgroundColor: c.surface,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
identityDetails: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
},
|
||||
identityName: {
|
||||
...typography.bodyMedium,
|
||||
color: c.text,
|
||||
},
|
||||
identityEmail: {
|
||||
...typography.caption,
|
||||
color: c.textSecondary,
|
||||
marginTop: 2,
|
||||
},
|
||||
identityEmailOnly: {
|
||||
...typography.bodyMedium,
|
||||
color: c.text,
|
||||
marginTop: 0,
|
||||
},
|
||||
checkWrap: {
|
||||
marginLeft: spacing.md,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -53,16 +53,19 @@ export function QrScanModal({ visible, onClose, onScanned }: QrScanModalProps) {
|
||||
<Pressable onPress={onClose} hitSlop={10} style={styles.closeButton}>
|
||||
<X size={24} color="#ffffff" />
|
||||
</Pressable>
|
||||
<Text style={styles.title}>Scan QR code</Text>
|
||||
<Text style={styles.title}>Sign-in code</Text>
|
||||
<View style={styles.closeButton} />
|
||||
</View>
|
||||
|
||||
{permission?.granted ? (
|
||||
<View style={styles.frameWrap}>
|
||||
<View style={styles.frame} />
|
||||
<Text style={styles.hint}>
|
||||
Point your camera at the QR code shown on the webmail settings screen.
|
||||
</Text>
|
||||
<View style={styles.hintWrap}>
|
||||
<Text style={styles.hintTitle}>Open Bulwark on your computer</Text>
|
||||
<Text style={styles.hint}>
|
||||
Settings → Devices → Add phone shows a code. Point the camera at it.
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<View style={styles.permissionWrap}>
|
||||
@@ -105,11 +108,12 @@ function makeStyles(c: ThemePalette) {
|
||||
borderRadius: radius.lg,
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
hintWrap: { alignItems: 'center', gap: spacing.xs, paddingHorizontal: spacing.xxl },
|
||||
hintTitle: { ...typography.bodySemibold, color: '#ffffff', textAlign: 'center' },
|
||||
hint: {
|
||||
...typography.caption,
|
||||
color: '#ffffff',
|
||||
color: 'rgba(255,255,255,0.8)',
|
||||
textAlign: 'center',
|
||||
paddingHorizontal: spacing.xxl,
|
||||
},
|
||||
permissionWrap: {
|
||||
flex: 1,
|
||||
|
||||
@@ -3,10 +3,7 @@ import { StyleSheet, View, Platform } from 'react-native';
|
||||
import { WebView, type WebViewMessageEvent } from 'react-native-webview';
|
||||
import { useColors } from '../theme/colors';
|
||||
import type { ThemePalette } from '../theme/tokens';
|
||||
|
||||
// Minimum visible editor height (px). The editor auto-grows beyond this as the
|
||||
// user types, and the parent ScrollView handles overflow.
|
||||
const MIN_HEIGHT = 220;
|
||||
import { buildEditorHtml, MIN_EDITOR_HEIGHT } from '../lib/editor-html';
|
||||
|
||||
export type RichTextCommand =
|
||||
| 'bold'
|
||||
@@ -54,6 +51,13 @@ export interface RichTextEditorHandle {
|
||||
unsetLink(): void;
|
||||
insertImage(src: string, cid?: string, alt?: string): void;
|
||||
setHtml(html: string): void;
|
||||
/**
|
||||
* Read the live editor DOM content. Resolves with the current innerHTML or
|
||||
* rejects after `timeoutMs` when the page script is dead or the bridge is
|
||||
* broken — callers must treat that as "content unknown", never fall back to
|
||||
* possibly-stale state (issue #9: doing so silently sent blank replies).
|
||||
*/
|
||||
getHtml(timeoutMs?: number): Promise<string>;
|
||||
focus(): void;
|
||||
}
|
||||
|
||||
@@ -66,273 +70,6 @@ interface Props {
|
||||
onBlur?: () => void;
|
||||
}
|
||||
|
||||
function buildEditorHtml(opts: {
|
||||
initialHtml: string;
|
||||
placeholder: string;
|
||||
c: ThemePalette;
|
||||
}): string {
|
||||
const { initialHtml, placeholder, c } = opts;
|
||||
// Inject initial content as a JSON-encoded string so any HTML/quotes inside
|
||||
// are safely embedded (no template literal collision with the script body).
|
||||
const initialJson = JSON.stringify(initialHtml);
|
||||
const placeholderJson = JSON.stringify(placeholder);
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
|
||||
<style>
|
||||
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||
html, body { margin: 0; padding: 0; background: ${c.background}; color: ${c.text}; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.5;
|
||||
overflow-y: hidden;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
#editor {
|
||||
outline: none;
|
||||
padding: 12px 16px 24px;
|
||||
min-height: ${MIN_HEIGHT}px;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
#editor[data-empty="true"]::before {
|
||||
content: attr(data-placeholder);
|
||||
color: ${c.textMuted};
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
}
|
||||
#editor p { margin: 0 0 12px 0; }
|
||||
#editor p:last-child { margin-bottom: 0; }
|
||||
#editor h1 { font-size: 1.4em; font-weight: 700; margin: 0 0 12px 0; line-height: 1.2; }
|
||||
#editor h2 { font-size: 1.2em; font-weight: 700; margin: 0 0 10px 0; line-height: 1.3; }
|
||||
#editor ul, #editor ol { margin: 0 0 12px 0; padding-left: 24px; }
|
||||
#editor li { margin-bottom: 4px; }
|
||||
#editor blockquote {
|
||||
margin: 0 0 12px 0;
|
||||
padding: 4px 0 4px 12px;
|
||||
border-left: 3px solid ${c.border};
|
||||
color: ${c.textSecondary};
|
||||
}
|
||||
#editor a { color: ${c.primary}; text-decoration: underline; }
|
||||
#editor img { max-width: 100%; height: auto; border-radius: 4px; }
|
||||
#editor pre, #editor code {
|
||||
background: ${c.surfaceActive};
|
||||
border-radius: 4px;
|
||||
padding: 2px 4px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 0.92em;
|
||||
}
|
||||
#editor pre { padding: 8px 12px; overflow-x: auto; }
|
||||
::selection { background: ${c.primary}33; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="editor" contenteditable="true" data-placeholder=${placeholderJson}></div>
|
||||
<script>
|
||||
(function () {
|
||||
var editor = document.getElementById('editor');
|
||||
var lastHtml = null;
|
||||
var lastHeight = 0;
|
||||
|
||||
function refreshEmpty() {
|
||||
var html = editor.innerHTML;
|
||||
var isEmpty =
|
||||
html === '' ||
|
||||
html === '<br>' ||
|
||||
html === '<p></p>' ||
|
||||
html === '<p><br></p>' ||
|
||||
editor.textContent.trim() === '' && editor.querySelectorAll('img').length === 0;
|
||||
editor.setAttribute('data-empty', isEmpty ? 'true' : 'false');
|
||||
}
|
||||
|
||||
function post(type, payload) {
|
||||
if (window.ReactNativeWebView && window.ReactNativeWebView.postMessage) {
|
||||
window.ReactNativeWebView.postMessage(JSON.stringify({ type: type, payload: payload }));
|
||||
}
|
||||
}
|
||||
|
||||
function reportHeight() {
|
||||
var h = Math.max(${MIN_HEIGHT}, editor.scrollHeight + 8);
|
||||
if (Math.abs(h - lastHeight) < 2) return;
|
||||
lastHeight = h;
|
||||
post('height', h);
|
||||
}
|
||||
|
||||
function reportChange() {
|
||||
refreshEmpty();
|
||||
var html = editor.innerHTML;
|
||||
if (html === lastHtml) return;
|
||||
lastHtml = html;
|
||||
post('change', html);
|
||||
}
|
||||
|
||||
function reportSelection() {
|
||||
function active(name) {
|
||||
try { return document.queryCommandState(name); } catch (e) { return false; }
|
||||
}
|
||||
function inBlock(tag) {
|
||||
var sel = window.getSelection();
|
||||
if (!sel || !sel.rangeCount) return false;
|
||||
var node = sel.anchorNode;
|
||||
while (node && node !== editor) {
|
||||
if (node.nodeType === 1 && node.tagName === tag) return true;
|
||||
node = node.parentNode;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
var state = {
|
||||
bold: active('bold'),
|
||||
italic: active('italic'),
|
||||
underline: active('underline'),
|
||||
strikeThrough: active('strikeThrough'),
|
||||
ul: active('insertUnorderedList'),
|
||||
ol: active('insertOrderedList'),
|
||||
blockquote: inBlock('BLOCKQUOTE'),
|
||||
h1: inBlock('H1'),
|
||||
h2: inBlock('H2'),
|
||||
alignLeft: active('justifyLeft'),
|
||||
alignCenter: active('justifyCenter'),
|
||||
alignRight: active('justifyRight'),
|
||||
link: inBlock('A'),
|
||||
};
|
||||
post('selection', state);
|
||||
}
|
||||
|
||||
// ── Initial content ────────────────────────────────────────────────
|
||||
var initial = ${initialJson};
|
||||
if (initial && typeof initial === 'string') editor.innerHTML = initial;
|
||||
refreshEmpty();
|
||||
lastHtml = editor.innerHTML;
|
||||
|
||||
editor.addEventListener('input', function () {
|
||||
reportChange();
|
||||
reportHeight();
|
||||
});
|
||||
editor.addEventListener('blur', function () { post('blur', null); });
|
||||
editor.addEventListener('focus', function () { post('focus', null); });
|
||||
document.addEventListener('selectionchange', function () {
|
||||
if (document.activeElement === editor) reportSelection();
|
||||
});
|
||||
|
||||
// ── Bridge: receive commands from RN ───────────────────────────────
|
||||
window.__rne = {
|
||||
exec: function (command, value) {
|
||||
editor.focus();
|
||||
try {
|
||||
if (command === 'formatBlock' && value) {
|
||||
// Toggle: if we're already in that block, switch to <p>.
|
||||
var sel = window.getSelection();
|
||||
if (sel && sel.rangeCount) {
|
||||
var node = sel.anchorNode;
|
||||
while (node && node !== editor) {
|
||||
if (node.nodeType === 1 && node.tagName === value.toUpperCase()) {
|
||||
document.execCommand('formatBlock', false, '<p>');
|
||||
reportChange();
|
||||
reportHeight();
|
||||
reportSelection();
|
||||
return;
|
||||
}
|
||||
node = node.parentNode;
|
||||
}
|
||||
}
|
||||
document.execCommand('formatBlock', false, '<' + value.toLowerCase() + '>');
|
||||
} else {
|
||||
document.execCommand(command, false, value);
|
||||
}
|
||||
} catch (e) {}
|
||||
reportChange();
|
||||
reportHeight();
|
||||
reportSelection();
|
||||
},
|
||||
setHtml: function (html) {
|
||||
editor.innerHTML = html || '';
|
||||
lastHtml = editor.innerHTML;
|
||||
refreshEmpty();
|
||||
reportChange();
|
||||
reportHeight();
|
||||
},
|
||||
insertHtml: function (html) {
|
||||
editor.focus();
|
||||
try { document.execCommand('insertHTML', false, html); } catch (e) {}
|
||||
reportChange();
|
||||
reportHeight();
|
||||
},
|
||||
insertLink: function (url, label) {
|
||||
editor.focus();
|
||||
// Reject anything that isn't a safe scheme or an absolute path, so the
|
||||
// user can't accidentally (or via a malicious paste) ship a
|
||||
// javascript:/data: link to their recipient.
|
||||
var safeSchemeRe = /^(https?:|mailto:|tel:|sms:|\/|\?|#)/i;
|
||||
var trimmed = (url || '').trim();
|
||||
if (!trimmed || !safeSchemeRe.test(trimmed)) return;
|
||||
var sel = window.getSelection();
|
||||
var hasSelection = sel && sel.rangeCount && !sel.getRangeAt(0).collapsed;
|
||||
if (hasSelection) {
|
||||
try { document.execCommand('createLink', false, trimmed); } catch (e) {}
|
||||
// execCommand doesn't set rel; tag every anchor that points at this URL.
|
||||
Array.prototype.forEach.call(editor.getElementsByTagName('a'), function (a) {
|
||||
if (a.getAttribute('href') === trimmed) {
|
||||
a.setAttribute('rel', 'noopener noreferrer nofollow');
|
||||
}
|
||||
});
|
||||
} else {
|
||||
var text = label && label.trim() ? label : trimmed;
|
||||
var safe = text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
var safeUrl = trimmed
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
var html = '<a href="' + safeUrl + '" rel="noopener noreferrer nofollow">' + safe + '</a>';
|
||||
try { document.execCommand('insertHTML', false, html); } catch (e) {}
|
||||
}
|
||||
reportChange();
|
||||
reportHeight();
|
||||
reportSelection();
|
||||
},
|
||||
unsetLink: function () {
|
||||
editor.focus();
|
||||
try { document.execCommand('unlink', false, null); } catch (e) {}
|
||||
reportChange();
|
||||
reportSelection();
|
||||
},
|
||||
insertImage: function (src, cid, alt) {
|
||||
editor.focus();
|
||||
var safeSrc = (src || '').replace(/"/g, '"');
|
||||
var safeAlt = (alt || '').replace(/&/g, '&').replace(/"/g, '"');
|
||||
var safeCid = cid ? cid.replace(/"/g, '"') : '';
|
||||
var html = '<img src="' + safeSrc + '" alt="' + safeAlt + '"' +
|
||||
(safeCid ? ' data-cid="' + safeCid + '"' : '') + ' />';
|
||||
try { document.execCommand('insertHTML', false, html); } catch (e) {}
|
||||
reportChange();
|
||||
reportHeight();
|
||||
},
|
||||
focus: function () { editor.focus(); },
|
||||
};
|
||||
|
||||
reportHeight();
|
||||
reportChange();
|
||||
|
||||
// Re-measure after async layout (image loads, font swap).
|
||||
window.addEventListener('load', function () {
|
||||
setTimeout(reportHeight, 50);
|
||||
setTimeout(reportHeight, 200);
|
||||
setTimeout(reportHeight, 600);
|
||||
});
|
||||
if (window.ResizeObserver) {
|
||||
new ResizeObserver(reportHeight).observe(editor);
|
||||
}
|
||||
})();
|
||||
true;
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
const RichTextEditor = React.forwardRef<RichTextEditorHandle, Props>(function RichTextEditor(
|
||||
{ initialHtml = '', placeholder = '', onChange, onSelectionChange, onFocus, onBlur },
|
||||
ref,
|
||||
@@ -340,7 +77,7 @@ const RichTextEditor = React.forwardRef<RichTextEditorHandle, Props>(function Ri
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const webViewRef = React.useRef<WebView>(null);
|
||||
const [height, setHeight] = React.useState(MIN_HEIGHT);
|
||||
const [height, setHeight] = React.useState(MIN_EDITOR_HEIGHT);
|
||||
const onChangeRef = React.useRef(onChange);
|
||||
const onSelectionRef = React.useRef(onSelectionChange);
|
||||
const onFocusRef = React.useRef(onFocus);
|
||||
@@ -364,6 +101,27 @@ const RichTextEditor = React.forwardRef<RichTextEditorHandle, Props>(function Ri
|
||||
webViewRef.current?.injectJavaScript(`${script}; true;`);
|
||||
}, []);
|
||||
|
||||
// Pending getHtml() readbacks, keyed by request id. Timers reject requests
|
||||
// the page never answers (dead script / broken bridge).
|
||||
const snapshotSeq = React.useRef(0);
|
||||
const pendingSnapshots = React.useRef(
|
||||
new Map<number, {
|
||||
resolve: (html: string) => void;
|
||||
reject: (err: Error) => void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
}>(),
|
||||
);
|
||||
React.useEffect(() => {
|
||||
const pending = pendingSnapshots.current;
|
||||
return () => {
|
||||
for (const { timer, reject } of pending.values()) {
|
||||
clearTimeout(timer);
|
||||
reject(new Error('Editor unmounted'));
|
||||
}
|
||||
pending.clear();
|
||||
};
|
||||
}, []);
|
||||
|
||||
React.useImperativeHandle(ref, () => ({
|
||||
exec: (command) => {
|
||||
const [name, value] = command.split(':');
|
||||
@@ -382,6 +140,16 @@ const RichTextEditor = React.forwardRef<RichTextEditorHandle, Props>(function Ri
|
||||
setHtml: (next) => {
|
||||
call(`window.__rne && window.__rne.setHtml(${JSON.stringify(next)})`);
|
||||
},
|
||||
getHtml: (timeoutMs = 2000) =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
const id = ++snapshotSeq.current;
|
||||
const timer = setTimeout(() => {
|
||||
pendingSnapshots.current.delete(id);
|
||||
reject(new Error('Editor did not answer'));
|
||||
}, timeoutMs);
|
||||
pendingSnapshots.current.set(id, { resolve, reject, timer });
|
||||
call(`window.__rne && window.__rne.getHtml(${id})`);
|
||||
}),
|
||||
focus: () => {
|
||||
call(`window.__rne && window.__rne.focus()`);
|
||||
},
|
||||
@@ -400,7 +168,17 @@ const RichTextEditor = React.forwardRef<RichTextEditorHandle, Props>(function Ri
|
||||
break;
|
||||
case 'height': {
|
||||
const h = typeof data.payload === 'number' ? data.payload : Number(data.payload);
|
||||
if (!Number.isNaN(h) && h > 0) setHeight(Math.max(MIN_HEIGHT, h));
|
||||
if (!Number.isNaN(h) && h > 0) setHeight(Math.max(MIN_EDITOR_HEIGHT, h));
|
||||
break;
|
||||
}
|
||||
case 'htmlSnapshot': {
|
||||
const p = data.payload as { id?: number; html?: string } | null;
|
||||
const entry = typeof p?.id === 'number' ? pendingSnapshots.current.get(p.id) : undefined;
|
||||
if (entry) {
|
||||
pendingSnapshots.current.delete(p!.id!);
|
||||
clearTimeout(entry.timer);
|
||||
entry.resolve(typeof p?.html === 'string' ? p.html : '');
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'selection':
|
||||
|
||||
@@ -172,9 +172,9 @@ export function SwipeableRow({
|
||||
return;
|
||||
}
|
||||
// Instant mode: fire on release-past-threshold, no second tap.
|
||||
if (g.dx >= COMMIT_THRESHOLD && rightAction !== 'none') {
|
||||
if ((g.dx >= COMMIT_THRESHOLD || (g.dx > 40 && g.vx >= 0.5)) && rightAction !== 'none') {
|
||||
fly(widthRef.current || EXIT_DISTANCE, rightAction);
|
||||
} else if (g.dx <= -COMMIT_THRESHOLD && leftAction !== 'none') {
|
||||
} else if ((g.dx <= -COMMIT_THRESHOLD || (g.dx < -40 && g.vx <= -0.5)) && leftAction !== 'none') {
|
||||
fly(-(widthRef.current || EXIT_DISTANCE), leftAction);
|
||||
} else {
|
||||
Animated.spring(dx, { toValue: 0, useNativeDriver: true, speed: 24, bounciness: 4 }).start();
|
||||
|
||||
@@ -83,6 +83,7 @@ function makeStyles(c: ThemePalette) {
|
||||
position: 'absolute',
|
||||
left: spacing.md,
|
||||
right: spacing.md,
|
||||
zIndex: 50,
|
||||
},
|
||||
bar: {
|
||||
flexDirection: 'row',
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import React from 'react';
|
||||
import { SectionList, StyleSheet, Text, View } from 'react-native';
|
||||
import { format, isSameDay, isToday, isTomorrow } from 'date-fns';
|
||||
import { addDays, format, isSameDay, isToday, isTomorrow, parseISO, startOfDay } from 'date-fns';
|
||||
import { CalendarDays } from 'lucide-react-native';
|
||||
import type { Calendar, CalendarEvent } from '../../api/types';
|
||||
import { spacing, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
import {
|
||||
buildEventDayIndex,
|
||||
dayKey,
|
||||
eventsOnDayFromIndex,
|
||||
getEventStartDate,
|
||||
type EventDayIndex,
|
||||
type TimeFormat,
|
||||
} from '../../lib/calendar-utils';
|
||||
import { EventCard } from './EventCard';
|
||||
|
||||
@@ -19,6 +20,7 @@ interface AgendaViewProps {
|
||||
events: CalendarEvent[];
|
||||
calendars: Calendar[];
|
||||
eventsByDay?: EventDayIndex;
|
||||
timeFormat?: TimeFormat;
|
||||
onSelectEvent?: (event: CalendarEvent) => void;
|
||||
}
|
||||
|
||||
@@ -40,6 +42,7 @@ export function AgendaView({
|
||||
events,
|
||||
calendars,
|
||||
eventsByDay,
|
||||
timeFormat,
|
||||
onSelectEvent,
|
||||
}: AgendaViewProps) {
|
||||
const c = useColors();
|
||||
@@ -50,32 +53,35 @@ export function AgendaView({
|
||||
);
|
||||
|
||||
const sections = React.useMemo<DaySection[]>(() => {
|
||||
const result: DaySection[] = [];
|
||||
const start = new Date(fromDate);
|
||||
start.setHours(0, 0, 0, 0);
|
||||
// Mirror webmail's agenda (calendar-agenda-view.tsx): build a group for
|
||||
// every day that actually has events, always include a "Today" anchor, and
|
||||
// render them sorted ascending. Driving the list off the events (rather than
|
||||
// a fixed day-counter) guarantees every upcoming loaded event appears - not
|
||||
// just the ones inside a brittle N-day window from the anchor.
|
||||
const anchor = startOfDay(fromDate);
|
||||
const horizonEnd = addDays(anchor, daysAhead); // safety bound (exclusive)
|
||||
|
||||
for (let i = 0; i < daysAhead; i++) {
|
||||
const day = new Date(start);
|
||||
day.setDate(start.getDate() + i);
|
||||
const dayEvents = eventsOnDayFromIndex(index, day).slice().sort((a, b) => {
|
||||
// All-day events first within a day, then by start time, then title
|
||||
// (stable tie-break) - mirrors the comparator the webmail uses for
|
||||
// packing week segments and keeps multi-event days predictable.
|
||||
if (a.showWithoutTime !== b.showWithoutTime) {
|
||||
return a.showWithoutTime ? -1 : 1;
|
||||
}
|
||||
const diff = getEventStartDate(a).getTime() - getEventStartDate(b).getTime();
|
||||
if (diff !== 0) return diff;
|
||||
return (a.title || '').localeCompare(b.title || '');
|
||||
});
|
||||
if (dayEvents.length === 0 && !isToday(day)) continue;
|
||||
result.push({
|
||||
const days = new Map<string, Date>();
|
||||
for (const key of index.keys()) {
|
||||
const day = parseISO(key); // index keys are local yyyy-MM-dd
|
||||
if (isNaN(day.getTime())) continue;
|
||||
if (day < anchor || day >= horizonEnd) continue;
|
||||
days.set(key, day);
|
||||
}
|
||||
// Always anchor "Today" so the view has a stable starting point even when
|
||||
// the current day has no events (webmail injects the same anchor).
|
||||
const today = startOfDay(new Date());
|
||||
if (today >= anchor && today < horizonEnd) days.set(dayKey(today), today);
|
||||
|
||||
return [...days.values()]
|
||||
.sort((a, b) => a.getTime() - b.getTime())
|
||||
.map((day) => ({
|
||||
title: formatDayHeader(day),
|
||||
date: day,
|
||||
data: dayEvents,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
// Buckets are pre-sorted by buildEventDayIndex (all-day first, then by
|
||||
// start, then title), so no extra sort is needed here.
|
||||
data: eventsOnDayFromIndex(index, day),
|
||||
}));
|
||||
}, [fromDate, daysAhead, index]);
|
||||
|
||||
if (sections.length === 0) {
|
||||
@@ -107,7 +113,7 @@ export function AgendaView({
|
||||
}}
|
||||
renderItem={({ item }) => (
|
||||
<View style={styles.itemWrap}>
|
||||
<EventCard event={item} calendars={calendars} onPress={onSelectEvent} />
|
||||
<EventCard event={item} calendars={calendars} timeFormat={timeFormat} onPress={onSelectEvent} />
|
||||
</View>
|
||||
)}
|
||||
renderSectionFooter={({ section }) =>
|
||||
|
||||
@@ -11,12 +11,13 @@ import {
|
||||
View,
|
||||
} from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { Check, X, Upload, Rss } from 'lucide-react-native';
|
||||
import { Check, X, Upload, Rss, Shuffle, Star } from 'lucide-react-native';
|
||||
import type { Calendar } from '../../api/types';
|
||||
import { radius, spacing, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
import { useAnimDuration } from '../../theme/dynamic';
|
||||
import { getCalendarColor } from '../../lib/calendar-utils';
|
||||
import { CALENDAR_COLOR_PALETTE, getCalendarColor } from '../../lib/calendar-utils';
|
||||
import { BIRTHDAY_CALENDAR_ID } from '../../lib/birthday-calendar';
|
||||
|
||||
interface CalendarSidebarDrawerProps {
|
||||
visible: boolean;
|
||||
@@ -26,6 +27,11 @@ interface CalendarSidebarDrawerProps {
|
||||
onClose: () => void;
|
||||
onImport?: () => void;
|
||||
onManageSubscriptions?: () => void;
|
||||
// Long-press actions. Set-default applies to the user's own calendars;
|
||||
// color change/reset applies to shared calendars (per-viewer recolor).
|
||||
onSetDefault?: (calendar: Calendar) => void;
|
||||
onSetColor?: (calendar: Calendar, color: string) => void;
|
||||
onResetColor?: (calendar: Calendar) => void;
|
||||
}
|
||||
|
||||
export function CalendarSidebarDrawer({
|
||||
@@ -36,6 +42,9 @@ export function CalendarSidebarDrawer({
|
||||
onClose,
|
||||
onImport,
|
||||
onManageSubscriptions,
|
||||
onSetDefault,
|
||||
onSetColor,
|
||||
onResetColor,
|
||||
}: CalendarSidebarDrawerProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
@@ -43,6 +52,7 @@ export function CalendarSidebarDrawer({
|
||||
const overlayOpacity = React.useRef(new Animated.Value(0)).current;
|
||||
const openDuration = useAnimDuration(240);
|
||||
const closeDuration = useAnimDuration(200);
|
||||
const [expandedId, setExpandedId] = React.useState<string | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (visible) {
|
||||
@@ -60,6 +70,7 @@ export function CalendarSidebarDrawer({
|
||||
}),
|
||||
]).start();
|
||||
} else {
|
||||
setExpandedId(null);
|
||||
Animated.parallel([
|
||||
Animated.timing(slideX, {
|
||||
toValue: -Dimensions.get('window').width,
|
||||
@@ -78,8 +89,23 @@ export function CalendarSidebarDrawer({
|
||||
|
||||
const hiddenSet = React.useMemo(() => new Set(hiddenCalendarIds), [hiddenCalendarIds]);
|
||||
|
||||
const myCalendars = calendars.filter((c) => !c.myRights || c.myRights.mayWrite !== false);
|
||||
const subscribed = calendars.filter((c) => c.myRights && c.myRights.mayWrite === false);
|
||||
const sharedCalendars = calendars.filter((cal) => cal.isShared);
|
||||
const myCalendars = calendars.filter(
|
||||
(cal) => !cal.isShared && (!cal.myRights || cal.myRights.mayWrite !== false),
|
||||
);
|
||||
const subscribed = calendars.filter(
|
||||
(cal) => !cal.isShared && cal.myRights && cal.myRights.mayWrite === false,
|
||||
);
|
||||
|
||||
const sectionProps = {
|
||||
hiddenSet,
|
||||
onToggle,
|
||||
expandedId,
|
||||
onExpand: setExpandedId,
|
||||
onSetDefault,
|
||||
onSetColor,
|
||||
onResetColor,
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@@ -110,21 +136,15 @@ export function CalendarSidebarDrawer({
|
||||
)}
|
||||
|
||||
{myCalendars.length > 0 && (
|
||||
<Section
|
||||
title="My calendars"
|
||||
calendars={myCalendars}
|
||||
hiddenSet={hiddenSet}
|
||||
onToggle={onToggle}
|
||||
/>
|
||||
<Section title="My calendars" calendars={myCalendars} {...sectionProps} />
|
||||
)}
|
||||
|
||||
{sharedCalendars.length > 0 && (
|
||||
<Section title="Shared with me" calendars={sharedCalendars} {...sectionProps} />
|
||||
)}
|
||||
|
||||
{subscribed.length > 0 && (
|
||||
<Section
|
||||
title="Subscribed"
|
||||
calendars={subscribed}
|
||||
hiddenSet={hiddenSet}
|
||||
onToggle={onToggle}
|
||||
/>
|
||||
<Section title="Subscribed" calendars={subscribed} {...sectionProps} />
|
||||
)}
|
||||
|
||||
{(onImport || onManageSubscriptions) && (
|
||||
@@ -161,11 +181,21 @@ function Section({
|
||||
calendars,
|
||||
hiddenSet,
|
||||
onToggle,
|
||||
expandedId,
|
||||
onExpand,
|
||||
onSetDefault,
|
||||
onSetColor,
|
||||
onResetColor,
|
||||
}: {
|
||||
title: string;
|
||||
calendars: Calendar[];
|
||||
hiddenSet: Set<string>;
|
||||
onToggle: (id: string) => void;
|
||||
expandedId: string | null;
|
||||
onExpand: (id: string | null) => void;
|
||||
onSetDefault?: (calendar: Calendar) => void;
|
||||
onSetColor?: (calendar: Calendar, color: string) => void;
|
||||
onResetColor?: (calendar: Calendar) => void;
|
||||
}) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
@@ -174,30 +204,85 @@ function Section({
|
||||
<Text style={styles.sectionTitle}>{title}</Text>
|
||||
{calendars.map((cal) => {
|
||||
const visible = !hiddenSet.has(cal.id);
|
||||
const isBirthday = cal.id === BIRTHDAY_CALENDAR_ID;
|
||||
const canSetDefault = !!onSetDefault && !cal.isShared && !isBirthday && !cal.isDefault;
|
||||
const canRecolor = !!onSetColor && !!cal.isShared;
|
||||
const hasActions = canSetDefault || canRecolor;
|
||||
const expanded = expandedId === cal.id && hasActions;
|
||||
return (
|
||||
<Pressable
|
||||
key={cal.id}
|
||||
onPress={() => onToggle(cal.id)}
|
||||
style={({ pressed }) => [
|
||||
styles.row,
|
||||
pressed && styles.rowPressed,
|
||||
]}
|
||||
>
|
||||
<View
|
||||
style={[
|
||||
styles.swatch,
|
||||
{
|
||||
backgroundColor: visible ? getCalendarColor(cal) : 'transparent',
|
||||
borderColor: getCalendarColor(cal),
|
||||
},
|
||||
<View key={cal.id}>
|
||||
<Pressable
|
||||
onPress={() => onToggle(cal.id)}
|
||||
onLongPress={hasActions ? () => onExpand(expanded ? null : cal.id) : undefined}
|
||||
style={({ pressed }) => [
|
||||
styles.row,
|
||||
pressed && styles.rowPressed,
|
||||
]}
|
||||
>
|
||||
{visible && <Check size={12} color={c.textInverse} />}
|
||||
</View>
|
||||
<Text style={[styles.rowName, !visible && styles.rowNameMuted]}>
|
||||
{cal.name}
|
||||
</Text>
|
||||
</Pressable>
|
||||
<View
|
||||
style={[
|
||||
styles.swatch,
|
||||
{
|
||||
backgroundColor: visible ? getCalendarColor(cal) : 'transparent',
|
||||
borderColor: getCalendarColor(cal),
|
||||
},
|
||||
]}
|
||||
>
|
||||
{visible && <Check size={12} color={c.textInverse} />}
|
||||
</View>
|
||||
<Text style={[styles.rowName, !visible && styles.rowNameMuted]} numberOfLines={1}>
|
||||
{cal.name}
|
||||
</Text>
|
||||
{cal.isDefault && !cal.isShared && (
|
||||
<Star size={14} color={c.textMuted} fill={c.textMuted} />
|
||||
)}
|
||||
</Pressable>
|
||||
|
||||
{expanded && (
|
||||
<View style={styles.actionsPanel}>
|
||||
{canSetDefault && (
|
||||
<Pressable
|
||||
onPress={() => { onExpand(null); onSetDefault!(cal); }}
|
||||
style={({ pressed }) => [styles.panelRow, pressed && styles.rowPressed]}
|
||||
>
|
||||
<Star size={16} color={c.textSecondary} />
|
||||
<Text style={styles.panelRowText}>Set as default calendar</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
{canRecolor && (
|
||||
<>
|
||||
<View style={styles.paletteRow}>
|
||||
{CALENDAR_COLOR_PALETTE.map((color) => {
|
||||
const active = cal.color?.toLowerCase() === color.toLowerCase();
|
||||
return (
|
||||
<Pressable
|
||||
key={color}
|
||||
onPress={() => { onExpand(null); onSetColor!(cal, color); }}
|
||||
style={[
|
||||
styles.paletteSwatch,
|
||||
{ backgroundColor: color },
|
||||
active && styles.paletteSwatchActive,
|
||||
]}
|
||||
>
|
||||
{active && <Check size={12} color={c.textInverse} />}
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
{!!onResetColor && cal.colorIsLocalOverride && (
|
||||
<Pressable
|
||||
onPress={() => { onExpand(null); onResetColor(cal); }}
|
||||
style={({ pressed }) => [styles.panelRow, pressed && styles.rowPressed]}
|
||||
>
|
||||
<Shuffle size={16} color={c.textSecondary} />
|
||||
<Text style={styles.panelRowText}>Random color</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
@@ -279,6 +364,43 @@ function makeStyles(c: ThemePalette) {
|
||||
rowName: { flex: 1, ...typography.body, color: c.text },
|
||||
rowNameMuted: { color: c.textMuted },
|
||||
|
||||
actionsPanel: {
|
||||
marginHorizontal: spacing.lg,
|
||||
marginBottom: spacing.sm,
|
||||
borderWidth: 1,
|
||||
borderColor: c.border,
|
||||
borderRadius: radius.sm,
|
||||
backgroundColor: c.surface,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
panelRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm,
|
||||
minHeight: 40,
|
||||
},
|
||||
panelRowText: { ...typography.body, color: c.text },
|
||||
paletteRow: {
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
gap: spacing.sm,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm,
|
||||
},
|
||||
paletteSwatch: {
|
||||
width: 24,
|
||||
height: 24,
|
||||
borderRadius: radius.full,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
paletteSwatchActive: {
|
||||
borderWidth: 2,
|
||||
borderColor: c.text,
|
||||
},
|
||||
|
||||
actionsSection: {
|
||||
marginTop: spacing.lg,
|
||||
paddingTop: spacing.sm,
|
||||
|
||||
@@ -5,11 +5,17 @@ import { format } from 'date-fns';
|
||||
import type { Calendar, CalendarEvent } from '../../api/types';
|
||||
import { radius, spacing, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
import { eventTimeRange, getEventColor } from '../../lib/calendar-utils';
|
||||
import {
|
||||
eventTimeRange,
|
||||
getEventColor,
|
||||
timePattern,
|
||||
type TimeFormat,
|
||||
} from '../../lib/calendar-utils';
|
||||
|
||||
interface EventCardProps {
|
||||
event: CalendarEvent;
|
||||
calendars: Calendar[];
|
||||
timeFormat?: TimeFormat;
|
||||
onPress?: (event: CalendarEvent) => void;
|
||||
onLongPress?: (event: CalendarEvent) => void;
|
||||
}
|
||||
@@ -18,17 +24,18 @@ function participantCount(event: CalendarEvent): number {
|
||||
return event.participants ? Object.keys(event.participants).length : 0;
|
||||
}
|
||||
|
||||
function formatTimeRange(event: CalendarEvent): string {
|
||||
function formatTimeRange(event: CalendarEvent, timeFormat?: TimeFormat): string {
|
||||
const { start, end, allDay } = eventTimeRange(event);
|
||||
if (allDay) return 'All day';
|
||||
return `${format(start, 'HH:mm')} – ${format(end, 'HH:mm')}`;
|
||||
const fmt = timePattern(timeFormat);
|
||||
return `${format(start, fmt)} – ${format(end, fmt)}`;
|
||||
}
|
||||
|
||||
export function EventCard({ event, calendars, onPress, onLongPress }: EventCardProps) {
|
||||
export function EventCard({ event, calendars, timeFormat, onPress, onLongPress }: EventCardProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const color = getEventColor(event, calendars);
|
||||
const time = formatTimeRange(event);
|
||||
const time = formatTimeRange(event, timeFormat);
|
||||
const count = participantCount(event);
|
||||
|
||||
return (
|
||||
|
||||
@@ -36,6 +36,8 @@ import {
|
||||
eventTimeRange,
|
||||
getEventColor,
|
||||
getPrimaryCalendarId,
|
||||
timePattern,
|
||||
type TimeFormat,
|
||||
} from '../../lib/calendar-utils';
|
||||
import { alertsToReminders, formatReminder } from '../../lib/calendar-alerts';
|
||||
import {
|
||||
@@ -50,6 +52,7 @@ type RsvpStatus = 'accepted' | 'declined' | 'tentative';
|
||||
interface EventDetailSheetProps {
|
||||
event: CalendarEvent | null;
|
||||
calendars: Calendar[];
|
||||
timeFormat?: TimeFormat;
|
||||
onClose: () => void;
|
||||
onEdit?: (event: CalendarEvent) => void;
|
||||
onDelete?: (event: CalendarEvent) => void;
|
||||
@@ -57,7 +60,7 @@ interface EventDetailSheetProps {
|
||||
onRsvp?: (event: CalendarEvent, participantId: string, status: RsvpStatus) => void | Promise<void>;
|
||||
}
|
||||
|
||||
function formatRange(event: CalendarEvent): string {
|
||||
function formatRange(event: CalendarEvent, timeFormat?: TimeFormat): string {
|
||||
const { start, end, allDay } = eventTimeRange(event);
|
||||
if (allDay) {
|
||||
if (
|
||||
@@ -69,14 +72,15 @@ function formatRange(event: CalendarEvent): string {
|
||||
}
|
||||
return `${format(start, 'MMM d')} – ${format(end, 'MMM d, yyyy')}`;
|
||||
}
|
||||
const t = timePattern(timeFormat);
|
||||
const sameDay =
|
||||
start.getFullYear() === end.getFullYear() &&
|
||||
start.getMonth() === end.getMonth() &&
|
||||
start.getDate() === end.getDate();
|
||||
if (sameDay) {
|
||||
return `${format(start, 'EEE, MMM d')} · ${format(start, 'HH:mm')} – ${format(end, 'HH:mm')}`;
|
||||
return `${format(start, 'EEE, MMM d')} · ${format(start, t)} – ${format(end, t)}`;
|
||||
}
|
||||
return `${format(start, 'MMM d, HH:mm')} – ${format(end, 'MMM d, HH:mm')}`;
|
||||
return `${format(start, `MMM d, ${t}`)} – ${format(end, `MMM d, ${t}`)}`;
|
||||
}
|
||||
|
||||
function recurrenceLabel(event: CalendarEvent): string | null {
|
||||
@@ -100,6 +104,7 @@ function recurrenceLabel(event: CalendarEvent): string | null {
|
||||
export function EventDetailSheet({
|
||||
event,
|
||||
calendars,
|
||||
timeFormat,
|
||||
onClose,
|
||||
onEdit,
|
||||
onDelete,
|
||||
@@ -156,7 +161,7 @@ export function EventDetailSheet({
|
||||
const color = getEventColor(event, calendars);
|
||||
const calendarId = getPrimaryCalendarId(event);
|
||||
const calendar = calendars.find((c) => c.id === calendarId);
|
||||
const range = formatRange(event);
|
||||
const range = formatRange(event, timeFormat);
|
||||
const recurrence = recurrenceLabel(event);
|
||||
const reminders = alertsToReminders(event.alerts);
|
||||
const participants = event.participants ? Object.values(event.participants) : [];
|
||||
|
||||
@@ -31,6 +31,7 @@ import type {
|
||||
CalendarEvent,
|
||||
Participant,
|
||||
EventLocation,
|
||||
RecurrenceRule,
|
||||
VirtualLocation,
|
||||
} from '../../api/types';
|
||||
import { radius, spacing, typography, type ThemePalette } from '../../theme/tokens';
|
||||
@@ -49,10 +50,12 @@ import {
|
||||
REMINDER_PRESETS,
|
||||
type Reminder,
|
||||
} from '../../lib/calendar-alerts';
|
||||
import { buildRecurrenceSummary, isSimpleRecurrenceRule } from '../../lib/recurrence';
|
||||
import { Button } from '..';
|
||||
import { ParticipantInput } from './ParticipantInput';
|
||||
import { RecurrenceEditor } from './RecurrenceEditor';
|
||||
|
||||
type RecurrenceOption = 'none' | 'daily' | 'weekly' | 'monthly' | 'yearly';
|
||||
type RecurrenceOption = 'none' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'custom';
|
||||
|
||||
const RECURRENCE_OPTIONS: { value: RecurrenceOption; label: string }[] = [
|
||||
{ value: 'none', label: 'Does not repeat' },
|
||||
@@ -60,6 +63,7 @@ const RECURRENCE_OPTIONS: { value: RecurrenceOption; label: string }[] = [
|
||||
{ value: 'weekly', label: 'Weekly' },
|
||||
{ value: 'monthly', label: 'Monthly' },
|
||||
{ value: 'yearly', label: 'Yearly' },
|
||||
{ value: 'custom', label: 'Custom…' },
|
||||
];
|
||||
|
||||
interface EventModalProps {
|
||||
@@ -99,11 +103,15 @@ function buildDuration(start: Date, end: Date): string {
|
||||
function detectRecurrence(event: CalendarEvent | null | undefined): RecurrenceOption {
|
||||
const rule = event?.recurrenceRules?.[0];
|
||||
if (!rule) return 'none';
|
||||
const f = rule.frequency.toLowerCase();
|
||||
if (f === 'daily' || f === 'weekly' || f === 'monthly' || f === 'yearly') {
|
||||
return f as RecurrenceOption;
|
||||
if (isSimpleRecurrenceRule(rule)) {
|
||||
const f = rule.frequency.toLowerCase();
|
||||
if (f === 'daily' || f === 'weekly' || f === 'monthly' || f === 'yearly') {
|
||||
return f as RecurrenceOption;
|
||||
}
|
||||
}
|
||||
return 'none';
|
||||
// Anything the simple presets can't represent is edited via the custom
|
||||
// recurrence editor.
|
||||
return 'custom';
|
||||
}
|
||||
|
||||
function detectLocation(event: CalendarEvent | null | undefined): string {
|
||||
@@ -156,9 +164,18 @@ export function EventModal({
|
||||
const [allDay, setAllDay] = React.useState(false);
|
||||
const [start, setStart] = React.useState<Date>(() => nextHalfHour(defaultDate ?? new Date()));
|
||||
const [end, setEnd] = React.useState<Date>(() => addHours(nextHalfHour(defaultDate ?? new Date()), 1));
|
||||
const [calendarId, setCalendarId] = React.useState<string>(defaultCalendarId || calendars[0]?.id || '');
|
||||
// New events land in the explicitly requested calendar, else the account's
|
||||
// default calendar, else the first one.
|
||||
const fallbackCalendarId =
|
||||
defaultCalendarId
|
||||
|| calendars.find((cal) => cal.isDefault && !cal.isShared)?.id
|
||||
|| calendars[0]?.id
|
||||
|| '';
|
||||
const [calendarId, setCalendarId] = React.useState<string>(fallbackCalendarId);
|
||||
const [participants, setParticipants] = React.useState<Record<string, Participant>>({});
|
||||
const [recurrence, setRecurrence] = React.useState<RecurrenceOption>('none');
|
||||
const [customRule, setCustomRule] = React.useState<RecurrenceRule | null>(null);
|
||||
const [recurrenceEditorOpen, setRecurrenceEditorOpen] = React.useState(false);
|
||||
const [reminders, setReminders] = React.useState<Reminder[]>([]);
|
||||
const [location, setLocation] = React.useState('');
|
||||
const [videoUrl, setVideoUrl] = React.useState('');
|
||||
@@ -181,7 +198,10 @@ export function EventModal({
|
||||
setEnd(getEventEndDate(event));
|
||||
setCalendarId(getPrimaryCalendarId(event) || calendars[0]?.id || '');
|
||||
setParticipants(event.participants || {});
|
||||
setRecurrence(detectRecurrence(event));
|
||||
const detected = detectRecurrence(event);
|
||||
setRecurrence(detected);
|
||||
setCustomRule(detected === 'custom' ? event.recurrenceRules?.[0] ?? null : null);
|
||||
setRecurrenceEditorOpen(false);
|
||||
setReminders(alertsToReminders(event.alerts));
|
||||
setLocation(detectLocation(event));
|
||||
setVideoUrl(detectVideoUrl(event));
|
||||
@@ -192,9 +212,16 @@ export function EventModal({
|
||||
setAllDay(false);
|
||||
setStart(d);
|
||||
setEnd(addHours(d, 1));
|
||||
setCalendarId(defaultCalendarId || calendars[0]?.id || '');
|
||||
setCalendarId(
|
||||
defaultCalendarId
|
||||
|| calendars.find((cal) => cal.isDefault && !cal.isShared)?.id
|
||||
|| calendars[0]?.id
|
||||
|| '',
|
||||
);
|
||||
setParticipants({});
|
||||
setRecurrence('none');
|
||||
setCustomRule(null);
|
||||
setRecurrenceEditorOpen(false);
|
||||
setReminders([]);
|
||||
setLocation('');
|
||||
setVideoUrl('');
|
||||
@@ -241,7 +268,12 @@ export function EventModal({
|
||||
: format(start, "yyyy-MM-dd'T'HH:mm:ss"),
|
||||
duration: allDay ? buildAllDayDuration(start, end) : buildDuration(start, end),
|
||||
participants: Object.keys(participants).length > 0 ? participants : undefined,
|
||||
recurrenceRules: recurrenceFromOption(recurrence),
|
||||
recurrenceRules:
|
||||
recurrence === 'custom'
|
||||
? customRule
|
||||
? [customRule]
|
||||
: undefined
|
||||
: recurrenceFromOption(recurrence),
|
||||
alerts: remindersToAlerts(reminders),
|
||||
useDefaultAlerts: reminders.length > 0 ? false : undefined,
|
||||
locations: buildLocations(location),
|
||||
@@ -259,7 +291,10 @@ export function EventModal({
|
||||
};
|
||||
|
||||
const selectedCalendar = calendars.find((c) => c.id === calendarId);
|
||||
const recurrenceLabel = RECURRENCE_OPTIONS.find((o) => o.value === recurrence)?.label || 'None';
|
||||
const recurrenceLabel =
|
||||
recurrence === 'custom'
|
||||
? (customRule && buildRecurrenceSummary(customRule)) || 'Custom'
|
||||
: RECURRENCE_OPTIONS.find((o) => o.value === recurrence)?.label || 'None';
|
||||
|
||||
const addReminder = (minutesBefore: number) => {
|
||||
setReminderPickerOpen(false);
|
||||
@@ -431,8 +466,14 @@ export function EventModal({
|
||||
opt.value === recurrence && styles.popoverRowActive,
|
||||
]}
|
||||
onPress={() => {
|
||||
setRecurrence(opt.value);
|
||||
setRecurrenceOpen(false);
|
||||
if (opt.value === 'custom') {
|
||||
setRecurrenceEditorOpen(true);
|
||||
return;
|
||||
}
|
||||
setRecurrence(opt.value);
|
||||
setCustomRule(null);
|
||||
setRecurrenceEditorOpen(false);
|
||||
}}
|
||||
>
|
||||
<Text style={styles.popoverRowText}>{opt.label}</Text>
|
||||
@@ -440,6 +481,23 @@ export function EventModal({
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
{recurrenceEditorOpen && (
|
||||
<RecurrenceEditor
|
||||
rule={customRule}
|
||||
eventStart={start}
|
||||
onSave={(rule) => {
|
||||
setCustomRule(rule);
|
||||
setRecurrence('custom');
|
||||
setRecurrenceEditorOpen(false);
|
||||
}}
|
||||
onCancel={() => setRecurrenceEditorOpen(false)}
|
||||
/>
|
||||
)}
|
||||
{recurrence === 'custom' && customRule && !recurrenceEditorOpen && (
|
||||
<Pressable style={styles.addRow} onPress={() => setRecurrenceEditorOpen(true)}>
|
||||
<Text style={styles.addRowText}>Edit custom recurrence</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section icon={<Bell size={16} color={c.textMuted} />} label="Reminders">
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
import React from 'react';
|
||||
import { View, Text, TextInput, Pressable, StyleSheet, Platform } from 'react-native';
|
||||
import DateTimePicker from '@react-native-community/datetimepicker';
|
||||
import { ChevronDown } from 'lucide-react-native';
|
||||
import { format, parseISO } from 'date-fns';
|
||||
import type { RecurrenceRule } from '../../api/types';
|
||||
import { radius, spacing, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
import { Button } from '..';
|
||||
import {
|
||||
EDITOR_FREQUENCIES,
|
||||
UNIT_LABELS,
|
||||
WEEKDAYS,
|
||||
buildRecurrenceSummary,
|
||||
buildRuleFromEditorValue,
|
||||
capitalize,
|
||||
editorValueFromRule,
|
||||
monthName,
|
||||
nthLabel,
|
||||
weekdayName,
|
||||
type EditorFrequency,
|
||||
type EndsMode,
|
||||
type MonthlyMode,
|
||||
type RecurrenceEditorValue,
|
||||
} from '../../lib/recurrence';
|
||||
|
||||
interface RecurrenceEditorProps {
|
||||
rule: RecurrenceRule | null;
|
||||
eventStart: Date;
|
||||
onSave: (rule: RecurrenceRule) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
// Small popover-style select, matching the EventModal field pattern.
|
||||
function InlineSelect<T extends string | number>({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
flex,
|
||||
}: {
|
||||
value: T;
|
||||
options: { value: T; label: string }[];
|
||||
onChange: (value: T) => void;
|
||||
flex?: boolean;
|
||||
}) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const selected = options.find((o) => o.value === value);
|
||||
return (
|
||||
<View style={flex ? styles.selectFlex : undefined}>
|
||||
<Pressable style={styles.selectButton} onPress={() => setOpen((v) => !v)}>
|
||||
<Text style={styles.selectText} numberOfLines={1}>
|
||||
{selected?.label ?? String(value)}
|
||||
</Text>
|
||||
<ChevronDown size={14} color={c.textMuted} />
|
||||
</Pressable>
|
||||
{open && (
|
||||
<View style={styles.popover}>
|
||||
{options.map((opt) => (
|
||||
<Pressable
|
||||
key={String(opt.value)}
|
||||
style={[styles.popoverRow, opt.value === value && styles.popoverRowActive]}
|
||||
onPress={() => {
|
||||
onChange(opt.value);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<Text style={styles.popoverRowText}>{opt.label}</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function NumberInput({
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
onChange,
|
||||
}: {
|
||||
value: number;
|
||||
min: number;
|
||||
max: number;
|
||||
onChange: (value: number) => void;
|
||||
}) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const [text, setText] = React.useState(String(value));
|
||||
React.useEffect(() => setText(String(value)), [value]);
|
||||
return (
|
||||
<TextInput
|
||||
value={text}
|
||||
onChangeText={setText}
|
||||
onEndEditing={() => {
|
||||
const n = parseInt(text, 10);
|
||||
const clamped = Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : min;
|
||||
setText(String(clamped));
|
||||
onChange(clamped);
|
||||
}}
|
||||
keyboardType="number-pad"
|
||||
style={styles.numberInput}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function RecurrenceEditor({ rule, eventStart, onSave, onCancel }: RecurrenceEditorProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
|
||||
const [value, setValue] = React.useState<RecurrenceEditorValue>(() =>
|
||||
editorValueFromRule(rule, eventStart),
|
||||
);
|
||||
const [showUntilPicker, setShowUntilPicker] = React.useState(false);
|
||||
|
||||
const update = (patch: Partial<RecurrenceEditorValue>) =>
|
||||
setValue((prev) => ({ ...prev, ...patch }));
|
||||
|
||||
const toggleWeekDay = (day: string) => {
|
||||
setValue((prev) => ({
|
||||
...prev,
|
||||
weekDays: prev.weekDays.includes(day)
|
||||
? prev.weekDays.length > 1
|
||||
? prev.weekDays.filter((d) => d !== day)
|
||||
: prev.weekDays
|
||||
: [...prev.weekDays, day],
|
||||
}));
|
||||
};
|
||||
|
||||
const builtRule = buildRuleFromEditorValue(value, eventStart);
|
||||
const summary = buildRecurrenceSummary(builtRule);
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={styles.row}>
|
||||
<Text style={styles.rowLabel}>Every</Text>
|
||||
<NumberInput
|
||||
value={value.interval}
|
||||
min={1}
|
||||
max={999}
|
||||
onChange={(interval) => update({ interval })}
|
||||
/>
|
||||
<InlineSelect<EditorFrequency>
|
||||
flex
|
||||
value={value.frequency}
|
||||
options={EDITOR_FREQUENCIES.map((f) => ({ value: f, label: UNIT_LABELS[f] }))}
|
||||
onChange={(frequency) => update({ frequency })}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{value.frequency === 'weekly' && (
|
||||
<View style={styles.weekdayRow}>
|
||||
{WEEKDAYS.map((day) => {
|
||||
const active = value.weekDays.includes(day);
|
||||
return (
|
||||
<Pressable
|
||||
key={day}
|
||||
onPress={() => toggleWeekDay(day)}
|
||||
style={[styles.weekdayChip, active && styles.weekdayChipActive]}
|
||||
>
|
||||
<Text style={[styles.weekdayChipText, active && styles.weekdayChipTextActive]}>
|
||||
{weekdayName(day, 'short')}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
|
||||
{value.frequency === 'yearly' && (
|
||||
<View style={styles.row}>
|
||||
<Text style={styles.rowLabel}>In</Text>
|
||||
<InlineSelect<number>
|
||||
flex
|
||||
value={value.month}
|
||||
options={Array.from({ length: 12 }, (_, i) => i + 1).map((m) => ({
|
||||
value: m,
|
||||
label: capitalize(monthName(m)),
|
||||
}))}
|
||||
onChange={(month) => update({ month })}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{(value.frequency === 'monthly' || value.frequency === 'yearly') && (
|
||||
<View style={styles.row}>
|
||||
<InlineSelect<MonthlyMode>
|
||||
value={value.monthlyMode}
|
||||
options={[
|
||||
{ value: 'day', label: 'On day' },
|
||||
{ value: 'nth', label: 'On the' },
|
||||
]}
|
||||
onChange={(monthlyMode) => update({ monthlyMode })}
|
||||
/>
|
||||
{value.monthlyMode === 'day' ? (
|
||||
<NumberInput
|
||||
value={value.monthDay}
|
||||
min={1}
|
||||
max={31}
|
||||
onChange={(monthDay) => update({ monthDay })}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<InlineSelect<number>
|
||||
flex
|
||||
value={value.nth}
|
||||
options={[1, 2, 3, 4, -1].map((n) => ({ value: n, label: capitalize(nthLabel(n)) }))}
|
||||
onChange={(nth) => update({ nth })}
|
||||
/>
|
||||
<InlineSelect<string>
|
||||
flex
|
||||
value={value.nthDay}
|
||||
options={WEEKDAYS.map((d) => ({ value: d, label: capitalize(weekdayName(d)) }))}
|
||||
onChange={(nthDay) => update({ nthDay })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View style={styles.row}>
|
||||
<Text style={styles.rowLabel}>Ends</Text>
|
||||
<InlineSelect<EndsMode>
|
||||
flex={value.endsMode === 'never'}
|
||||
value={value.endsMode}
|
||||
options={[
|
||||
{ value: 'never', label: 'Never' },
|
||||
{ value: 'on', label: 'On date' },
|
||||
{ value: 'after', label: 'After' },
|
||||
]}
|
||||
onChange={(endsMode) => update({ endsMode })}
|
||||
/>
|
||||
{value.endsMode === 'on' && (
|
||||
<Pressable style={[styles.selectButton, styles.selectFlex]} onPress={() => setShowUntilPicker(true)}>
|
||||
<Text style={styles.selectText}>
|
||||
{format(parseISO(value.untilDate), 'MMM d, yyyy')}
|
||||
</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
{value.endsMode === 'after' && (
|
||||
<>
|
||||
<NumberInput
|
||||
value={value.count}
|
||||
min={1}
|
||||
max={999}
|
||||
onChange={(count) => update({ count })}
|
||||
/>
|
||||
<Text style={styles.muted}>occurrences</Text>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View style={styles.footer}>
|
||||
<Text style={styles.summary} numberOfLines={2}>
|
||||
{summary}
|
||||
</Text>
|
||||
<View style={styles.footerButtons}>
|
||||
<Button variant="outline" size="sm" onPress={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="default" size="sm" onPress={() => onSave(builtRule)}>
|
||||
Done
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{showUntilPicker && (
|
||||
<DateTimePicker
|
||||
value={parseISO(value.untilDate)}
|
||||
mode="date"
|
||||
display={Platform.OS === 'ios' ? 'spinner' : 'default'}
|
||||
onChange={(_, d) => {
|
||||
setShowUntilPicker(false);
|
||||
if (d) update({ untilDate: format(d, 'yyyy-MM-dd') });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
container: {
|
||||
borderWidth: 1,
|
||||
borderColor: c.border,
|
||||
borderRadius: radius.sm,
|
||||
backgroundColor: c.surface,
|
||||
padding: spacing.md,
|
||||
gap: spacing.sm,
|
||||
},
|
||||
row: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
|
||||
rowLabel: { ...typography.body, color: c.textSecondary },
|
||||
muted: { ...typography.caption, color: c.textMuted, flexShrink: 1 },
|
||||
|
||||
numberInput: {
|
||||
minWidth: 52,
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: spacing.xs,
|
||||
borderRadius: radius.xs,
|
||||
borderWidth: 1,
|
||||
borderColor: c.border,
|
||||
backgroundColor: c.background,
|
||||
color: c.text,
|
||||
...typography.body,
|
||||
textAlign: 'center',
|
||||
},
|
||||
|
||||
selectFlex: { flex: 1, minWidth: 0 },
|
||||
selectButton: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: spacing.xs,
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: spacing.xs,
|
||||
minHeight: 36,
|
||||
borderRadius: radius.xs,
|
||||
borderWidth: 1,
|
||||
borderColor: c.border,
|
||||
backgroundColor: c.background,
|
||||
},
|
||||
selectText: { ...typography.body, color: c.text, flexShrink: 1 },
|
||||
|
||||
popover: {
|
||||
marginTop: spacing.xs,
|
||||
borderWidth: 1,
|
||||
borderColor: c.border,
|
||||
borderRadius: radius.xs,
|
||||
backgroundColor: c.background,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
popoverRow: {
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: c.borderLight,
|
||||
},
|
||||
popoverRowActive: { backgroundColor: c.primaryBg },
|
||||
popoverRowText: { ...typography.body, color: c.text },
|
||||
|
||||
weekdayRow: { flexDirection: 'row', gap: 4 },
|
||||
weekdayChip: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
paddingVertical: spacing.xs,
|
||||
borderRadius: radius.xs,
|
||||
borderWidth: 1,
|
||||
borderColor: c.border,
|
||||
alignItems: 'center',
|
||||
},
|
||||
weekdayChipActive: {
|
||||
borderColor: c.primary,
|
||||
backgroundColor: c.primaryBg,
|
||||
},
|
||||
weekdayChipText: { ...typography.caption, color: c.textMuted },
|
||||
weekdayChipTextActive: { color: c.primary },
|
||||
|
||||
footer: {
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: c.border,
|
||||
paddingTop: spacing.sm,
|
||||
gap: spacing.sm,
|
||||
},
|
||||
summary: { ...typography.caption, color: c.textMuted },
|
||||
footerButtons: { flexDirection: 'row', justifyContent: 'flex-end', gap: spacing.sm },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Modal,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
Text,
|
||||
TextInput,
|
||||
TouchableWithoutFeedback,
|
||||
View,
|
||||
} from 'react-native';
|
||||
import { Folder, FileText, Trash2, UserPlus, Users } from 'lucide-react-native';
|
||||
|
||||
import { getPrincipals, isFolder, ownPrincipalId, setFileNodeShare } from '../../api/files';
|
||||
import type { FileNode, FileNodeRights, Principal } from '../../api/types';
|
||||
import { spacing, radius, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
|
||||
type RolePreset = 'read' | 'readWrite' | 'manager';
|
||||
|
||||
// Same presets the webmail's share dialog offers (#408). "custom" rights set
|
||||
// by another client are shown as-is and left untouched until the user picks a
|
||||
// preset for that principal.
|
||||
const FILE_PRESETS: Record<RolePreset, FileNodeRights> = {
|
||||
read: {
|
||||
mayRead: true, mayAddChildren: false, mayRename: false,
|
||||
mayDelete: false, mayModifyContent: false, mayShare: false,
|
||||
},
|
||||
readWrite: {
|
||||
mayRead: true, mayAddChildren: true, mayRename: true,
|
||||
mayDelete: true, mayModifyContent: true, mayShare: false,
|
||||
},
|
||||
manager: {
|
||||
mayRead: true, mayAddChildren: true, mayRename: true,
|
||||
mayDelete: true, mayModifyContent: true, mayShare: true,
|
||||
},
|
||||
};
|
||||
|
||||
const PRESET_LABELS: Record<RolePreset, string> = {
|
||||
read: 'Viewer',
|
||||
readWrite: 'Editor',
|
||||
manager: 'Manager',
|
||||
};
|
||||
|
||||
const PRESET_ORDER: RolePreset[] = ['read', 'readWrite', 'manager'];
|
||||
|
||||
function detectPreset(rights: FileNodeRights): RolePreset | 'custom' {
|
||||
for (const preset of PRESET_ORDER) {
|
||||
const expected = FILE_PRESETS[preset];
|
||||
const keys = Object.keys(expected) as (keyof FileNodeRights)[];
|
||||
if (keys.every((k) => expected[k] === (rights[k] ?? false))) return preset;
|
||||
}
|
||||
return 'custom';
|
||||
}
|
||||
|
||||
interface ShareSheetProps {
|
||||
node: FileNode | null;
|
||||
onClose: () => void;
|
||||
/** Fired after any successful share change so the parent can refresh. */
|
||||
onChanged: () => void;
|
||||
}
|
||||
|
||||
export default function ShareSheet({ node, onClose, onChanged }: ShareSheetProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
|
||||
const [principals, setPrincipals] = useState<Principal[]>([]);
|
||||
const [loadingPrincipals, setLoadingPrincipals] = useState(false);
|
||||
const [shares, setShares] = useState<Record<string, FileNodeRights>>({});
|
||||
const [search, setSearch] = useState('');
|
||||
const [savingId, setSavingId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!node) return;
|
||||
setShares(node.shareWith ?? {});
|
||||
setSearch('');
|
||||
setLoadingPrincipals(true);
|
||||
getPrincipals()
|
||||
.then(setPrincipals)
|
||||
.catch(() => setPrincipals([]))
|
||||
.finally(() => setLoadingPrincipals(false));
|
||||
}, [node]);
|
||||
|
||||
const principalsById = useMemo(() => {
|
||||
const map = new Map<string, Principal>();
|
||||
for (const p of principals) map.set(p.id, p);
|
||||
return map;
|
||||
}, [principals]);
|
||||
|
||||
const sharedEntries = useMemo(
|
||||
() => Object.entries(shares).filter(([, rights]) => rights != null),
|
||||
[shares],
|
||||
);
|
||||
|
||||
const candidates = useMemo(() => {
|
||||
const self = ownPrincipalId();
|
||||
const q = search.trim().toLowerCase();
|
||||
return principals
|
||||
.filter((p) => p.id !== self && shares[p.id] == null)
|
||||
.filter((p) =>
|
||||
!q ||
|
||||
p.name?.toLowerCase().includes(q) ||
|
||||
p.email?.toLowerCase().includes(q) ||
|
||||
p.description?.toLowerCase().includes(q))
|
||||
.slice(0, 25);
|
||||
}, [principals, shares, search]);
|
||||
|
||||
const applyShare = useCallback(
|
||||
async (principalId: string, rights: FileNodeRights | null) => {
|
||||
if (!node || savingId) return;
|
||||
setSavingId(principalId);
|
||||
try {
|
||||
await setFileNodeShare(node.id, principalId, rights);
|
||||
setShares((prev) => {
|
||||
const next = { ...prev };
|
||||
if (rights == null) delete next[principalId];
|
||||
else next[principalId] = rights;
|
||||
return next;
|
||||
});
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
Alert.alert('Sharing failed', e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setSavingId(null);
|
||||
}
|
||||
},
|
||||
[node, savingId, onChanged],
|
||||
);
|
||||
|
||||
if (!node) return null;
|
||||
const Icon = isFolder(node) ? Folder : FileText;
|
||||
|
||||
const renderPrincipalLabel = (principalId: string) => {
|
||||
const p = principalsById.get(principalId);
|
||||
return (
|
||||
<View style={styles.principalInfo}>
|
||||
<Text style={styles.principalName} numberOfLines={1}>
|
||||
{p?.description || p?.name || principalId}
|
||||
</Text>
|
||||
{p?.email ? (
|
||||
<Text style={styles.principalEmail} numberOfLines={1}>
|
||||
{p.email}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal visible transparent animationType="slide" onRequestClose={onClose}>
|
||||
<TouchableWithoutFeedback onPress={onClose}>
|
||||
<View style={styles.backdrop}>
|
||||
<TouchableWithoutFeedback>
|
||||
<View style={styles.sheet}>
|
||||
<View style={styles.titleRow}>
|
||||
<Icon size={18} color={c.textMuted} />
|
||||
<Text style={styles.title} numberOfLines={1}>
|
||||
Share “{node.name}”
|
||||
</Text>
|
||||
</View>
|
||||
{isFolder(node) ? (
|
||||
<Text style={styles.subtitle}>
|
||||
Sharing a folder shares everything inside it.
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
<ScrollView
|
||||
style={styles.scroll}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
>
|
||||
{sharedEntries.length > 0 ? (
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionLabel}>Shared with</Text>
|
||||
{sharedEntries.map(([principalId, rights]) => {
|
||||
const preset = detectPreset(rights);
|
||||
const busy = savingId === principalId;
|
||||
return (
|
||||
<View key={principalId} style={styles.shareRow}>
|
||||
{renderPrincipalLabel(principalId)}
|
||||
<View style={styles.roleChips}>
|
||||
{PRESET_ORDER.map((p) => (
|
||||
<Pressable
|
||||
key={p}
|
||||
onPress={() => void applyShare(principalId, FILE_PRESETS[p])}
|
||||
disabled={busy}
|
||||
style={[styles.chip, preset === p && styles.chipActive]}
|
||||
>
|
||||
<Text
|
||||
style={[styles.chipText, preset === p && styles.chipTextActive]}
|
||||
>
|
||||
{PRESET_LABELS[p]}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
{preset === 'custom' ? (
|
||||
<Text style={styles.customLabel}>Custom</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{busy ? (
|
||||
<ActivityIndicator size="small" color={c.textMuted} />
|
||||
) : (
|
||||
<Pressable
|
||||
onPress={() => void applyShare(principalId, null)}
|
||||
hitSlop={8}
|
||||
accessibilityLabel="Remove access"
|
||||
>
|
||||
<Trash2 size={18} color={c.error} />
|
||||
</Pressable>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
) : (
|
||||
<View style={styles.emptyRow}>
|
||||
<Users size={18} color={c.textMuted} />
|
||||
<Text style={styles.emptyText}>Not shared with anyone yet</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionLabel}>Add people</Text>
|
||||
<TextInput
|
||||
value={search}
|
||||
onChangeText={setSearch}
|
||||
placeholder="Search by name or email"
|
||||
placeholderTextColor={c.textMuted}
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
{loadingPrincipals ? (
|
||||
<ActivityIndicator
|
||||
size="small"
|
||||
color={c.textMuted}
|
||||
style={{ marginTop: spacing.sm }}
|
||||
/>
|
||||
) : candidates.length === 0 ? (
|
||||
<Text style={styles.noMatches}>
|
||||
{principals.length === 0 ? 'No other users found' : 'No matches'}
|
||||
</Text>
|
||||
) : (
|
||||
candidates.map((p) => (
|
||||
<Pressable
|
||||
key={p.id}
|
||||
onPress={() => void applyShare(p.id, FILE_PRESETS.read)}
|
||||
disabled={savingId != null}
|
||||
style={({ pressed }) => [
|
||||
styles.candidateRow,
|
||||
pressed && { backgroundColor: c.surfaceHover },
|
||||
]}
|
||||
>
|
||||
{renderPrincipalLabel(p.id)}
|
||||
{savingId === p.id ? (
|
||||
<ActivityIndicator size="small" color={c.textMuted} />
|
||||
) : (
|
||||
<UserPlus size={18} color={c.primary} />
|
||||
)}
|
||||
</Pressable>
|
||||
))
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
|
||||
<Pressable onPress={onClose} style={styles.doneBtn}>
|
||||
<Text style={styles.doneText}>Done</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</TouchableWithoutFeedback>
|
||||
</View>
|
||||
</TouchableWithoutFeedback>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
backdrop: {
|
||||
flex: 1,
|
||||
backgroundColor: 'rgba(0,0,0,0.5)',
|
||||
justifyContent: 'flex-end',
|
||||
},
|
||||
sheet: {
|
||||
backgroundColor: c.background,
|
||||
borderTopLeftRadius: radius.lg,
|
||||
borderTopRightRadius: radius.lg,
|
||||
paddingTop: spacing.md,
|
||||
paddingBottom: spacing.xxl,
|
||||
paddingHorizontal: spacing.md,
|
||||
maxHeight: '80%',
|
||||
},
|
||||
titleRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
paddingHorizontal: spacing.sm,
|
||||
},
|
||||
title: {
|
||||
...typography.h3,
|
||||
color: c.text,
|
||||
flexShrink: 1,
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: typography.caption.fontSize,
|
||||
color: c.textMuted,
|
||||
paddingHorizontal: spacing.sm,
|
||||
marginTop: 2,
|
||||
},
|
||||
scroll: {
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
section: {
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
sectionLabel: {
|
||||
fontSize: typography.caption.fontSize,
|
||||
fontWeight: '600' as const,
|
||||
color: c.textMuted,
|
||||
textTransform: 'uppercase' as const,
|
||||
paddingHorizontal: spacing.sm,
|
||||
marginBottom: spacing.xs,
|
||||
},
|
||||
shareRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: spacing.sm,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: c.border,
|
||||
},
|
||||
principalInfo: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
principalName: {
|
||||
fontSize: typography.body.fontSize,
|
||||
color: c.text,
|
||||
},
|
||||
principalEmail: {
|
||||
fontSize: typography.caption.fontSize,
|
||||
color: c.textMuted,
|
||||
},
|
||||
roleChips: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.xs,
|
||||
},
|
||||
chip: {
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: 4,
|
||||
borderRadius: radius.sm,
|
||||
borderWidth: 1,
|
||||
borderColor: c.border,
|
||||
},
|
||||
chipActive: {
|
||||
backgroundColor: c.primaryBg,
|
||||
borderColor: c.primary,
|
||||
},
|
||||
chipText: {
|
||||
fontSize: typography.caption.fontSize,
|
||||
color: c.textMuted,
|
||||
},
|
||||
chipTextActive: {
|
||||
color: c.primary,
|
||||
fontWeight: '600' as const,
|
||||
},
|
||||
customLabel: {
|
||||
fontSize: typography.caption.fontSize,
|
||||
color: c.textMuted,
|
||||
fontStyle: 'italic' as const,
|
||||
},
|
||||
emptyRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
emptyText: {
|
||||
fontSize: typography.body.fontSize,
|
||||
color: c.textMuted,
|
||||
},
|
||||
input: {
|
||||
borderWidth: 1,
|
||||
borderColor: c.border,
|
||||
borderRadius: radius.md,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm,
|
||||
color: c.text,
|
||||
fontSize: typography.body.fontSize,
|
||||
backgroundColor: c.surface,
|
||||
marginHorizontal: spacing.sm,
|
||||
},
|
||||
noMatches: {
|
||||
fontSize: typography.caption.fontSize,
|
||||
color: c.textMuted,
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: spacing.sm,
|
||||
},
|
||||
candidateRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: spacing.sm,
|
||||
borderRadius: radius.md,
|
||||
},
|
||||
doneBtn: {
|
||||
marginTop: spacing.md,
|
||||
alignSelf: 'stretch',
|
||||
alignItems: 'center',
|
||||
paddingVertical: spacing.sm,
|
||||
borderRadius: radius.md,
|
||||
backgroundColor: c.primary,
|
||||
},
|
||||
doneText: {
|
||||
color: c.primaryForeground,
|
||||
fontWeight: '600' as const,
|
||||
fontSize: typography.body.fontSize,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -5,3 +5,5 @@ export { default as Badge } from './Badge';
|
||||
export { Card, SectionHeader, SettingItemRow } from './Card';
|
||||
export { default as RadioGroup } from './RadioGroup';
|
||||
export { default as Dialog } from './Dialog';
|
||||
export { IdentitySheet } from './IdentitySheet';
|
||||
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
normalizeAllDayDuration,
|
||||
buildAllDayDuration,
|
||||
getCalendarColor,
|
||||
getEventStartDate,
|
||||
getEventEndDate,
|
||||
timePattern,
|
||||
layoutOverlappingEvents,
|
||||
CALENDAR_COLOR_PALETTE,
|
||||
} from '../calendar-utils';
|
||||
@@ -51,6 +54,32 @@ describe('parseLocalDateTime', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getEventStartDate / getEventEndDate malformed utc fallback', () => {
|
||||
// Mirrors webmail (#316): a malformed utcStart/utcEnd must fall back to the
|
||||
// floating `start` + duration instead of producing an Invalid Date, which
|
||||
// would silently drop the event from the day index and every view.
|
||||
it('falls back to start when utcStart is unparseable', () => {
|
||||
const d = getEventStartDate(ev({ utcStart: 'garbage' }));
|
||||
expect(isNaN(d.getTime())).toBe(false);
|
||||
expect(d.getHours()).toBe(9);
|
||||
});
|
||||
|
||||
it('falls back to start + duration when utcEnd is unparseable', () => {
|
||||
const end = getEventEndDate(ev({ utcEnd: 'garbage', duration: 'PT1H' }));
|
||||
expect(isNaN(end.getTime())).toBe(false);
|
||||
const start = getEventStartDate(ev({}));
|
||||
expect(end.getTime() - start.getTime()).toBe(60 * 60 * 1000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('timePattern', () => {
|
||||
it('maps 12h to an am/pm pattern and 24h (or undefined) to HH:mm', () => {
|
||||
expect(timePattern('12h')).toBe('h:mm a');
|
||||
expect(timePattern('24h')).toBe('HH:mm');
|
||||
expect(timePattern(undefined)).toBe('HH:mm');
|
||||
});
|
||||
});
|
||||
|
||||
describe('eventTimeRange', () => {
|
||||
it('returns start, end, allDay for a timed event with utcStart/utcEnd', () => {
|
||||
const range = eventTimeRange(ev({
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildEditorHtml } from '../editor-html';
|
||||
import { LIGHT_COLORS, DARK_COLORS } from '../../theme/tokens';
|
||||
|
||||
function extractScript(html: string): string {
|
||||
const m = html.match(/<script>([\s\S]*?)<\/script>/);
|
||||
expect(m, 'page must contain an inline <script>').toBeTruthy();
|
||||
return m![1];
|
||||
}
|
||||
|
||||
describe('buildEditorHtml', () => {
|
||||
const base = { initialHtml: '<p><br></p>', placeholder: 'Write…', c: LIGHT_COLORS };
|
||||
|
||||
// Regression for issue #11: backslash escapes inside the template literal
|
||||
// are cooked away (`\/` → `/`), which once emitted an invalid regex. That
|
||||
// SyntaxError killed the entire inline script, so the editor never posted
|
||||
// `change` messages and Send stayed disabled on Android/iOS.
|
||||
it('emits an inline script that parses as valid JavaScript', () => {
|
||||
for (const c of [LIGHT_COLORS, DARK_COLORS]) {
|
||||
const script = extractScript(buildEditorHtml({ ...base, c }));
|
||||
// new Function() parses without executing (script needs a DOM to run).
|
||||
expect(() => new Function(script)).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('emits no cooked-away backslashes in the script', () => {
|
||||
// The page script is written escape-free on purpose; a backslash-free
|
||||
// source cannot silently lose escapes to template-literal cooking.
|
||||
const script = extractScript(buildEditorHtml(base));
|
||||
expect(script).not.toContain('\\');
|
||||
});
|
||||
|
||||
it('embeds initial content and placeholder as JSON strings', () => {
|
||||
const html = buildEditorHtml({
|
||||
...base,
|
||||
initialHtml: '<p>He said "hi" & left</p>',
|
||||
placeholder: 'Say "something"…',
|
||||
});
|
||||
expect(html).toContain(JSON.stringify('<p>He said "hi" & left</p>'));
|
||||
expect(html).toContain(`data-placeholder=${JSON.stringify('Say "something"…')}`);
|
||||
});
|
||||
|
||||
it('keeps the editor contenteditable and the bridge object wiring', () => {
|
||||
const html = buildEditorHtml(base);
|
||||
expect(html).toContain('<div id="editor" contenteditable="true"');
|
||||
const script = extractScript(html);
|
||||
expect(script).toContain('window.__rne');
|
||||
expect(script).toContain('ReactNativeWebView.postMessage');
|
||||
});
|
||||
|
||||
// Regression for issue #9: sends must be able to read the live DOM back
|
||||
// instead of trusting async `change` messages that can lag or be lost.
|
||||
it('exposes the send-time getHtml readback on the bridge', () => {
|
||||
const script = extractScript(buildEditorHtml(base));
|
||||
expect(script).toContain('getHtml: function (id)');
|
||||
expect(script).toContain("post('htmlSnapshot', { id: id, html: editor.innerHTML })");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describeLoginError } from '../login-errors';
|
||||
|
||||
function named(name: string, message: string): Error {
|
||||
const err = new Error(message);
|
||||
err.name = name;
|
||||
return err;
|
||||
}
|
||||
|
||||
describe('describeLoginError', () => {
|
||||
it('turns a rejected credential into an actionable message', () => {
|
||||
const copy = describeLoginError(named('AuthenticationError', 'Invalid credentials'));
|
||||
expect(copy.title).toBe("That didn't work");
|
||||
expect(copy.detail).toMatch(/app password/i);
|
||||
});
|
||||
|
||||
it('names the host it could not reach', () => {
|
||||
const copy = describeLoginError(named('NetworkError', 'Network request failed'), {
|
||||
serverUrl: 'https://mail.example.com',
|
||||
});
|
||||
expect(copy.title).toBe("Can't reach mail.example.com");
|
||||
});
|
||||
|
||||
it('falls back to a generic host label when the server is unknown', () => {
|
||||
const copy = describeLoginError(named('TypeError', 'Network request failed'));
|
||||
expect(copy.title).toBe("Can't reach the server");
|
||||
});
|
||||
|
||||
it('explains a 404 from session discovery as a wrong address', () => {
|
||||
const copy = describeLoginError(new Error('Session discovery failed: 404 Not Found'), {
|
||||
serverUrl: 'https://example.com',
|
||||
});
|
||||
expect(copy.title).toBe('No mail server at example.com');
|
||||
});
|
||||
|
||||
it('flags a certificate problem separately from a connection problem', () => {
|
||||
const copy = describeLoginError(new Error('SSL certificate has expired'), {
|
||||
serverUrl: 'https://mail.example.com',
|
||||
});
|
||||
expect(copy.title).toBe("Couldn't verify mail.example.com");
|
||||
});
|
||||
|
||||
it('explains an expired pairing code', () => {
|
||||
const copy = describeLoginError(new Error('Pairing code is invalid or has expired'));
|
||||
expect(copy.title).toBe('That code has expired');
|
||||
expect(copy.detail).toMatch(/fresh one/i);
|
||||
});
|
||||
|
||||
it('passes through an unrecognised message rather than inventing a cause', () => {
|
||||
const copy = describeLoginError(new Error('Teapot refused to brew'));
|
||||
expect(copy.title).toBe('Sign-in failed');
|
||||
expect(copy.detail).toBe('Teapot refused to brew');
|
||||
});
|
||||
|
||||
it('handles non-Error throws', () => {
|
||||
expect(describeLoginError(undefined).title).toBe('Sign-in failed');
|
||||
expect(describeLoginError('boom').detail).toBe('boom');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { mockSecureFetch } = vi.hoisted(() => ({
|
||||
mockSecureFetch: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../client-cert', () => ({
|
||||
secureFetch: mockSecureFetch,
|
||||
}));
|
||||
|
||||
import { refreshOAuthAccessToken, type OAuthTokens } from '../oauth';
|
||||
|
||||
describe('oauth token refresh deduplication', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should only send a single HTTP request when refreshOAuthAccessToken is called concurrently with the same refresh token', async () => {
|
||||
const tokens: OAuthTokens = {
|
||||
accessToken: 'old-access',
|
||||
refreshToken: 'same-refresh-token',
|
||||
expiresAt: 123456,
|
||||
tokenEndpoint: 'https://auth.example.com/token',
|
||||
clientId: 'client-id-123',
|
||||
};
|
||||
|
||||
// Set up a mock response that takes a brief moment to resolve
|
||||
mockSecureFetch.mockImplementation(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
access_token: 'new-access-token',
|
||||
refresh_token: 'rotated-refresh-token',
|
||||
expires_in: 3600,
|
||||
}),
|
||||
} as Response;
|
||||
});
|
||||
|
||||
// Fire two refreshes concurrently
|
||||
const [res1, res2] = await Promise.all([
|
||||
refreshOAuthAccessToken(tokens),
|
||||
refreshOAuthAccessToken(tokens),
|
||||
]);
|
||||
|
||||
// Check that secureFetch was called exactly once
|
||||
expect(mockSecureFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Verify both calls received the exact same updated token bundle
|
||||
expect(res1.accessToken).toBe('new-access-token');
|
||||
expect(res1.refreshToken).toBe('rotated-refresh-token');
|
||||
expect(res2.accessToken).toBe('new-access-token');
|
||||
expect(res2.refreshToken).toBe('rotated-refresh-token');
|
||||
|
||||
// Fire another refresh after the first completes (now the map should be empty for this token)
|
||||
mockSecureFetch.mockClear();
|
||||
const res3 = await refreshOAuthAccessToken(tokens);
|
||||
expect(mockSecureFetch).toHaveBeenCalledTimes(1);
|
||||
expect(res3.accessToken).toBe('new-access-token');
|
||||
});
|
||||
|
||||
it('should propagate errors to all waiters if the HTTP request fails', async () => {
|
||||
const tokens: OAuthTokens = {
|
||||
accessToken: 'old-access',
|
||||
refreshToken: 'failing-refresh-token',
|
||||
expiresAt: 123456,
|
||||
tokenEndpoint: 'https://auth.example.com/token',
|
||||
clientId: 'client-id-123',
|
||||
};
|
||||
|
||||
mockSecureFetch.mockImplementation(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
return {
|
||||
ok: false,
|
||||
status: 400,
|
||||
} as Response;
|
||||
});
|
||||
|
||||
// Fire two refreshes concurrently and check that both reject with the same error
|
||||
const promise1 = refreshOAuthAccessToken(tokens);
|
||||
const promise2 = refreshOAuthAccessToken(tokens);
|
||||
|
||||
await expect(promise1).rejects.toThrow('Token refresh failed: 400');
|
||||
await expect(promise2).rejects.toThrow('Token refresh failed: 400');
|
||||
|
||||
expect(mockSecureFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// Provide the Android native FCM surface setupPushNotifications needs. The
|
||||
// global test-setup mocks react-native with an empty NativeModules, so override
|
||||
// it here with a BulwarkFcm module and a pre-33 Platform.Version (which skips
|
||||
// the runtime permission request).
|
||||
vi.mock('react-native', () => {
|
||||
class NativeEventEmitter {
|
||||
addListener() {
|
||||
return { remove: () => undefined };
|
||||
}
|
||||
}
|
||||
return {
|
||||
Platform: { OS: 'android', Version: 30, select: <T,>(s: { default?: T; android?: T }) => s.android ?? s.default },
|
||||
NativeModules: {
|
||||
BulwarkFcm: {
|
||||
getToken: vi.fn(async () => 'fcm-token-xyz'),
|
||||
deleteToken: vi.fn(async () => undefined),
|
||||
},
|
||||
},
|
||||
NativeEventEmitter,
|
||||
PermissionsAndroid: { RESULTS: { GRANTED: 'granted' }, request: vi.fn(async () => 'granted') },
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../api/jmap-client', () => ({
|
||||
jmapClient: { username: 'user@example.com', serverUrl: 'https://mail.example.com' },
|
||||
}));
|
||||
|
||||
vi.mock('../../api/push', () => ({
|
||||
listPushSubscriptions: vi.fn(async () => []),
|
||||
createPushSubscription: vi.fn(async () => 'new-server-id'),
|
||||
verifyPushSubscription: vi.fn(async () => undefined),
|
||||
destroyPushSubscription: vi.fn(async () => undefined),
|
||||
updatePushSubscription: vi.fn(async () => true),
|
||||
}));
|
||||
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { setupPushNotifications, deviceClientIdKey } from '../push-notifications';
|
||||
import {
|
||||
listPushSubscriptions,
|
||||
createPushSubscription,
|
||||
destroyPushSubscription,
|
||||
} from '../../api/push';
|
||||
import { generateAccountId } from '../account-utils';
|
||||
|
||||
const OUR_DCID = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
|
||||
const ACCOUNT_ID = generateAccountId('user@example.com', 'https://mail.example.com');
|
||||
const RELAY = 'https://relay.example.com';
|
||||
|
||||
// State the fake relay reports for each foreign deviceClientId's /active probe.
|
||||
type RelayState = 'dead' | 'live' | 'unknown';
|
||||
|
||||
function installFetch(states: Record<string, RelayState>): void {
|
||||
global.fetch = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = typeof input === 'string' ? input : input.toString();
|
||||
if (url.includes('/api/push/register')) {
|
||||
return { ok: true, status: 200, json: async () => ({ ok: true }) } as Response;
|
||||
}
|
||||
if (url.includes('/api/push/verify/')) {
|
||||
return { ok: true, status: 200, json: async () => ({ verificationCode: 'CODE' }) } as Response;
|
||||
}
|
||||
const active = url.match(/\/api\/push\/active\/([^/?]+)$/);
|
||||
if (active) {
|
||||
const dcid = decodeURIComponent(active[1]);
|
||||
const state = states[dcid] ?? 'unknown';
|
||||
if (state === 'unknown') {
|
||||
return { ok: false, status: 404, json: async () => ({ error: 'Unknown subscription' }) } as Response;
|
||||
}
|
||||
return { ok: true, status: 200, json: async () => ({ active: state === 'live' }) } as Response;
|
||||
}
|
||||
throw new Error(`unexpected fetch: ${url}`);
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
const destroyMock = destroyPushSubscription as ReturnType<typeof vi.fn>;
|
||||
const listMock = listPushSubscriptions as ReturnType<typeof vi.fn>;
|
||||
const createMock = createPushSubscription as ReturnType<typeof vi.fn>;
|
||||
|
||||
function sub(id: string, deviceClientId: string) {
|
||||
return { id, deviceClientId, expires: new Date(Date.now() + 86400000).toISOString(), types: ['Email'] };
|
||||
}
|
||||
|
||||
describe('setupPushNotifications leftover reaping', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
await AsyncStorage.clear();
|
||||
// Pin our deviceClientId so we control which leftovers are "ours".
|
||||
await AsyncStorage.setItem(deviceClientIdKey(ACCOUNT_ID), OUR_DCID);
|
||||
});
|
||||
|
||||
it('reaps our own and relay-confirmed-dead leftovers, keeps live and unverifiable ones', async () => {
|
||||
listMock.mockResolvedValue([
|
||||
sub('own-old', OUR_DCID), // our own previous attempt -> reap
|
||||
sub('foreign-dead', 'deaddeaddeaddeaddeaddeaddeaddead'), // relay: dead -> reap
|
||||
sub('foreign-live', 'livelivelivelivelivelivelivelive'), // relay: live -> keep
|
||||
sub('foreign-unknown', 'unknwunknwunknwunknwunknwunknwun'), // relay: 404 -> keep
|
||||
]);
|
||||
installFetch({
|
||||
deaddeaddeaddeaddeaddeaddeaddead: 'dead',
|
||||
livelivelivelivelivelivelivelive: 'live',
|
||||
unknwunknwunknwunknwunknwunknwun: 'unknown',
|
||||
});
|
||||
|
||||
const result = await setupPushNotifications({ relayBaseUrl: RELAY });
|
||||
|
||||
expect(result.verified).toBe(true);
|
||||
const reaped = destroyMock.mock.calls.map((c) => c[0]);
|
||||
expect(reaped).toContain('own-old');
|
||||
expect(reaped).toContain('foreign-dead');
|
||||
expect(reaped).not.toContain('foreign-live');
|
||||
expect(reaped).not.toContain('foreign-unknown');
|
||||
});
|
||||
|
||||
it('keeps foreign subs when the relay probe fails (network error)', async () => {
|
||||
listMock.mockResolvedValue([sub('foreign-x', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')]);
|
||||
global.fetch = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = typeof input === 'string' ? input : input.toString();
|
||||
if (url.includes('/api/push/register')) {
|
||||
return { ok: true, status: 200, json: async () => ({ ok: true }) } as Response;
|
||||
}
|
||||
if (url.includes('/api/push/verify/')) {
|
||||
return { ok: true, status: 200, json: async () => ({ verificationCode: 'CODE' }) } as Response;
|
||||
}
|
||||
if (url.includes('/api/push/active/')) throw new Error('network down');
|
||||
throw new Error(`unexpected fetch: ${url}`);
|
||||
}) as typeof fetch;
|
||||
|
||||
await setupPushNotifications({ relayBaseUrl: RELAY });
|
||||
|
||||
expect(destroyMock.mock.calls.map((c) => c[0])).not.toContain('foreign-x');
|
||||
});
|
||||
|
||||
it('coalesces concurrent setups into a single flow (no subscription swarm)', async () => {
|
||||
listMock.mockResolvedValue([]);
|
||||
installFetch({});
|
||||
|
||||
// Fire several overlapping setups, as App.tsx does while auth settles and
|
||||
// on FCM token refresh. Only one underlying JMAP subscription must be made.
|
||||
const results = await Promise.all([
|
||||
setupPushNotifications({ relayBaseUrl: RELAY }),
|
||||
setupPushNotifications({ relayBaseUrl: RELAY }),
|
||||
setupPushNotifications({ relayBaseUrl: RELAY }),
|
||||
]);
|
||||
|
||||
expect(createMock).toHaveBeenCalledTimes(1);
|
||||
expect(new Set(results.map((r) => r.subscriptionId)).size).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -74,6 +74,54 @@ describe('expandRecurringEvents - weekly', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('expandRecurringEvents - interval > 1 (#13)', () => {
|
||||
it('expands an every-5-weeks rule', () => {
|
||||
const rule: RecurrenceRule = { frequency: 'weekly', interval: 5 };
|
||||
const result = expandRecurringEvents(
|
||||
[ev({ recurrenceRules: [rule] })], // starts Mon 2026-04-06
|
||||
'2026-04-01T00:00:00',
|
||||
'2026-08-01T00:00:00',
|
||||
);
|
||||
expect(result.map((e) => e.start)).toEqual([
|
||||
'2026-04-06T09:00:00',
|
||||
'2026-05-11T09:00:00',
|
||||
'2026-06-15T09:00:00',
|
||||
'2026-07-20T09:00:00',
|
||||
]);
|
||||
});
|
||||
|
||||
it('expands an every-5-weeks series started long before the visible range', () => {
|
||||
const event = ev({
|
||||
start: '2025-01-06T09:00:00', // Monday
|
||||
recurrenceRules: [{ frequency: 'weekly', interval: 5 }],
|
||||
});
|
||||
// Occurrences fall every 35 days from 2025-01-06 (…2026-04-06, 05-11,
|
||||
// 06-15, 07-20…) — only those inside the window are returned.
|
||||
const result = expandRecurringEvents([event], '2026-05-01T00:00:00', '2026-08-01T00:00:00');
|
||||
expect(result.map((e) => e.start)).toEqual([
|
||||
'2026-05-11T09:00:00',
|
||||
'2026-06-15T09:00:00',
|
||||
'2026-07-20T09:00:00',
|
||||
]);
|
||||
});
|
||||
|
||||
it('expands an every-2-months rule', () => {
|
||||
const rule: RecurrenceRule = { frequency: 'monthly', interval: 2 };
|
||||
const result = expandRecurringEvents(
|
||||
[ev({ recurrenceRules: [rule] })],
|
||||
'2026-04-01T00:00:00',
|
||||
'2026-12-31T00:00:00',
|
||||
);
|
||||
expect(result.map((e) => e.start)).toEqual([
|
||||
'2026-04-06T09:00:00',
|
||||
'2026-06-06T09:00:00',
|
||||
'2026-08-06T09:00:00',
|
||||
'2026-10-06T09:00:00',
|
||||
'2026-12-06T09:00:00',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('expandRecurringEvents - monthly', () => {
|
||||
it('expands monthly on the 6th', () => {
|
||||
const rule: RecurrenceRule = { frequency: 'monthly', count: 3 };
|
||||
@@ -174,3 +222,77 @@ describe('expandRecurringEvents - range filtering', () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('expandRecurringEvents - excludedRecurrenceRules', () => {
|
||||
it('removes occurrences generated by excluded rules', () => {
|
||||
const event = ev({
|
||||
start: '2025-01-06T09:00:00',
|
||||
recurrenceRules: [{ frequency: 'daily' }],
|
||||
excludedRecurrenceRules: [{
|
||||
frequency: 'weekly',
|
||||
byDay: [{ day: 'tu' }],
|
||||
}],
|
||||
});
|
||||
// Jan 6-12 2025: Mon-Sun, Tuesday Jan 7 excluded
|
||||
const result = expandRecurringEvents([event], '2025-01-06T00:00:00', '2025-01-13T00:00:00');
|
||||
const days = result.map((e) => e.start.substring(0, 10));
|
||||
expect(days).not.toContain('2025-01-07');
|
||||
expect(days).toContain('2025-01-06');
|
||||
expect(days).toContain('2025-01-08');
|
||||
expect(result).toHaveLength(6);
|
||||
});
|
||||
});
|
||||
|
||||
describe('expandRecurringEvents - long-running series', () => {
|
||||
it('expands a daily series started years before the visible range', () => {
|
||||
const event = ev({
|
||||
start: '2022-01-03T09:00:00',
|
||||
recurrenceRules: [{ frequency: 'daily' }],
|
||||
});
|
||||
const result = expandRecurringEvents([event], '2025-06-02T00:00:00', '2025-06-05T00:00:00');
|
||||
expect(result.map((e) => e.start)).toEqual([
|
||||
'2025-06-02T09:00:00',
|
||||
'2025-06-03T09:00:00',
|
||||
'2025-06-04T09:00:00',
|
||||
]);
|
||||
});
|
||||
|
||||
it('expands a weekly series started years before the visible range', () => {
|
||||
const event = ev({
|
||||
start: '2020-01-06T09:00:00', // Monday
|
||||
recurrenceRules: [{ frequency: 'weekly' }],
|
||||
});
|
||||
const result = expandRecurringEvents([event], '2025-06-01T00:00:00', '2025-06-30T00:00:00');
|
||||
const days = result.map((e) => e.start.substring(0, 10));
|
||||
expect(days).toEqual(['2025-06-02', '2025-06-09', '2025-06-16', '2025-06-23']);
|
||||
});
|
||||
|
||||
it('still respects count for old series (no fast-forward shortcut)', () => {
|
||||
const event = ev({
|
||||
start: '2025-01-06T09:00:00',
|
||||
recurrenceRules: [{ frequency: 'daily', count: 5 }],
|
||||
});
|
||||
// Range far after the 5 occurrences ran out
|
||||
const result = expandRecurringEvents([event], '2025-06-01T00:00:00', '2025-06-30T00:00:00');
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('expandRecurringEvents - event timezone DST handling', () => {
|
||||
it('keeps wall time across a DST transition in the event timezone', () => {
|
||||
// America/New_York: EST (UTC-5) until 2025-03-09, EDT (UTC-4) after
|
||||
const event = ev({
|
||||
start: '2025-03-03T10:00:00',
|
||||
timeZone: 'America/New_York',
|
||||
utcStart: '2025-03-03T15:00:00Z',
|
||||
utcEnd: '2025-03-03T16:00:00Z',
|
||||
recurrenceRules: [{ frequency: 'weekly' }],
|
||||
});
|
||||
const result = expandRecurringEvents([event], '2025-03-03T00:00:00', '2025-03-17T00:00:00');
|
||||
const utcStarts = result.map((e) => e.utcStart);
|
||||
expect(utcStarts[0]).toBe('2025-03-03T15:00:00.000Z'); // EST: 10:00 -5
|
||||
expect(utcStarts[1]).toBe('2025-03-10T14:00:00.000Z'); // EDT: 10:00 -4
|
||||
const utcEnds = result.map((e) => e.utcEnd);
|
||||
expect(utcEnds[1]).toBe('2025-03-10T15:00:00.000Z');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { mockSecureFetch } = vi.hoisted(() => ({
|
||||
mockSecureFetch: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../client-cert', () => ({
|
||||
secureFetch: mockSecureFetch,
|
||||
}));
|
||||
|
||||
import {
|
||||
normalizeServerUrl,
|
||||
emailDomain,
|
||||
isEmailAddress,
|
||||
serverCandidates,
|
||||
probeJmapServer,
|
||||
discoverServerForEmail,
|
||||
} from '../server-discovery';
|
||||
|
||||
const SESSION_DOC = { capabilities: {}, apiUrl: '/jmap/', primaryAccounts: {} };
|
||||
|
||||
/**
|
||||
* Answers `status` for the listed base URLs and rejects everything else. A 200
|
||||
* yields a JMAP session document unless a body is given explicitly.
|
||||
*/
|
||||
function respondFor(statuses: Record<string, number | { status: number; body: unknown }>) {
|
||||
mockSecureFetch.mockImplementation(async (url: string) => {
|
||||
const base = url.replace(/\/\.well-known\/jmap$/, '');
|
||||
const entry = statuses[base];
|
||||
if (entry === undefined) throw new TypeError('Network request failed');
|
||||
const { status, body } =
|
||||
typeof entry === 'number' ? { status: entry, body: SESSION_DOC } : entry;
|
||||
return { status, json: async () => body } as Response;
|
||||
});
|
||||
}
|
||||
|
||||
describe('normalizeServerUrl', () => {
|
||||
it('adds https:// to a bare host', () => {
|
||||
expect(normalizeServerUrl('mail.example.com')).toBe('https://mail.example.com');
|
||||
});
|
||||
|
||||
it('strips trailing slashes', () => {
|
||||
expect(normalizeServerUrl('https://mail.example.com//')).toBe('https://mail.example.com');
|
||||
});
|
||||
|
||||
it('strips a pasted JMAP session endpoint', () => {
|
||||
expect(normalizeServerUrl('https://mail.example.com/.well-known/jmap')).toBe(
|
||||
'https://mail.example.com',
|
||||
);
|
||||
expect(normalizeServerUrl('mail.example.com/jmap')).toBe('https://mail.example.com');
|
||||
});
|
||||
|
||||
it('keeps an explicit http scheme and port', () => {
|
||||
expect(normalizeServerUrl('http://localhost:8080')).toBe('http://localhost:8080');
|
||||
});
|
||||
|
||||
it('rejects non-http schemes', () => {
|
||||
expect(normalizeServerUrl('ftp://mail.example.com')).toBeNull();
|
||||
expect(normalizeServerUrl('bulwarkmail://connect')).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects input that is not a host', () => {
|
||||
expect(normalizeServerUrl('')).toBeNull();
|
||||
expect(normalizeServerUrl(' ')).toBeNull();
|
||||
expect(normalizeServerUrl('not a host')).toBeNull();
|
||||
expect(normalizeServerUrl('ada@example.com')).toBeNull();
|
||||
// A single label can't be a public host — except localhost.
|
||||
expect(normalizeServerUrl('example')).toBeNull();
|
||||
expect(normalizeServerUrl('localhost')).toBe('https://localhost');
|
||||
});
|
||||
});
|
||||
|
||||
describe('emailDomain', () => {
|
||||
it('extracts and lowercases the domain', () => {
|
||||
expect(emailDomain('Ada@Example.COM')).toBe('example.com');
|
||||
});
|
||||
|
||||
it('rejects anything that is not an address', () => {
|
||||
expect(emailDomain('ada')).toBeNull();
|
||||
expect(emailDomain('ada@localhost')).toBeNull();
|
||||
expect(emailDomain('a@b@example.com')).toBeNull();
|
||||
expect(isEmailAddress('ada@example.com')).toBe(true);
|
||||
expect(isEmailAddress('ada')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('serverCandidates', () => {
|
||||
it('orders the bare domain ahead of the conventional subdomains', () => {
|
||||
expect(serverCandidates('example.com')).toEqual([
|
||||
'https://example.com',
|
||||
'https://mail.example.com',
|
||||
'https://webmail.example.com',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('probeJmapServer', () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it('treats 200 as a hit', async () => {
|
||||
respondFor({ 'https://mail.example.com': 200 });
|
||||
await expect(probeJmapServer('https://mail.example.com')).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('treats 401 as a hit — an unauthenticated probe is meant to be rejected', async () => {
|
||||
respondFor({ 'https://mail.example.com': 401 });
|
||||
await expect(probeJmapServer('https://mail.example.com')).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('treats 404 and transport failures as a miss', async () => {
|
||||
respondFor({ 'https://mail.example.com': 404 });
|
||||
await expect(probeJmapServer('https://mail.example.com')).resolves.toBe(false);
|
||||
await expect(probeJmapServer('https://nothing.example.com')).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a 200 that is not a session document', async () => {
|
||||
// A catch-all web server or captive portal answering 200 for every path.
|
||||
respondFor({ 'https://example.com': { status: 200, body: '<!doctype html>' } });
|
||||
await expect(probeJmapServer('https://example.com')).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a 200 whose body is not JSON at all', async () => {
|
||||
mockSecureFetch.mockResolvedValue({
|
||||
status: 200,
|
||||
json: async () => {
|
||||
throw new SyntaxError('Unexpected token <');
|
||||
},
|
||||
} as unknown as Response);
|
||||
await expect(probeJmapServer('https://example.com')).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('gives up at the deadline instead of hanging', async () => {
|
||||
mockSecureFetch.mockImplementation(
|
||||
() => new Promise(() => {/* never settles */}),
|
||||
);
|
||||
await expect(probeJmapServer('https://slow.example.com', 20)).resolves.toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('discoverServerForEmail', () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it('returns a known account server for the same domain without probing', async () => {
|
||||
respondFor({});
|
||||
const found = await discoverServerForEmail('ada@example.com', {
|
||||
knownServerUrls: ['https://mail.example.com'],
|
||||
});
|
||||
expect(found).toBe('https://mail.example.com');
|
||||
expect(mockSecureFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prefers the bare domain when several hosts answer', async () => {
|
||||
respondFor({ 'https://example.com': 401, 'https://mail.example.com': 200 });
|
||||
await expect(discoverServerForEmail('ada@example.com')).resolves.toBe('https://example.com');
|
||||
});
|
||||
|
||||
it('falls back to mail.<domain> when the bare domain is not a JMAP server', async () => {
|
||||
respondFor({ 'https://example.com': 404, 'https://mail.example.com': 401 });
|
||||
await expect(discoverServerForEmail('ada@example.com')).resolves.toBe(
|
||||
'https://mail.example.com',
|
||||
);
|
||||
});
|
||||
|
||||
it('skips a bare domain that only serves a marketing site', async () => {
|
||||
respondFor({
|
||||
'https://example.com': { status: 200, body: '<!doctype html>' },
|
||||
'https://mail.example.com': 200,
|
||||
});
|
||||
await expect(discoverServerForEmail('ada@example.com')).resolves.toBe(
|
||||
'https://mail.example.com',
|
||||
);
|
||||
});
|
||||
|
||||
it('returns null when nothing answers, so the caller can ask', async () => {
|
||||
respondFor({});
|
||||
await expect(discoverServerForEmail('ada@example.org')).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns null without touching the network for a non-address', async () => {
|
||||
respondFor({});
|
||||
await expect(discoverServerForEmail('ada')).resolves.toBeNull();
|
||||
expect(mockSecureFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -35,13 +35,20 @@ export function parseLocalDateTime(iso: string): Date {
|
||||
export function getEventStartDate(
|
||||
event: Pick<CalendarEvent, 'start' | 'utcStart' | 'showWithoutTime'>,
|
||||
): Date {
|
||||
const source = !event.showWithoutTime && event.utcStart ? event.utcStart : event.start;
|
||||
return parseISO(source);
|
||||
// Prefer utcStart for timed events but fall back to start if utcStart is
|
||||
// missing or unparseable — a malformed utcStart used to surface as an
|
||||
// Invalid Date that silently dropped the event from every view (#316).
|
||||
if (!event.showWithoutTime && event.utcStart) {
|
||||
const utc = parseISO(event.utcStart);
|
||||
if (!isNaN(utc.getTime())) return utc;
|
||||
}
|
||||
return parseISO(event.start);
|
||||
}
|
||||
|
||||
export function getEventEndDate(event: CalendarEvent): Date {
|
||||
if (!event.showWithoutTime && event.utcEnd) {
|
||||
return parseISO(event.utcEnd);
|
||||
const utc = parseISO(event.utcEnd);
|
||||
if (!isNaN(utc.getTime())) return utc;
|
||||
}
|
||||
const start = getEventStartDate(event);
|
||||
if (!event.duration) return start;
|
||||
@@ -57,6 +64,17 @@ export function getEventDisplayEndDate(event: CalendarEvent): Date {
|
||||
return subMilliseconds(end, 1);
|
||||
}
|
||||
|
||||
// ─── Time-of-day formatting ──────────────────────────────
|
||||
// Maps the user's 12h/24h preference to a date-fns pattern, matching webmail
|
||||
// (event-card.tsx: `timeFormat === "12h" ? "h:mm a" : "HH:mm"`). Components
|
||||
// thread the `calendarTimeFormat` setting through so the calendar renders
|
||||
// times in the same format the webmail does.
|
||||
export type TimeFormat = '12h' | '24h';
|
||||
|
||||
export function timePattern(timeFormat: TimeFormat | undefined): string {
|
||||
return timeFormat === '12h' ? 'h:mm a' : 'HH:mm';
|
||||
}
|
||||
|
||||
export interface EventTimeRange {
|
||||
start: Date;
|
||||
end: Date;
|
||||
@@ -435,12 +453,63 @@ export function getEventColor(
|
||||
event: Pick<CalendarEvent, 'calendarIds' | 'color'>,
|
||||
calendars: Calendar[],
|
||||
): string {
|
||||
if (event.color) return event.color;
|
||||
const calendarId = Object.keys(event.calendarIds || {})[0];
|
||||
const cal = calendars.find((c) => c.id === calendarId);
|
||||
// A local color override on a shared calendar wins over per-event colors,
|
||||
// so the whole shared calendar paints uniformly in the viewer's chosen hue.
|
||||
if (cal?.colorIsLocalOverride && cal.color) return cal.color;
|
||||
if (event.color) return event.color;
|
||||
return getCalendarColor(cal);
|
||||
}
|
||||
|
||||
// ─── Per-viewer colors for shared calendars (#345) ───────
|
||||
// Shared calendars are recolored locally only: the viewer usually can't write
|
||||
// the owner's calendar, and doing so would recolor it for everyone. Overrides
|
||||
// live in the settings store keyed by sharedCalendarColorKey().
|
||||
|
||||
/**
|
||||
* Stable key for a shared calendar's local color override. Built from the
|
||||
* owning JMAP account + the calendar id so it stays unique across accounts.
|
||||
*/
|
||||
export function sharedCalendarColorKey(
|
||||
cal: Pick<Calendar, 'id' | 'accountId'>,
|
||||
): string {
|
||||
return `${cal.accountId ?? ''}|${cal.id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick a random palette color not present in `usedColors`. Once every palette
|
||||
* entry is taken, fall back to a random palette color (collisions are
|
||||
* unavoidable past CALENDAR_PALETTE.length calendars).
|
||||
*/
|
||||
export function pickUnusedCalendarColor(usedColors: Iterable<string>): string {
|
||||
const used = new Set<string>();
|
||||
for (const c of usedColors) {
|
||||
if (c) used.add(c.toLowerCase());
|
||||
}
|
||||
const available = CALENDAR_PALETTE.filter((c) => !used.has(c.toLowerCase()));
|
||||
const pool = available.length > 0 ? available : CALENDAR_PALETTE;
|
||||
return pool[Math.floor(Math.random() * pool.length)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply each shared calendar's local color override (per-viewer recolor).
|
||||
* The override replaces the calendar's color and wins over per-event colors
|
||||
* via the `colorIsLocalOverride` flag (see getEventColor). Personal calendars
|
||||
* are passed through untouched.
|
||||
*/
|
||||
export function applySharedCalendarColors(
|
||||
calendars: Calendar[],
|
||||
overrides: Record<string, string>,
|
||||
): Calendar[] {
|
||||
return calendars.map((cal) => {
|
||||
if (!cal.isShared) return cal;
|
||||
const override = overrides[sharedCalendarColorKey(cal)];
|
||||
if (!override) return cal;
|
||||
return { ...cal, color: override, colorIsLocalOverride: true };
|
||||
});
|
||||
}
|
||||
|
||||
export function getPrimaryCalendarId(
|
||||
event: Pick<CalendarEvent, 'calendarIds'>,
|
||||
): string | undefined {
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
// Builds the self-contained HTML document for the RichTextEditor WebView.
|
||||
// Kept as a pure module (no react-native imports) so tests can assert the
|
||||
// embedded page script stays syntactically valid JavaScript.
|
||||
//
|
||||
// IMPORTANT: the page script lives inside a JS template literal. Backslash
|
||||
// escapes are "cooked" by the template (`\/` becomes `/`, `\s` becomes `s`),
|
||||
// which once shipped an invalid regex that killed the whole inline script
|
||||
// with a SyntaxError (issue #11 — Send stayed disabled because the editor
|
||||
// never posted `change` messages). Never rely on a backslash reaching the
|
||||
// page verbatim; write escape-free code or double the backslash.
|
||||
|
||||
import type { ThemePalette } from '../theme/tokens';
|
||||
|
||||
// Minimum visible editor height (px). The editor auto-grows beyond this as the
|
||||
// user types, and the parent ScrollView handles overflow.
|
||||
export const MIN_EDITOR_HEIGHT = 220;
|
||||
|
||||
export function buildEditorHtml(opts: {
|
||||
initialHtml: string;
|
||||
placeholder: string;
|
||||
c: ThemePalette;
|
||||
}): string {
|
||||
const { initialHtml, placeholder, c } = opts;
|
||||
// Inject initial content as a JSON-encoded string so any HTML/quotes inside
|
||||
// are safely embedded (no template literal collision with the script body).
|
||||
const initialJson = JSON.stringify(initialHtml);
|
||||
const placeholderJson = JSON.stringify(placeholder);
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
|
||||
<style>
|
||||
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||
html, body { margin: 0; padding: 0; background: ${c.background}; color: ${c.text}; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.5;
|
||||
overflow-y: hidden;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
#editor {
|
||||
outline: none;
|
||||
padding: 12px 16px 24px;
|
||||
min-height: ${MIN_EDITOR_HEIGHT}px;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
#editor[data-empty="true"]::before {
|
||||
content: attr(data-placeholder);
|
||||
color: ${c.textMuted};
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
}
|
||||
#editor p { margin: 0 0 12px 0; }
|
||||
#editor p:last-child { margin-bottom: 0; }
|
||||
#editor h1 { font-size: 1.4em; font-weight: 700; margin: 0 0 12px 0; line-height: 1.2; }
|
||||
#editor h2 { font-size: 1.2em; font-weight: 700; margin: 0 0 10px 0; line-height: 1.3; }
|
||||
#editor ul, #editor ol { margin: 0 0 12px 0; padding-left: 24px; }
|
||||
#editor li { margin-bottom: 4px; }
|
||||
#editor blockquote {
|
||||
margin: 0 0 12px 0;
|
||||
padding: 4px 0 4px 12px;
|
||||
border-left: 3px solid ${c.border};
|
||||
color: ${c.textSecondary};
|
||||
}
|
||||
#editor a { color: ${c.primary}; text-decoration: underline; }
|
||||
#editor img { max-width: 100%; height: auto; border-radius: 4px; }
|
||||
#editor pre, #editor code {
|
||||
background: ${c.surfaceActive};
|
||||
border-radius: 4px;
|
||||
padding: 2px 4px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 0.92em;
|
||||
}
|
||||
#editor pre { padding: 8px 12px; overflow-x: auto; }
|
||||
::selection { background: ${c.primary}33; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="editor" contenteditable="true" data-placeholder=${placeholderJson}></div>
|
||||
<script>
|
||||
(function () {
|
||||
var editor = document.getElementById('editor');
|
||||
var lastHtml = null;
|
||||
var lastHeight = 0;
|
||||
|
||||
function refreshEmpty() {
|
||||
var html = editor.innerHTML;
|
||||
var isEmpty =
|
||||
html === '' ||
|
||||
html === '<br>' ||
|
||||
html === '<p></p>' ||
|
||||
html === '<p><br></p>' ||
|
||||
editor.textContent.trim() === '' && editor.querySelectorAll('img').length === 0;
|
||||
editor.setAttribute('data-empty', isEmpty ? 'true' : 'false');
|
||||
}
|
||||
|
||||
function post(type, payload) {
|
||||
if (window.ReactNativeWebView && window.ReactNativeWebView.postMessage) {
|
||||
window.ReactNativeWebView.postMessage(JSON.stringify({ type: type, payload: payload }));
|
||||
}
|
||||
}
|
||||
|
||||
function reportHeight() {
|
||||
var h = Math.max(${MIN_EDITOR_HEIGHT}, editor.scrollHeight + 8);
|
||||
if (Math.abs(h - lastHeight) < 2) return;
|
||||
lastHeight = h;
|
||||
post('height', h);
|
||||
}
|
||||
|
||||
function reportChange() {
|
||||
refreshEmpty();
|
||||
var html = editor.innerHTML;
|
||||
if (html === lastHtml) return;
|
||||
lastHtml = html;
|
||||
post('change', html);
|
||||
}
|
||||
|
||||
function reportSelection() {
|
||||
function active(name) {
|
||||
try { return document.queryCommandState(name); } catch (e) { return false; }
|
||||
}
|
||||
function inBlock(tag) {
|
||||
var sel = window.getSelection();
|
||||
if (!sel || !sel.rangeCount) return false;
|
||||
var node = sel.anchorNode;
|
||||
while (node && node !== editor) {
|
||||
if (node.nodeType === 1 && node.tagName === tag) return true;
|
||||
node = node.parentNode;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
var state = {
|
||||
bold: active('bold'),
|
||||
italic: active('italic'),
|
||||
underline: active('underline'),
|
||||
strikeThrough: active('strikeThrough'),
|
||||
ul: active('insertUnorderedList'),
|
||||
ol: active('insertOrderedList'),
|
||||
blockquote: inBlock('BLOCKQUOTE'),
|
||||
h1: inBlock('H1'),
|
||||
h2: inBlock('H2'),
|
||||
alignLeft: active('justifyLeft'),
|
||||
alignCenter: active('justifyCenter'),
|
||||
alignRight: active('justifyRight'),
|
||||
link: inBlock('A'),
|
||||
};
|
||||
post('selection', state);
|
||||
}
|
||||
|
||||
// ── Initial content ────────────────────────────────────────────────
|
||||
var initial = ${initialJson};
|
||||
if (initial && typeof initial === 'string') editor.innerHTML = initial;
|
||||
refreshEmpty();
|
||||
lastHtml = editor.innerHTML;
|
||||
|
||||
editor.addEventListener('input', function () {
|
||||
reportChange();
|
||||
reportHeight();
|
||||
});
|
||||
editor.addEventListener('blur', function () { post('blur', null); });
|
||||
editor.addEventListener('focus', function () { post('focus', null); });
|
||||
document.addEventListener('selectionchange', function () {
|
||||
if (document.activeElement === editor) reportSelection();
|
||||
});
|
||||
|
||||
// ── Bridge: receive commands from RN ───────────────────────────────
|
||||
window.__rne = {
|
||||
exec: function (command, value) {
|
||||
editor.focus();
|
||||
try {
|
||||
if (command === 'formatBlock' && value) {
|
||||
// Toggle: if we're already in that block, switch to <p>.
|
||||
var sel = window.getSelection();
|
||||
if (sel && sel.rangeCount) {
|
||||
var node = sel.anchorNode;
|
||||
while (node && node !== editor) {
|
||||
if (node.nodeType === 1 && node.tagName === value.toUpperCase()) {
|
||||
document.execCommand('formatBlock', false, '<p>');
|
||||
reportChange();
|
||||
reportHeight();
|
||||
reportSelection();
|
||||
return;
|
||||
}
|
||||
node = node.parentNode;
|
||||
}
|
||||
}
|
||||
document.execCommand('formatBlock', false, '<' + value.toLowerCase() + '>');
|
||||
} else {
|
||||
document.execCommand(command, false, value);
|
||||
}
|
||||
} catch (e) {}
|
||||
reportChange();
|
||||
reportHeight();
|
||||
reportSelection();
|
||||
},
|
||||
setHtml: function (html) {
|
||||
editor.innerHTML = html || '';
|
||||
lastHtml = editor.innerHTML;
|
||||
refreshEmpty();
|
||||
reportChange();
|
||||
reportHeight();
|
||||
},
|
||||
insertHtml: function (html) {
|
||||
editor.focus();
|
||||
try { document.execCommand('insertHTML', false, html); } catch (e) {}
|
||||
reportChange();
|
||||
reportHeight();
|
||||
},
|
||||
insertLink: function (url, label) {
|
||||
editor.focus();
|
||||
// Reject anything that isn't a safe scheme or an absolute path, so the
|
||||
// user can't accidentally (or via a malicious paste) ship a
|
||||
// javascript:/data: link to their recipient. Written without regex
|
||||
// backslash escapes — see the template-cooking warning at the top.
|
||||
var trimmed = (url || '').trim();
|
||||
var first = trimmed.charAt(0);
|
||||
var safeScheme = /^(https?:|mailto:|tel:|sms:)/i.test(trimmed)
|
||||
|| first === '/' || first === '?' || first === '#';
|
||||
if (!trimmed || !safeScheme) return;
|
||||
var sel = window.getSelection();
|
||||
var hasSelection = sel && sel.rangeCount && !sel.getRangeAt(0).collapsed;
|
||||
if (hasSelection) {
|
||||
try { document.execCommand('createLink', false, trimmed); } catch (e) {}
|
||||
// execCommand doesn't set rel; tag every anchor that points at this URL.
|
||||
Array.prototype.forEach.call(editor.getElementsByTagName('a'), function (a) {
|
||||
if (a.getAttribute('href') === trimmed) {
|
||||
a.setAttribute('rel', 'noopener noreferrer nofollow');
|
||||
}
|
||||
});
|
||||
} else {
|
||||
var text = label && label.trim() ? label : trimmed;
|
||||
var safe = text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
var safeUrl = trimmed
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
var html = '<a href="' + safeUrl + '" rel="noopener noreferrer nofollow">' + safe + '</a>';
|
||||
try { document.execCommand('insertHTML', false, html); } catch (e) {}
|
||||
}
|
||||
reportChange();
|
||||
reportHeight();
|
||||
reportSelection();
|
||||
},
|
||||
unsetLink: function () {
|
||||
editor.focus();
|
||||
try { document.execCommand('unlink', false, null); } catch (e) {}
|
||||
reportChange();
|
||||
reportSelection();
|
||||
},
|
||||
insertImage: function (src, cid, alt) {
|
||||
editor.focus();
|
||||
var safeSrc = (src || '').replace(/"/g, '"');
|
||||
var safeAlt = (alt || '').replace(/&/g, '&').replace(/"/g, '"');
|
||||
var safeCid = cid ? cid.replace(/"/g, '"') : '';
|
||||
var html = '<img src="' + safeSrc + '" alt="' + safeAlt + '"' +
|
||||
(safeCid ? ' data-cid="' + safeCid + '"' : '') + ' />';
|
||||
try { document.execCommand('insertHTML', false, html); } catch (e) {}
|
||||
reportChange();
|
||||
reportHeight();
|
||||
},
|
||||
// Send-time readback (issue #9): RN asks for the live DOM content instead
|
||||
// of trusting the last change message, which can lag typing or be lost
|
||||
// entirely if the bridge breaks. The id lets RN match reply to request.
|
||||
getHtml: function (id) {
|
||||
post('htmlSnapshot', { id: id, html: editor.innerHTML });
|
||||
},
|
||||
focus: function () { editor.focus(); },
|
||||
};
|
||||
|
||||
reportHeight();
|
||||
reportChange();
|
||||
|
||||
// Re-measure after async layout (image loads, font swap).
|
||||
window.addEventListener('load', function () {
|
||||
setTimeout(reportHeight, 50);
|
||||
setTimeout(reportHeight, 200);
|
||||
setTimeout(reportHeight, 600);
|
||||
});
|
||||
if (window.ResizeObserver) {
|
||||
new ResizeObserver(reportHeight).observe(editor);
|
||||
}
|
||||
})();
|
||||
true;
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -89,13 +89,15 @@ export async function shareAttachment(
|
||||
name: string | undefined,
|
||||
type: string | undefined,
|
||||
email?: Email | null,
|
||||
// Owning account for blobs shared by another principal (Files app).
|
||||
accountId?: string,
|
||||
): Promise<void> {
|
||||
const filename = email
|
||||
? attachmentDownloadFilename(email, { name, type }, attachmentFileOptions())
|
||||
: safeAttachmentName(name, type);
|
||||
const mimeType = type || 'application/octet-stream';
|
||||
const dest = new File(Paths.cache, filename);
|
||||
const url = getDownloadUrl(blobId, filename, mimeType);
|
||||
const url = getDownloadUrl(blobId, filename, mimeType, accountId);
|
||||
const downloaded = await downloadInto(url, dest, Paths.cache);
|
||||
if (!(await Sharing.isAvailableAsync())) {
|
||||
throw new Error('Sharing is not available on this device');
|
||||
@@ -116,13 +118,15 @@ export async function downloadAttachment(
|
||||
name: string | undefined,
|
||||
type: string | undefined,
|
||||
email?: Email | null,
|
||||
// Owning account for blobs shared by another principal (Files app).
|
||||
accountId?: string,
|
||||
): Promise<void> {
|
||||
const filename = email
|
||||
? attachmentDownloadFilename(email, { name, type }, attachmentFileOptions())
|
||||
: safeAttachmentName(name, type);
|
||||
const mimeType = type || 'application/octet-stream';
|
||||
const dest = new File(Paths.document, filename);
|
||||
const url = getDownloadUrl(blobId, filename, mimeType);
|
||||
const url = getDownloadUrl(blobId, filename, mimeType, accountId);
|
||||
const downloaded = await downloadInto(url, dest, Paths.document);
|
||||
if (!(await Sharing.isAvailableAsync())) {
|
||||
throw new Error('Sharing is not available on this device');
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,102 @@
|
||||
// Sign-in failures reach the UI as raw strings from the JMAP client — "Session
|
||||
// discovery failed: 404 Not Found", "Network request failed". Those describe
|
||||
// what the code was doing, not what the person should do next. This maps the
|
||||
// ones we can recognise onto copy that names a likely cause and an action.
|
||||
//
|
||||
// Errors are matched by `name` and message text rather than `instanceof` so
|
||||
// this module stays free of the api/ and expo dependency graph.
|
||||
|
||||
export interface LoginErrorCopy {
|
||||
title: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export interface LoginErrorContext {
|
||||
/** Host shown in "can't reach X" copy. */
|
||||
serverUrl?: string | null;
|
||||
}
|
||||
|
||||
function messageOf(err: unknown): string {
|
||||
return err instanceof Error ? err.message : typeof err === 'string' ? err : '';
|
||||
}
|
||||
|
||||
function nameOf(err: unknown): string {
|
||||
return err instanceof Error ? err.name : '';
|
||||
}
|
||||
|
||||
function hostLabel(serverUrl: string | null | undefined): string {
|
||||
if (!serverUrl) return 'the server';
|
||||
const host = serverUrl.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '').split('/')[0];
|
||||
return host || 'the server';
|
||||
}
|
||||
|
||||
export function describeLoginError(err: unknown, context: LoginErrorContext = {}): LoginErrorCopy {
|
||||
const name = nameOf(err);
|
||||
const message = messageOf(err);
|
||||
const lower = message.toLowerCase();
|
||||
const host = hostLabel(context.serverUrl);
|
||||
|
||||
if (name === 'AuthenticationError' || lower.includes('invalid username or password')) {
|
||||
return {
|
||||
title: "That didn't work",
|
||||
detail:
|
||||
'Check your email and password. If your account uses two-factor sign-in, create an app password in the webmail and use that here.',
|
||||
};
|
||||
}
|
||||
|
||||
if (lower.includes('certificate') || lower.includes('ssl') || lower.includes('tls')) {
|
||||
return {
|
||||
title: `Couldn't verify ${host}`,
|
||||
detail:
|
||||
"The server's security certificate was rejected. If this is your own server, check the certificate is valid and not expired.",
|
||||
};
|
||||
}
|
||||
|
||||
// The endpoint answered, but it isn't a JMAP server — almost always a
|
||||
// mistyped host or a webmail that lives on a subpath.
|
||||
if (lower.includes('session discovery failed') && /\b40[34]\b/.test(message)) {
|
||||
return {
|
||||
title: `No mail server at ${host}`,
|
||||
detail: 'Double-check the address, or scan a sign-in code from the webmail instead.',
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
name === 'NetworkError' ||
|
||||
name === 'TypeError' ||
|
||||
name === 'AbortError' ||
|
||||
lower.includes('network request failed') ||
|
||||
lower.includes('failed to fetch') ||
|
||||
lower.includes('timeout') ||
|
||||
lower.includes('timed out')
|
||||
) {
|
||||
return {
|
||||
title: `Can't reach ${host}`,
|
||||
detail: 'Check your connection and the server address, then try again.',
|
||||
};
|
||||
}
|
||||
|
||||
if (lower.includes('pairing code')) {
|
||||
return {
|
||||
title: 'That code has expired',
|
||||
detail: 'Sign-in codes are good for a few minutes. Generate a fresh one in the webmail and scan again.',
|
||||
};
|
||||
}
|
||||
|
||||
if (lower.includes('state mismatch')) {
|
||||
return {
|
||||
title: 'Sign-in was interrupted',
|
||||
detail: "The response didn't match the request we started. Try signing in again.",
|
||||
};
|
||||
}
|
||||
|
||||
if (lower.includes('maximum of') && lower.includes('accounts')) {
|
||||
return { title: message };
|
||||
}
|
||||
|
||||
// Unrecognised: show what we were told rather than inventing a cause.
|
||||
return {
|
||||
title: 'Sign-in failed',
|
||||
detail: message || 'Something went wrong. Try again.',
|
||||
};
|
||||
}
|
||||
@@ -96,3 +96,36 @@ export function flattenVisible(
|
||||
walk(nodes);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function findTrashMailbox(mailboxes: Mailbox[]): Mailbox | undefined {
|
||||
const roleMatch = mailboxes.find((m) => m.role === 'trash');
|
||||
if (roleMatch) return roleMatch;
|
||||
|
||||
const names = ['trash', 'bin', 'deleted', 'deleted items', 'corbeille', 'messages supprimés', 'éléments supprimés', 'supprimé', 'supprimés'];
|
||||
return mailboxes.find((m) => {
|
||||
const lower = m.name.toLowerCase();
|
||||
return names.includes(lower) || names.some((n) => lower.includes(n));
|
||||
});
|
||||
}
|
||||
|
||||
export function findArchiveMailbox(mailboxes: Mailbox[]): Mailbox | undefined {
|
||||
const roleMatch = mailboxes.find((m) => m.role === 'archive');
|
||||
if (roleMatch) return roleMatch;
|
||||
|
||||
const names = ['archive', 'archives', 'archived'];
|
||||
return mailboxes.find((m) => {
|
||||
const lower = m.name.toLowerCase();
|
||||
return names.includes(lower) || names.some((n) => lower.includes(n));
|
||||
});
|
||||
}
|
||||
|
||||
export function findJunkMailbox(mailboxes: Mailbox[]): Mailbox | undefined {
|
||||
const roleMatch = mailboxes.find((m) => m.role === 'junk' || m.role === 'spam');
|
||||
if (roleMatch) return roleMatch;
|
||||
|
||||
const names = ['junk', 'spam', 'indésirables', 'indésirable', 'courrier indésirable'];
|
||||
return mailboxes.find((m) => {
|
||||
const lower = m.name.toLowerCase();
|
||||
return names.includes(lower) || names.some((n) => lower.includes(n));
|
||||
});
|
||||
}
|
||||
|
||||
+47
-30
@@ -207,6 +207,8 @@ export async function redeemPairingCode(webmailUrl: string, code: string): Promi
|
||||
};
|
||||
}
|
||||
|
||||
const activeRefreshes = new Map<string, Promise<OAuthTokens>>();
|
||||
|
||||
// OAuth refresh — exchanges the refresh token at the original token endpoint
|
||||
// for a new access token. Returns the updated bundle so the caller can
|
||||
// persist it.
|
||||
@@ -214,37 +216,52 @@ export async function refreshOAuthAccessToken(tokens: OAuthTokens): Promise<OAut
|
||||
if (!tokens.refreshToken) {
|
||||
throw new HandoffError('No refresh token available');
|
||||
}
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: tokens.refreshToken,
|
||||
client_id: tokens.clientId,
|
||||
});
|
||||
const response = await secureFetch(tokens.tokenEndpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: body.toString(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new HandoffError(`Token refresh failed: ${response.status}`);
|
||||
|
||||
const cacheKey = tokens.refreshToken;
|
||||
let promise = activeRefreshes.get(cacheKey);
|
||||
|
||||
if (!promise) {
|
||||
promise = (async () => {
|
||||
try {
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: tokens.refreshToken!,
|
||||
client_id: tokens.clientId,
|
||||
});
|
||||
const response = await secureFetch(tokens.tokenEndpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: body.toString(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new HandoffError(`Token refresh failed: ${response.status}`);
|
||||
}
|
||||
const data = (await response.json()) as {
|
||||
access_token?: string;
|
||||
refresh_token?: string;
|
||||
expires_in?: number;
|
||||
};
|
||||
if (!data.access_token) {
|
||||
throw new HandoffError('Token refresh response missing access_token');
|
||||
}
|
||||
return {
|
||||
accessToken: data.access_token,
|
||||
refreshToken: data.refresh_token ?? tokens.refreshToken!,
|
||||
expiresAt: data.expires_in ? Date.now() + data.expires_in * 1000 : undefined,
|
||||
tokenEndpoint: tokens.tokenEndpoint,
|
||||
clientId: tokens.clientId,
|
||||
};
|
||||
} finally {
|
||||
activeRefreshes.delete(cacheKey);
|
||||
}
|
||||
})();
|
||||
activeRefreshes.set(cacheKey, promise);
|
||||
}
|
||||
const data = (await response.json()) as {
|
||||
access_token?: string;
|
||||
refresh_token?: string;
|
||||
expires_in?: number;
|
||||
};
|
||||
if (!data.access_token) {
|
||||
throw new HandoffError('Token refresh response missing access_token');
|
||||
}
|
||||
return {
|
||||
accessToken: data.access_token,
|
||||
refreshToken: data.refresh_token ?? tokens.refreshToken,
|
||||
expiresAt: data.expires_in ? Date.now() + data.expires_in * 1000 : undefined,
|
||||
tokenEndpoint: tokens.tokenEndpoint,
|
||||
clientId: tokens.clientId,
|
||||
};
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
WebBrowser.maybeCompleteAuthSession();
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// Single source of truth for "this feature only exists on some platforms", so
|
||||
// the UI, the stores and the native bridges all agree on what is reachable.
|
||||
|
||||
import { Platform } from 'react-native';
|
||||
|
||||
/**
|
||||
* In-app sideload updates: download the release APK from GitHub and hand it to
|
||||
* the system package installer (see `lib/install-update`).
|
||||
*
|
||||
* Android only. App Store Review guideline 2.5.2 forbids an iOS app from
|
||||
* downloading and installing executable code, and there is no iOS equivalent of
|
||||
* the installer intent anyway - iOS builds are updated through TestFlight or
|
||||
* the App Store. The whole updater surface (banner, settings pane, launch-time
|
||||
* check) is hidden when this is false.
|
||||
*/
|
||||
export const supportsSideloadUpdates = Platform.OS === 'android';
|
||||
@@ -217,6 +217,33 @@ async function registerWithRelay(params: {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask the relay whether a leftover subscription is dead. Returns true ONLY when
|
||||
* the relay positively reports it inactive - a record it knows about that has
|
||||
* never forwarded a push and isn't freshly registered. Every other outcome (the
|
||||
* relay doesn't recognise the id, an older relay without this endpoint, a
|
||||
* network blip, or a live subscription) returns false, so we never reap
|
||||
* anything we can't confirm is dead. This is what lets setup clear its own
|
||||
* abandoned attempts - and dead siblings left by reinstalls that regenerated
|
||||
* the deviceClientId - without disturbing another live device or the PWA that
|
||||
* shares the account.
|
||||
*/
|
||||
async function relayReportsDead(
|
||||
relayBaseUrl: string,
|
||||
subscriptionId: string,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch(
|
||||
buildRelayUrl(relayBaseUrl, `/api/push/active/${encodeURIComponent(subscriptionId)}`),
|
||||
);
|
||||
if (!res.ok) return false;
|
||||
const body = (await res.json()) as { active?: unknown };
|
||||
return body.active === false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function pollVerificationCode(
|
||||
relayBaseUrl: string,
|
||||
subscriptionId: string,
|
||||
@@ -241,12 +268,36 @@ async function pollVerificationCode(
|
||||
throw new Error('Timed out waiting for PushVerification from JMAP server');
|
||||
}
|
||||
|
||||
// Coalesce concurrent setup attempts per account. App.tsx re-runs its push
|
||||
// effect as auth state settles during startup and again on every FCM token
|
||||
// refresh; because a failing attempt blocks for up to 75s polling for the
|
||||
// verification code, those re-fires overlap. Without this guard each
|
||||
// overlapping run mints its OWN deviceClientId and JMAP subscription, and the
|
||||
// resulting swarm starves Stalwart's one-PushVerification-per-60s slot so none
|
||||
// of them ever verifies (the symptom is a perpetual "Timed out waiting for
|
||||
// PushVerification"). Callers share the first in-flight run instead.
|
||||
const inFlightSetups = new Map<string, Promise<PushSetupResult>>();
|
||||
|
||||
/**
|
||||
* Full setup flow: ask permission, fetch the device's FCM token, register
|
||||
* with the relay, create a JMAP PushSubscription, poll for the verification
|
||||
* code, and finalise the subscription.
|
||||
* code, and finalise the subscription. Concurrent calls for the same account
|
||||
* are coalesced onto a single in-flight run.
|
||||
*/
|
||||
export async function setupPushNotifications(
|
||||
export function setupPushNotifications(
|
||||
params: PushSetupParams,
|
||||
): Promise<PushSetupResult> {
|
||||
const key = `${jmapClient.username ?? ''}@${jmapClient.serverUrl ?? ''}`;
|
||||
const existing = inFlightSetups.get(key);
|
||||
if (existing) return existing;
|
||||
const run = setupPushNotificationsInner(params).finally(() => {
|
||||
inFlightSetups.delete(key);
|
||||
});
|
||||
inFlightSetups.set(key, run);
|
||||
return run;
|
||||
}
|
||||
|
||||
async function setupPushNotificationsInner(
|
||||
params: PushSetupParams,
|
||||
): Promise<PushSetupResult> {
|
||||
const native = getNative();
|
||||
@@ -306,19 +357,29 @@ export async function setupPushNotifications(
|
||||
await AsyncStorage.removeItem(subKey);
|
||||
}
|
||||
|
||||
// Reap any leftover Stalwart subscriptions still bound to this account's
|
||||
// deviceClientId. These pile up when a previous enable attempt failed
|
||||
// mid-flow (verify race, network blip, app killed). Stalwart per-account
|
||||
// rate-limits PushVerification posts, so leaving stragglers around blocks
|
||||
// the new one's verification - the symptom is a confusing "code does not
|
||||
// match". Only reap matches for THIS account's deviceClientId; other
|
||||
// accounts' subscriptions on this server (rare but possible if the same
|
||||
// JMAP server backs multiple accounts) must be left alone.
|
||||
const stragglers = existingSubs.filter(
|
||||
(s) => s.deviceClientId === deviceClientId && s.id !== storedServerId,
|
||||
);
|
||||
for (const s of stragglers) {
|
||||
await destroyPushSubscription(s.id).catch(() => undefined);
|
||||
// Reap leftover Stalwart subscriptions that would otherwise starve the new
|
||||
// one's verification. Stalwart emits only one PushVerification per account
|
||||
// per ~60s and picks the oldest unverified subscription, so a single stale
|
||||
// straggler blocks every fresh attempt - the symptom is the confusing
|
||||
// "Timed out waiting for PushVerification" error. We can't read a
|
||||
// subscription's verified state or URL over JMAP (Stalwart hides both), only
|
||||
// its deviceClientId, so we decide what's safe to remove like this:
|
||||
// - same deviceClientId as ours: a previous attempt from THIS device,
|
||||
// always safe to reap.
|
||||
// - a different deviceClientId: could be another live device or the PWA on
|
||||
// this account. Ask the relay whether it's still alive and only reap the
|
||||
// ones it confirms are dead. Anything live - or anything the relay can't
|
||||
// vouch for (a different relay, a non-Bulwark client, a network blip) -
|
||||
// is left untouched.
|
||||
for (const s of existingSubs) {
|
||||
if (s.id === storedServerId) continue;
|
||||
if (s.deviceClientId === deviceClientId) {
|
||||
await destroyPushSubscription(s.id).catch(() => undefined);
|
||||
continue;
|
||||
}
|
||||
if (await relayReportsDead(relayBaseUrl, s.deviceClientId)) {
|
||||
await destroyPushSubscription(s.id).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
const serverAssignedId = await createPushSubscription({
|
||||
|
||||
+191
-27
@@ -11,7 +11,7 @@
|
||||
* on the client.
|
||||
*/
|
||||
|
||||
import { addDays, addMonths, addWeeks, addYears, format, parseISO } from 'date-fns';
|
||||
import { addDays, addMonths, addWeeks, addYears, differenceInCalendarDays, format, parseISO } from 'date-fns';
|
||||
import type { CalendarEvent, RecurrenceRule } from '../api/types';
|
||||
|
||||
type NDay = { day: string; nthOfPeriod?: number };
|
||||
@@ -60,6 +60,10 @@ export function expandRecurringEvents(
|
||||
return result;
|
||||
}
|
||||
|
||||
function occurrenceDateKey(master: CalendarEvent, date: Date): string {
|
||||
return master.showWithoutTime ? format(date, 'yyyy-MM-dd') : date.toISOString();
|
||||
}
|
||||
|
||||
function expandEvent(
|
||||
master: CalendarEvent,
|
||||
rangeStart: Date,
|
||||
@@ -73,13 +77,23 @@ function expandEvent(
|
||||
const occurrences: CalendarEvent[] = [];
|
||||
const seenDates = new Set<string>();
|
||||
|
||||
// RFC 8984 §4.3.3: occurrences produced by excludedRecurrenceRules
|
||||
// (iCalendar EXRULE) are removed from the recurrence set.
|
||||
const excludedDates = new Set<string>();
|
||||
for (const exRule of master.excludedRecurrenceRules || []) {
|
||||
// includeStartDate=false: "the series start is always an occurrence"
|
||||
// applies to recurrence rules, not to exclusion rules.
|
||||
for (const date of generateDates(eventStart, exRule, rangeStart, rangeEnd, false)) {
|
||||
excludedDates.add(occurrenceDateKey(master, date));
|
||||
}
|
||||
}
|
||||
|
||||
for (const rule of rules) {
|
||||
const dates = generateDates(eventStart, rule, rangeStart, rangeEnd);
|
||||
for (const date of dates) {
|
||||
const dateKey = master.showWithoutTime
|
||||
? format(date, 'yyyy-MM-dd')
|
||||
: date.toISOString();
|
||||
const dateKey = occurrenceDateKey(master, date);
|
||||
|
||||
if (excludedDates.has(dateKey)) continue;
|
||||
if (seenDates.has(dateKey)) continue;
|
||||
seenDates.add(dateKey);
|
||||
|
||||
@@ -104,9 +118,9 @@ function expandEvent(
|
||||
if (isNaN(overrideDate.getTime())) continue;
|
||||
if (overrideDate < rangeStart || overrideDate >= rangeEnd) continue;
|
||||
|
||||
const dateKey = master.showWithoutTime
|
||||
? format(overrideDate, 'yyyy-MM-dd')
|
||||
: overrideDate.toISOString();
|
||||
// Overrides take precedence over excludedRecurrenceRules (they re-add
|
||||
// a concrete instance), so only dedupe against already-generated dates.
|
||||
const dateKey = occurrenceDateKey(master, overrideDate);
|
||||
if (seenDates.has(dateKey)) continue;
|
||||
seenDates.add(dateKey);
|
||||
|
||||
@@ -116,6 +130,65 @@ function expandEvent(
|
||||
return occurrences;
|
||||
}
|
||||
|
||||
// Cache Intl formatters per IANA timezone id — constructing them is expensive
|
||||
// and expansion runs over hundreds of occurrences. `null` marks ids the
|
||||
// runtime rejected so we don't retry them.
|
||||
const tzFormatterCache = new Map<string, Intl.DateTimeFormat | null>();
|
||||
|
||||
function getTzFormatter(timeZone: string): Intl.DateTimeFormat | null {
|
||||
let formatter = tzFormatterCache.get(timeZone);
|
||||
if (formatter === undefined) {
|
||||
try {
|
||||
formatter = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
});
|
||||
} catch {
|
||||
formatter = null;
|
||||
}
|
||||
tzFormatterCache.set(timeZone, formatter);
|
||||
}
|
||||
return formatter;
|
||||
}
|
||||
|
||||
/** The wall-clock reading of `instant` in the formatter's zone, re-encoded as a UTC timestamp. */
|
||||
function wallClockAsUtcTimestamp(formatter: Intl.DateTimeFormat, instant: number): number {
|
||||
const map: Record<string, string> = {};
|
||||
for (const part of formatter.formatToParts(new Date(instant))) {
|
||||
if (part.type !== 'literal') map[part.type] = part.value;
|
||||
}
|
||||
const hour = map.hour === '24' ? 0 : Number(map.hour);
|
||||
return Date.UTC(
|
||||
Number(map.year), Number(map.month) - 1, Number(map.day),
|
||||
hour, Number(map.minute), Number(map.second),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Interpret the wall-clock fields of `wall` as a local time in `timeZone`
|
||||
* and return the corresponding UTC instant. Two fixup iterations converge
|
||||
* for all real offsets, including across DST transitions.
|
||||
*/
|
||||
function zonedWallTimeToUtc(wall: Date, timeZone: string): Date | null {
|
||||
const formatter = getTzFormatter(timeZone);
|
||||
if (!formatter) return null;
|
||||
const wallAsUtc = Date.UTC(
|
||||
wall.getFullYear(), wall.getMonth(), wall.getDate(),
|
||||
wall.getHours(), wall.getMinutes(), wall.getSeconds(),
|
||||
);
|
||||
let guess = wallAsUtc;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
guess = wallAsUtc - (wallClockAsUtcTimestamp(formatter, guess) - guess);
|
||||
}
|
||||
return new Date(guess);
|
||||
}
|
||||
|
||||
function createOccurrence(
|
||||
master: CalendarEvent,
|
||||
date: Date,
|
||||
@@ -130,16 +203,33 @@ function createOccurrence(
|
||||
// getEventEndDate return the occurrence times rather than the master's.
|
||||
let utcStart: string | undefined;
|
||||
let utcEnd: string | undefined;
|
||||
if (!master.showWithoutTime && master.utcStart && master.start) {
|
||||
const masterLocal = parseISO(master.start);
|
||||
const masterUtc = parseISO(master.utcStart);
|
||||
const offsetMs = masterUtc.getTime() - masterLocal.getTime();
|
||||
utcStart = new Date(date.getTime() + offsetMs).toISOString();
|
||||
if (!master.showWithoutTime) {
|
||||
let durationMs: number | null = null;
|
||||
if (master.utcStart && master.utcEnd) {
|
||||
const ms = parseISO(master.utcEnd).getTime() - parseISO(master.utcStart).getTime();
|
||||
if (!isNaN(ms)) durationMs = ms;
|
||||
}
|
||||
|
||||
if (master.utcEnd) {
|
||||
const masterUtcEnd = parseISO(master.utcEnd);
|
||||
const durationMs = masterUtcEnd.getTime() - masterUtc.getTime();
|
||||
utcEnd = new Date(date.getTime() + offsetMs + durationMs).toISOString();
|
||||
// Convert the occurrence's wall time using the event's own timezone, so
|
||||
// occurrences on the other side of a DST transition in that zone keep
|
||||
// their wall time. Reusing the master's fixed UTC offset (the fallback
|
||||
// below) would shift them by the DST delta.
|
||||
const zoned = master.timeZone ? zonedWallTimeToUtc(date, master.timeZone) : null;
|
||||
if (zoned) {
|
||||
utcStart = zoned.toISOString();
|
||||
if (durationMs !== null) {
|
||||
utcEnd = new Date(zoned.getTime() + durationMs).toISOString();
|
||||
}
|
||||
} else if (master.utcStart && master.start) {
|
||||
// Floating events (or an unrecognized timezone id): keep the master's
|
||||
// offset, which by definition doesn't vary.
|
||||
const masterLocal = parseISO(master.start);
|
||||
const masterUtc = parseISO(master.utcStart);
|
||||
const offsetMs = masterUtc.getTime() - masterLocal.getTime();
|
||||
utcStart = new Date(date.getTime() + offsetMs).toISOString();
|
||||
if (durationMs !== null) {
|
||||
utcEnd = new Date(date.getTime() + offsetMs + durationMs).toISOString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,6 +297,7 @@ function generateDates(
|
||||
rawRule: RecurrenceRule,
|
||||
rangeStart: Date,
|
||||
rangeEnd: Date,
|
||||
includeStartDate = true,
|
||||
): Date[] {
|
||||
const rule = addImplicitByX(rawRule, eventStart);
|
||||
const dates: Date[] = [];
|
||||
@@ -214,21 +305,34 @@ function generateDates(
|
||||
const countLimit = rule.count || Infinity;
|
||||
const until = rule.until ? parseISO(rule.until) : null;
|
||||
let totalCount = 0;
|
||||
let current = new Date(eventStart);
|
||||
// Without a `count` limit we can jump straight to the period containing
|
||||
// the visible range. With one, every occurrence since the series start
|
||||
// must be generated so it counts against `count`.
|
||||
let current = rule.count
|
||||
? new Date(eventStart)
|
||||
: fastForwardToRange(eventStart, rule.frequency, interval, rangeStart);
|
||||
|
||||
const maxIterations = 2000;
|
||||
// Cap on *emitted* (in-range) dates. This must not count occurrences
|
||||
// before rangeStart, otherwise a series started long ago (e.g. a daily
|
||||
// event from two years back) exhausts the budget before reaching the
|
||||
// visible range and silently renders nothing.
|
||||
const maxOccurrences = 500;
|
||||
let iterations = 0;
|
||||
|
||||
while (iterations++ < maxIterations) {
|
||||
if (totalCount >= countLimit || totalCount >= maxOccurrences) break;
|
||||
if (totalCount >= countLimit || dates.length >= maxOccurrences) break;
|
||||
if (until && current > until) break;
|
||||
if (
|
||||
current >= rangeEnd
|
||||
&& rule.frequency !== 'yearly'
|
||||
&& rule.frequency !== 'monthly'
|
||||
&& rule.frequency !== 'weekly'
|
||||
) break;
|
||||
// Stop once no candidate in this or a later period can fall before
|
||||
// rangeEnd. Monthly/yearly candidates may precede the period anchor
|
||||
// within the same month/year, so floor the anchor before comparing.
|
||||
if (rule.frequency === 'monthly') {
|
||||
if (new Date(current.getFullYear(), current.getMonth(), 1) >= rangeEnd) break;
|
||||
} else if (rule.frequency === 'yearly') {
|
||||
if (new Date(current.getFullYear(), 0, 1) >= rangeEnd) break;
|
||||
} else if (current >= rangeEnd) {
|
||||
break;
|
||||
}
|
||||
|
||||
const candidates = generateCandidatesForPeriod(current, rule, eventStart);
|
||||
|
||||
@@ -238,7 +342,7 @@ function generateDates(
|
||||
|
||||
for (const d of filtered) {
|
||||
if (until && d > until) break;
|
||||
if (totalCount >= countLimit || totalCount >= maxOccurrences) break;
|
||||
if (totalCount >= countLimit || dates.length >= maxOccurrences) break;
|
||||
|
||||
// Spec rule 4: eliminate dates before event start
|
||||
if (d < eventStart) continue;
|
||||
@@ -250,7 +354,7 @@ function generateDates(
|
||||
if (d >= rangeEnd) break;
|
||||
}
|
||||
|
||||
if (totalCount >= countLimit || totalCount >= maxOccurrences) break;
|
||||
if (totalCount >= countLimit || dates.length >= maxOccurrences) break;
|
||||
|
||||
current = advancePeriod(current, rule.frequency, interval);
|
||||
if (current <= eventStart && iterations === 1) {
|
||||
@@ -259,7 +363,7 @@ function generateDates(
|
||||
}
|
||||
|
||||
// Spec rule 1: the start date-time is ALWAYS the first occurrence.
|
||||
if (dates.length > 0 && dates[0].getTime() !== eventStart.getTime()) {
|
||||
if (includeStartDate && dates.length > 0 && dates[0].getTime() !== eventStart.getTime()) {
|
||||
if (eventStart >= rangeStart && eventStart < rangeEnd) {
|
||||
if (!dates.some((d) => d.getTime() === eventStart.getTime())) {
|
||||
dates.unshift(eventStart);
|
||||
@@ -505,6 +609,66 @@ function advancePeriod(
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Fast-forward to the visible range ───────────────────
|
||||
// Jump to the period just before the visible range in O(1), so long-running
|
||||
// series don't burn the iteration budget on years of out-of-range periods.
|
||||
// Only valid for rules without `count` (counted rules must enumerate every
|
||||
// occurrence from the series start).
|
||||
function fastForwardToRange(
|
||||
eventStart: Date,
|
||||
frequency: RecurrenceRule['frequency'],
|
||||
interval: number,
|
||||
rangeStart: Date,
|
||||
): Date {
|
||||
if (eventStart >= rangeStart) return new Date(eventStart);
|
||||
|
||||
let periods: number;
|
||||
switch (frequency) {
|
||||
case 'secondly':
|
||||
periods = Math.floor((rangeStart.getTime() - eventStart.getTime()) / (1000 * interval));
|
||||
break;
|
||||
case 'minutely':
|
||||
periods = Math.floor((rangeStart.getTime() - eventStart.getTime()) / (60000 * interval));
|
||||
break;
|
||||
case 'hourly':
|
||||
periods = Math.floor((rangeStart.getTime() - eventStart.getTime()) / (3600000 * interval));
|
||||
break;
|
||||
case 'daily':
|
||||
periods = Math.floor(differenceInCalendarDays(rangeStart, eventStart) / interval);
|
||||
break;
|
||||
case 'weekly':
|
||||
periods = Math.floor(differenceInCalendarDays(rangeStart, eventStart) / (7 * interval));
|
||||
break;
|
||||
case 'monthly': {
|
||||
const months = (rangeStart.getFullYear() - eventStart.getFullYear()) * 12
|
||||
+ (rangeStart.getMonth() - eventStart.getMonth());
|
||||
periods = Math.floor(months / interval);
|
||||
break;
|
||||
}
|
||||
case 'yearly':
|
||||
periods = Math.floor((rangeStart.getFullYear() - eventStart.getFullYear()) / interval);
|
||||
break;
|
||||
default:
|
||||
return new Date(eventStart);
|
||||
}
|
||||
|
||||
// Land one full period early so candidates inside the boundary period
|
||||
// (which can precede the period anchor) are still generated.
|
||||
periods = Math.max(0, periods - 1);
|
||||
if (periods === 0) return new Date(eventStart);
|
||||
|
||||
switch (frequency) {
|
||||
case 'secondly': return new Date(eventStart.getTime() + periods * interval * 1000);
|
||||
case 'minutely': return new Date(eventStart.getTime() + periods * interval * 60000);
|
||||
case 'hourly': return new Date(eventStart.getTime() + periods * interval * 3600000);
|
||||
case 'daily': return addDays(eventStart, periods * interval);
|
||||
case 'weekly': return addWeeks(eventStart, periods * interval);
|
||||
case 'monthly': return addMonths(eventStart, periods * interval);
|
||||
case 'yearly': return addYears(eventStart, periods * interval);
|
||||
default: return new Date(eventStart);
|
||||
}
|
||||
}
|
||||
|
||||
function expandByDayInMonth(
|
||||
year: number,
|
||||
month: number,
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
/**
|
||||
* Custom recurrence rule helpers for the event editor. Mobile port of
|
||||
* webmail's components/calendar/recurrence-editor.tsx logic (rule detection,
|
||||
* construction, and the human-readable summary).
|
||||
*/
|
||||
|
||||
import { format } from 'date-fns';
|
||||
import type { RecurrenceRule } from '../api/types';
|
||||
|
||||
export type EditorFrequency = 'daily' | 'weekly' | 'monthly' | 'yearly';
|
||||
export type MonthlyMode = 'day' | 'nth';
|
||||
export type EndsMode = 'never' | 'on' | 'after';
|
||||
|
||||
export const EDITOR_FREQUENCIES: EditorFrequency[] = ['daily', 'weekly', 'monthly', 'yearly'];
|
||||
|
||||
// JSCalendar weekday ids in display order (week starts Monday, matching the
|
||||
// firstDayOfWeek the built rules declare).
|
||||
export const WEEKDAYS: string[] = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su'];
|
||||
const DAY_TO_REF_DATE: Record<string, number> = { mo: 1, tu: 2, we: 3, th: 4, fr: 5, sa: 6, su: 7 };
|
||||
export const INDEX_TO_DAY = ['su', 'mo', 'tu', 'we', 'th', 'fr', 'sa'];
|
||||
|
||||
export const UNIT_LABELS: Record<EditorFrequency, string> = {
|
||||
daily: 'days',
|
||||
weekly: 'weeks',
|
||||
monthly: 'months',
|
||||
yearly: 'years',
|
||||
};
|
||||
|
||||
// 2024-01-01 is a Monday — used to render weekday names via date-fns.
|
||||
export function weekdayName(day: string, style: 'long' | 'short' = 'long'): string {
|
||||
const ref = new Date(2024, 0, DAY_TO_REF_DATE[day] ?? 1);
|
||||
return format(ref, style === 'long' ? 'EEEE' : 'EEE');
|
||||
}
|
||||
|
||||
export function monthName(month: number): string {
|
||||
return format(new Date(2024, month - 1, 1), 'LLLL');
|
||||
}
|
||||
|
||||
const NTH_LABELS: Record<number, string> = {
|
||||
1: 'first',
|
||||
2: 'second',
|
||||
3: 'third',
|
||||
4: 'fourth',
|
||||
[-1]: 'last',
|
||||
};
|
||||
|
||||
export function nthLabel(nth: number): string {
|
||||
return NTH_LABELS[nth] ?? String(nth);
|
||||
}
|
||||
|
||||
export function capitalize(s: string): string {
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract an "nth weekday" pattern from a rule, accepting both the
|
||||
* byDay+nthOfPeriod encoding and the byDay+bySetPosition encoding.
|
||||
*/
|
||||
export function getNthDay(rule: RecurrenceRule): { day: string; nth: number } | null {
|
||||
if (rule.byDay?.length === 1) {
|
||||
const nd = rule.byDay[0];
|
||||
if (nd.nthOfPeriod) return { day: nd.day, nth: nd.nthOfPeriod };
|
||||
if (rule.bySetPosition?.length === 1) return { day: nd.day, nth: rule.bySetPosition[0] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the rule is exactly what the plain Daily/Weekly/Monthly/Yearly
|
||||
* dropdown presets produce, i.e. it needs no custom editor to represent.
|
||||
*/
|
||||
export function isSimpleRecurrenceRule(rule: RecurrenceRule): boolean {
|
||||
return (
|
||||
(EDITOR_FREQUENCIES as string[]).includes(rule.frequency) &&
|
||||
(!rule.interval || rule.interval === 1) &&
|
||||
!rule.byDay?.length &&
|
||||
!rule.byMonthDay?.length &&
|
||||
!rule.byMonth?.length &&
|
||||
!rule.byYearDay?.length &&
|
||||
!rule.byWeekNo?.length &&
|
||||
!rule.bySetPosition?.length &&
|
||||
!rule.count &&
|
||||
!rule.until
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-readable summary of a recurrence rule, e.g.
|
||||
* "Every 2 months on the third Thursday · 12 occurrences".
|
||||
* Returns null for frequencies the UI cannot describe (hourly etc.).
|
||||
*/
|
||||
export function buildRecurrenceSummary(rule: RecurrenceRule): string | null {
|
||||
const interval = rule.interval || 1;
|
||||
let base: string;
|
||||
switch (rule.frequency) {
|
||||
case 'daily':
|
||||
base = interval > 1 ? `Every ${interval} days` : 'Daily';
|
||||
break;
|
||||
case 'weekly':
|
||||
base = interval > 1 ? `Every ${interval} weeks` : 'Weekly';
|
||||
break;
|
||||
case 'monthly':
|
||||
base = interval > 1 ? `Every ${interval} months` : 'Monthly';
|
||||
break;
|
||||
case 'yearly':
|
||||
base = interval > 1 ? `Every ${interval} years` : 'Yearly';
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
const parts = [base];
|
||||
|
||||
if (rule.frequency === 'weekly' && rule.byDay?.length) {
|
||||
const days = rule.byDay
|
||||
.filter((d) => WEEKDAYS.includes(d.day))
|
||||
.sort((a, b) => WEEKDAYS.indexOf(a.day) - WEEKDAYS.indexOf(b.day))
|
||||
.map((d) => weekdayName(d.day, 'short'))
|
||||
.join(', ');
|
||||
if (days) parts.push(`on ${days}`);
|
||||
}
|
||||
|
||||
if (rule.frequency === 'monthly' || rule.frequency === 'yearly') {
|
||||
if (rule.frequency === 'yearly' && rule.byMonth?.length) {
|
||||
const m = parseInt(rule.byMonth[0], 10);
|
||||
if (m >= 1 && m <= 12) parts.push(`in ${monthName(m)}`);
|
||||
}
|
||||
const nthDay = getNthDay(rule);
|
||||
if (nthDay) {
|
||||
parts.push(`on the ${nthLabel(nthDay.nth)} ${weekdayName(nthDay.day)}`);
|
||||
} else if (rule.byMonthDay?.length) {
|
||||
parts.push(`on day ${rule.byMonthDay[0]}`);
|
||||
}
|
||||
}
|
||||
|
||||
let summary = parts.join(' ');
|
||||
if (rule.count) {
|
||||
summary += ` · ${rule.count} ${rule.count === 1 ? 'occurrence' : 'occurrences'}`;
|
||||
} else if (rule.until) {
|
||||
const d = new Date(rule.until);
|
||||
if (!isNaN(d.getTime())) {
|
||||
summary += ` · until ${format(d, 'MMM d, yyyy')}`;
|
||||
}
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
export interface RecurrenceEditorValue {
|
||||
frequency: EditorFrequency;
|
||||
interval: number;
|
||||
weekDays: string[];
|
||||
monthlyMode: MonthlyMode;
|
||||
monthDay: number;
|
||||
nth: number;
|
||||
nthDay: string;
|
||||
month: number;
|
||||
endsMode: EndsMode;
|
||||
untilDate: string; // yyyy-MM-dd
|
||||
count: number;
|
||||
}
|
||||
|
||||
/** Build the editor's initial state from an existing rule (or defaults). */
|
||||
export function editorValueFromRule(
|
||||
rule: RecurrenceRule | null,
|
||||
eventStart: Date,
|
||||
): RecurrenceEditorValue {
|
||||
const startDay = INDEX_TO_DAY[eventStart.getDay()];
|
||||
const nthDayInfo = rule ? getNthDay(rule) : null;
|
||||
|
||||
const weekDays = (() => {
|
||||
if (rule?.frequency === 'weekly' && rule.byDay?.length) {
|
||||
const days = rule.byDay.map((d) => d.day).filter((d) => WEEKDAYS.includes(d));
|
||||
if (days.length) return days;
|
||||
}
|
||||
return [startDay];
|
||||
})();
|
||||
|
||||
const monthFromRule = rule?.byMonth?.length ? parseInt(rule.byMonth[0], 10) : NaN;
|
||||
const untilFromRule = (() => {
|
||||
if (rule?.until) {
|
||||
const d = new Date(rule.until);
|
||||
if (!isNaN(d.getTime())) return format(d, 'yyyy-MM-dd');
|
||||
}
|
||||
const inAYear = new Date(eventStart);
|
||||
inAYear.setFullYear(inAYear.getFullYear() + 1);
|
||||
return format(inAYear, 'yyyy-MM-dd');
|
||||
})();
|
||||
|
||||
return {
|
||||
frequency: rule && (EDITOR_FREQUENCIES as string[]).includes(rule.frequency)
|
||||
? (rule.frequency as EditorFrequency)
|
||||
: 'weekly',
|
||||
interval: rule?.interval || 1,
|
||||
weekDays,
|
||||
monthlyMode: nthDayInfo ? 'nth' : 'day',
|
||||
monthDay: rule?.byMonthDay?.[0] && rule.byMonthDay[0] >= 1 && rule.byMonthDay[0] <= 31
|
||||
? rule.byMonthDay[0]
|
||||
: eventStart.getDate(),
|
||||
nth: nthDayInfo && (nthDayInfo.nth === -1 || (nthDayInfo.nth >= 1 && nthDayInfo.nth <= 4))
|
||||
? nthDayInfo.nth
|
||||
: Math.min(4, Math.floor((eventStart.getDate() - 1) / 7) + 1),
|
||||
nthDay: nthDayInfo && WEEKDAYS.includes(nthDayInfo.day) ? nthDayInfo.day : startDay,
|
||||
month: monthFromRule >= 1 && monthFromRule <= 12 ? monthFromRule : eventStart.getMonth() + 1,
|
||||
endsMode: rule?.count ? 'after' : rule?.until ? 'on' : 'never',
|
||||
untilDate: untilFromRule,
|
||||
count: rule?.count ?? 12,
|
||||
};
|
||||
}
|
||||
|
||||
/** Build the JSCalendar rule the editor state describes. */
|
||||
export function buildRuleFromEditorValue(
|
||||
value: RecurrenceEditorValue,
|
||||
eventStart: Date,
|
||||
): RecurrenceRule {
|
||||
const startDay = INDEX_TO_DAY[eventStart.getDay()];
|
||||
const built: RecurrenceRule = {
|
||||
'@type': 'RecurrenceRule',
|
||||
frequency: value.frequency,
|
||||
interval: Math.max(1, value.interval),
|
||||
rscale: 'gregorian',
|
||||
skip: 'omit',
|
||||
firstDayOfWeek: 'mo',
|
||||
};
|
||||
|
||||
if (value.endsMode === 'after') {
|
||||
built.count = Math.max(1, value.count);
|
||||
} else if (value.endsMode === 'on' && value.untilDate) {
|
||||
built.until = `${value.untilDate}T23:59:59`;
|
||||
}
|
||||
|
||||
if (value.frequency === 'weekly') {
|
||||
const days = value.weekDays.length ? value.weekDays : [startDay];
|
||||
built.byDay = WEEKDAYS.filter((d) => days.includes(d)).map((day) => ({ day }));
|
||||
} else if (value.frequency === 'monthly' || value.frequency === 'yearly') {
|
||||
if (value.monthlyMode === 'nth') {
|
||||
built.byDay = [{ day: value.nthDay, nthOfPeriod: value.nth }];
|
||||
} else {
|
||||
built.byMonthDay = [Math.min(31, Math.max(1, value.monthDay))];
|
||||
}
|
||||
if (value.frequency === 'yearly') {
|
||||
built.byMonth = [String(value.month)];
|
||||
}
|
||||
}
|
||||
|
||||
return built;
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// Turn an email address into a JMAP server URL so the sign-in flow doesn't
|
||||
// have to open with a "Server URL" field nobody knows the answer to.
|
||||
//
|
||||
// The probe is deliberately cheap and short-lived: a GET of
|
||||
// `<base>/.well-known/jmap` against a handful of conventional hosts, all in
|
||||
// parallel, with a hard deadline. Discovery is an optimisation — if it comes
|
||||
// back empty the caller falls through to asking for the server by hand, so a
|
||||
// slow or hostile network must never be worse than typing it in.
|
||||
|
||||
import { secureFetch } from './client-cert';
|
||||
|
||||
export const DISCOVERY_TIMEOUT_MS = 2500;
|
||||
|
||||
const SCHEME_RE = /^([a-z][a-z0-9+.-]*):\/\//i;
|
||||
const EMAIL_RE = /^[^\s@]+@([^\s@]+\.[^\s@]+)$/;
|
||||
|
||||
/**
|
||||
* Accept what people actually type — `mail.example.com`, `example.com/`,
|
||||
* `https://mail.example.com/.well-known/jmap` — and return the base URL the
|
||||
* JMAP client expects, or null if it can't be one.
|
||||
*/
|
||||
export function normalizeServerUrl(input: string): string | null {
|
||||
let value = input.trim();
|
||||
if (!value) return null;
|
||||
|
||||
const scheme = SCHEME_RE.exec(value);
|
||||
if (scheme) {
|
||||
const protocol = scheme[1].toLowerCase();
|
||||
if (protocol !== 'http' && protocol !== 'https') return null;
|
||||
value = `${protocol}://${value.slice(scheme[0].length)}`;
|
||||
} else {
|
||||
value = `https://${value}`;
|
||||
}
|
||||
|
||||
// Someone pasting the endpoint they found in the webmail's settings gets the
|
||||
// same result as someone typing the address they use in the browser.
|
||||
value = value
|
||||
.replace(/\/+$/, '')
|
||||
.replace(/\/\.well-known\/jmap$/i, '')
|
||||
.replace(/\/jmap$/i, '')
|
||||
.replace(/\/+$/, '');
|
||||
|
||||
const host = value.slice(value.indexOf('://') + 3).split('/')[0];
|
||||
if (!host || /[\s@]/.test(host)) return null;
|
||||
|
||||
const hostname = host.split(':')[0].toLowerCase();
|
||||
if (!hostname) return null;
|
||||
if (!hostname.includes('.') && hostname !== 'localhost') return null;
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function emailDomain(email: string): string | null {
|
||||
const match = EMAIL_RE.exec(email.trim());
|
||||
return match ? match[1].toLowerCase() : null;
|
||||
}
|
||||
|
||||
export function isEmailAddress(value: string): boolean {
|
||||
return emailDomain(value) !== null;
|
||||
}
|
||||
|
||||
function hostOf(url: string): string {
|
||||
return url.slice(url.indexOf('://') + 3).split('/')[0].split(':')[0].toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Hosts worth probing for `domain`, most likely first. The order is also the
|
||||
* tie-break order when several respond.
|
||||
*/
|
||||
export function serverCandidates(domain: string): string[] {
|
||||
return [`https://${domain}`, `https://mail.${domain}`, `https://webmail.${domain}`];
|
||||
}
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, ms: number, fallback: T): Promise<T> {
|
||||
return new Promise<T>((resolve) => {
|
||||
const timer = setTimeout(() => resolve(fallback), ms);
|
||||
promise
|
||||
.then((value) => {
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
})
|
||||
.catch(() => {
|
||||
clearTimeout(timer);
|
||||
resolve(fallback);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function looksLikeSession(body: unknown): boolean {
|
||||
if (!body || typeof body !== 'object') return false;
|
||||
return 'capabilities' in body || 'apiUrl' in body || 'primaryAccounts' in body;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `baseUrl` looks like a JMAP server.
|
||||
*
|
||||
* A 401 counts as a hit — an unauthenticated probe of Stalwart's session
|
||||
* endpoint is *supposed* to be rejected, and that rejection is proof the
|
||||
* endpoint is there. A 200, on the other hand, has to actually contain a
|
||||
* session document: a captive portal or a catch-all web server will happily
|
||||
* answer 200 with HTML for any path we ask for.
|
||||
*/
|
||||
export async function probeJmapServer(
|
||||
baseUrl: string,
|
||||
timeoutMs: number = DISCOVERY_TIMEOUT_MS,
|
||||
): Promise<boolean> {
|
||||
const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
|
||||
const abortTimer = setTimeout(() => controller?.abort(), timeoutMs);
|
||||
|
||||
const request = (async () => {
|
||||
try {
|
||||
const response = await secureFetch(`${baseUrl}/.well-known/jmap`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal: controller?.signal,
|
||||
});
|
||||
if (response.status === 401) return true;
|
||||
if (response.status !== 200) return false;
|
||||
return looksLikeSession(await response.json());
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
|
||||
try {
|
||||
// The abort signal doesn't reach the native client-certificate path, so
|
||||
// race the whole thing rather than trusting the request to give up.
|
||||
return await withTimeout(request, timeoutMs, false);
|
||||
} finally {
|
||||
clearTimeout(abortTimer);
|
||||
}
|
||||
}
|
||||
|
||||
export interface DiscoveryOptions {
|
||||
/** Servers of already-registered accounts, trusted without a probe. */
|
||||
knownServerUrls?: string[];
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Best guess at the mail server for `email`, or null if nothing answered in
|
||||
* time. Callers treat null as "ask the user".
|
||||
*/
|
||||
export async function discoverServerForEmail(
|
||||
email: string,
|
||||
options: DiscoveryOptions = {},
|
||||
): Promise<string | null> {
|
||||
const domain = emailDomain(email);
|
||||
if (!domain) return null;
|
||||
|
||||
// A server we're already signed in to for this domain needs no probe, and
|
||||
// covers the common case of adding a second account on the same host.
|
||||
const known = (options.knownServerUrls ?? [])
|
||||
.map(normalizeServerUrl)
|
||||
.filter((url): url is string => url !== null);
|
||||
const alreadyKnown = known.find((url) => {
|
||||
const host = hostOf(url);
|
||||
return host === domain || host.endsWith(`.${domain}`);
|
||||
});
|
||||
if (alreadyKnown) return alreadyKnown;
|
||||
|
||||
const timeoutMs = options.timeoutMs ?? DISCOVERY_TIMEOUT_MS;
|
||||
const candidates = serverCandidates(domain);
|
||||
const results = await Promise.all(
|
||||
candidates.map(async (candidate) => ((await probeJmapServer(candidate, timeoutMs)) ? candidate : null)),
|
||||
);
|
||||
|
||||
// `find` keeps candidate order, so a bare domain wins over `mail.` even when
|
||||
// both answer.
|
||||
return results.find((url): url is string => url !== null) ?? null;
|
||||
}
|
||||
+100
-10
@@ -52,9 +52,13 @@ import { TasksSheet } from '../components/calendar/TasksSheet';
|
||||
import { ICalImportSheet } from '../components/calendar/ICalImportSheet';
|
||||
import { ICalSubscriptionSheet } from '../components/calendar/ICalSubscriptionSheet';
|
||||
import {
|
||||
applySharedCalendarColors,
|
||||
buildEventDayIndex,
|
||||
eventsOnDayFromIndex,
|
||||
pickUnusedCalendarColor,
|
||||
sharedCalendarColorKey,
|
||||
type EventDayIndex,
|
||||
type TimeFormat,
|
||||
} from '../lib/calendar-utils';
|
||||
import { buildReplyTo } from '../lib/calendar-invitation';
|
||||
import { generateBirthdayEvents, createBirthdayCalendar, BIRTHDAY_CALENDAR_ID } from '../lib/birthday-calendar';
|
||||
@@ -117,6 +121,9 @@ export default function CalendarScreen() {
|
||||
const calendarTimeFormat = useSettingsStore((s) => s.calendarTimeFormat);
|
||||
const showBirthdayCalendar = useSettingsStore((s) => s.showBirthdayCalendar);
|
||||
const enableCalendarTasks = useSettingsStore((s) => s.enableCalendarTasks);
|
||||
const sharedCalendarColors = useSettingsStore((s) => s.sharedCalendarColors);
|
||||
const setSharedCalendarColor = useSettingsStore((s) => s.setSharedCalendarColor);
|
||||
const removeSharedCalendarColor = useSettingsStore((s) => s.removeSharedCalendarColor);
|
||||
const contacts = useContactsStore((s) => s.contacts);
|
||||
|
||||
const [currentDate, setCurrentDate] = React.useState(new Date());
|
||||
@@ -154,7 +161,9 @@ export default function CalendarScreen() {
|
||||
const toggleTaskComplete = useCalendarStore((s) => s.toggleTaskComplete);
|
||||
const deleteTask = useCalendarStore((s) => s.deleteTask);
|
||||
const toggleCalendarVisibility = useCalendarStore((s) => s.toggleCalendarVisibility);
|
||||
const setDefaultCalendar = useCalendarStore((s) => s.setDefaultCalendar);
|
||||
const storeCalendars = useCalendarStore((s) => s.calendars);
|
||||
const taskOnlyCalendarIds = useCalendarStore((s) => s.taskOnlyCalendarIds);
|
||||
const hiddenCalendarIds = useCalendarStore((s) => s.hiddenCalendarIds);
|
||||
const loading = useCalendarStore((s) => s.loading);
|
||||
const error = useCalendarStore((s) => s.error);
|
||||
@@ -169,15 +178,69 @@ export default function CalendarScreen() {
|
||||
return generateBirthdayEvents(contacts, after.toISOString(), before.toISOString());
|
||||
}, [showBirthdayCalendar, contacts, viewMode, currentDate, calendarFirstDayOfWeek]);
|
||||
|
||||
// Per-viewer recolor (#345): shared calendars get the viewer's local color
|
||||
// override applied before anything renders. Personal calendars pass through.
|
||||
const displayCalendars = React.useMemo(
|
||||
() => applySharedCalendarColors(storeCalendars, sharedCalendarColors),
|
||||
[storeCalendars, sharedCalendarColors],
|
||||
);
|
||||
|
||||
// Auto-assign a random, not-yet-used palette color to any freshly shared
|
||||
// calendar so multiple shared calendars don't collide on one color. Runs
|
||||
// once per calendar (guarded by the presence of an existing key), and the
|
||||
// user can still overwrite it from the sidebar.
|
||||
React.useEffect(() => {
|
||||
const missing = storeCalendars.filter(
|
||||
(cal) => cal.isShared && !sharedCalendarColors[sharedCalendarColorKey(cal)],
|
||||
);
|
||||
if (missing.length === 0) return;
|
||||
// Seed "used" with personal calendar colors plus already-assigned shared
|
||||
// overrides so the picks stay distinct from what's already on screen.
|
||||
const used = new Set<string>();
|
||||
for (const cal of storeCalendars) {
|
||||
if (!cal.isShared && cal.color) used.add(cal.color.toLowerCase());
|
||||
}
|
||||
for (const color of Object.values(sharedCalendarColors)) {
|
||||
if (color) used.add(color.toLowerCase());
|
||||
}
|
||||
for (const cal of missing) {
|
||||
const color = pickUnusedCalendarColor(used);
|
||||
used.add(color.toLowerCase());
|
||||
setSharedCalendarColor(sharedCalendarColorKey(cal), color);
|
||||
}
|
||||
}, [storeCalendars, sharedCalendarColors, setSharedCalendarColor]);
|
||||
|
||||
const allCalendars = React.useMemo(
|
||||
() => (showBirthdayCalendar ? [...storeCalendars, createBirthdayCalendar()] : storeCalendars),
|
||||
[storeCalendars, showBirthdayCalendar],
|
||||
() => (showBirthdayCalendar ? [...displayCalendars, createBirthdayCalendar()] : displayCalendars),
|
||||
[displayCalendars, showBirthdayCalendar],
|
||||
);
|
||||
const allEvents = React.useMemo(
|
||||
() => (birthdayEvents.length > 0 ? [...storeEvents, ...birthdayEvents] : storeEvents),
|
||||
[storeEvents, birthdayEvents],
|
||||
);
|
||||
|
||||
// VTODO-only task lists (Todoist imports, per-project Thunderbird task
|
||||
// lists) are sibling CalDAV collections that Calendar/get returns alongside
|
||||
// event calendars. Their contents surface in the Tasks sheet, so keep them
|
||||
// out of the calendar drawer and out of the event/import calendar pickers —
|
||||
// listing them as calendars just produces duplicate/confusing entries. (#28)
|
||||
const eventCalendars = React.useMemo(() => {
|
||||
if (taskOnlyCalendarIds.length === 0) return allCalendars;
|
||||
const taskOnly = new Set(taskOnlyCalendarIds);
|
||||
return allCalendars.filter((cal) => !taskOnly.has(cal.id));
|
||||
}, [allCalendars, taskOnlyCalendarIds]);
|
||||
|
||||
// The Tasks sheet keeps the full list but with task lists sorted first, so
|
||||
// its create-picker (which defaults to the first writable calendar) targets
|
||||
// a dedicated task list when the account has one.
|
||||
const taskSheetCalendars = React.useMemo(() => {
|
||||
if (taskOnlyCalendarIds.length === 0) return allCalendars;
|
||||
const taskOnly = new Set(taskOnlyCalendarIds);
|
||||
return [...allCalendars].sort(
|
||||
(a, b) => Number(taskOnly.has(b.id)) - Number(taskOnly.has(a.id)),
|
||||
);
|
||||
}, [allCalendars, taskOnlyCalendarIds]);
|
||||
|
||||
const calendars = React.useMemo(
|
||||
() => allCalendars.filter((c) => !hiddenCalendarIds.includes(c.id)),
|
||||
[allCalendars, hiddenCalendarIds],
|
||||
@@ -252,25 +315,34 @@ export default function CalendarScreen() {
|
||||
[],
|
||||
);
|
||||
|
||||
// A recurring series member is a master (has recurrenceRules) or an expanded
|
||||
// occurrence (has recurrenceId) — those get the this/all scope dialog. Note:
|
||||
// we must NOT key off originalId here, since shared/group events now carry it
|
||||
// for id-namespacing even when they aren't recurring.
|
||||
const isRecurringSeriesMember = React.useCallback(
|
||||
(event: CalendarEvent) => !!event.recurrenceRules?.length || !!event.recurrenceId,
|
||||
[],
|
||||
);
|
||||
|
||||
const handleEditFromDetail = React.useCallback((event: CalendarEvent) => {
|
||||
if (isReadOnlyEvent(event)) { setDetailEvent(null); return; }
|
||||
setDetailEvent(null);
|
||||
if (event.recurrenceRules?.length || event.originalId) {
|
||||
if (isRecurringSeriesMember(event)) {
|
||||
setPendingAction({ kind: 'edit', event });
|
||||
} else {
|
||||
openEditDirect(event);
|
||||
}
|
||||
}, [openEditDirect, isReadOnlyEvent]);
|
||||
}, [openEditDirect, isReadOnlyEvent, isRecurringSeriesMember]);
|
||||
|
||||
const handleDeleteFromDetail = React.useCallback((event: CalendarEvent) => {
|
||||
if (isReadOnlyEvent(event)) { setDetailEvent(null); return; }
|
||||
setDetailEvent(null);
|
||||
if (event.recurrenceRules?.length || event.originalId) {
|
||||
if (isRecurringSeriesMember(event)) {
|
||||
setPendingAction({ kind: 'delete', event });
|
||||
} else {
|
||||
void deleteEvent(event.id);
|
||||
}
|
||||
}, [deleteEvent, isReadOnlyEvent]);
|
||||
}, [deleteEvent, isReadOnlyEvent, isRecurringSeriesMember]);
|
||||
|
||||
const handleScopeSelect = React.useCallback(
|
||||
async (scope: RecurrenceEditScope) => {
|
||||
@@ -420,6 +492,7 @@ export default function CalendarScreen() {
|
||||
events={events}
|
||||
eventsByDay={eventsByDay}
|
||||
calendars={calendars}
|
||||
timeFormat={calendarTimeFormat}
|
||||
onSelectEvent={setDetailEvent}
|
||||
/>
|
||||
)}
|
||||
@@ -436,6 +509,7 @@ export default function CalendarScreen() {
|
||||
date={selectedDate}
|
||||
eventsByDay={eventsByDay}
|
||||
calendars={calendars}
|
||||
timeFormat={calendarTimeFormat}
|
||||
onSelectEvent={setDetailEvent}
|
||||
refreshing={refreshing}
|
||||
onRefresh={onRefresh}
|
||||
@@ -447,6 +521,7 @@ export default function CalendarScreen() {
|
||||
<EventDetailSheet
|
||||
event={detailEvent}
|
||||
calendars={calendars}
|
||||
timeFormat={calendarTimeFormat}
|
||||
onClose={() => setDetailEvent(null)}
|
||||
onEdit={handleEditFromDetail}
|
||||
onDelete={handleDeleteFromDetail}
|
||||
@@ -469,7 +544,7 @@ export default function CalendarScreen() {
|
||||
<EventModal
|
||||
visible={modalVisible}
|
||||
event={modalEvent}
|
||||
calendars={allCalendars}
|
||||
calendars={eventCalendars}
|
||||
defaultDate={modalDate}
|
||||
onSave={handleSave}
|
||||
onDelete={handleDeleteFromModal}
|
||||
@@ -485,18 +560,25 @@ export default function CalendarScreen() {
|
||||
|
||||
<CalendarSidebarDrawer
|
||||
visible={sidebarVisible}
|
||||
calendars={allCalendars}
|
||||
calendars={eventCalendars}
|
||||
hiddenCalendarIds={hiddenCalendarIds}
|
||||
onToggle={toggleCalendarVisibility}
|
||||
onClose={() => setSidebarVisible(false)}
|
||||
onImport={() => { setSidebarVisible(false); setImportVisible(true); }}
|
||||
onManageSubscriptions={() => { setSidebarVisible(false); setSubscriptionsVisible(true); }}
|
||||
onSetDefault={(cal) => { void setDefaultCalendar(cal.id); }}
|
||||
onSetColor={(cal, color) => setSharedCalendarColor(sharedCalendarColorKey(cal), color)}
|
||||
onResetColor={(cal) => {
|
||||
// Drop the local override; the auto-assign effect picks a fresh
|
||||
// unused color (so it never reverts to a collision).
|
||||
removeSharedCalendarColor(sharedCalendarColorKey(cal));
|
||||
}}
|
||||
/>
|
||||
|
||||
<TasksSheet
|
||||
visible={tasksVisible}
|
||||
tasks={tasks}
|
||||
calendars={allCalendars}
|
||||
calendars={taskSheetCalendars}
|
||||
onClose={() => setTasksVisible(false)}
|
||||
onCreate={createTask}
|
||||
onToggle={toggleTaskComplete}
|
||||
@@ -505,7 +587,12 @@ export default function CalendarScreen() {
|
||||
|
||||
<ICalImportSheet
|
||||
visible={importVisible}
|
||||
calendars={storeCalendars}
|
||||
// Import batch-creates against the primary account, so only offer the
|
||||
// user's own event calendars (no shared calendars, no task lists) as
|
||||
// targets.
|
||||
calendars={eventCalendars.filter(
|
||||
(cal) => !cal.isShared && cal.id !== BIRTHDAY_CALENDAR_ID,
|
||||
)}
|
||||
onClose={() => setImportVisible(false)}
|
||||
onImport={importEvents}
|
||||
/>
|
||||
@@ -522,6 +609,7 @@ function DayEventList({
|
||||
date,
|
||||
eventsByDay,
|
||||
calendars,
|
||||
timeFormat,
|
||||
onSelectEvent,
|
||||
refreshing,
|
||||
onRefresh,
|
||||
@@ -529,6 +617,7 @@ function DayEventList({
|
||||
date: Date;
|
||||
eventsByDay: EventDayIndex;
|
||||
calendars: Calendar[];
|
||||
timeFormat?: TimeFormat;
|
||||
onSelectEvent?: (event: CalendarEvent) => void;
|
||||
refreshing: boolean;
|
||||
onRefresh: () => void;
|
||||
@@ -565,6 +654,7 @@ function DayEventList({
|
||||
key={event.id}
|
||||
event={event}
|
||||
calendars={calendars}
|
||||
timeFormat={timeFormat}
|
||||
onPress={onSelectEvent}
|
||||
/>
|
||||
))}
|
||||
|
||||
+129
-35
@@ -17,7 +17,7 @@ import * as FileSystem from 'expo-file-system/legacy';
|
||||
import { File as FsFile } from 'expo-file-system';
|
||||
import { spacing, radius, typography, componentSizes, type ThemePalette } from '../theme/tokens';
|
||||
import { useColors } from '../theme/colors';
|
||||
import { Button } from '../components';
|
||||
import { Button, IdentitySheet } from '../components';
|
||||
import RichTextEditor, {
|
||||
type RichTextEditorHandle,
|
||||
type RichTextSelectionState,
|
||||
@@ -26,6 +26,7 @@ import { useEmailStore } from '../stores/email-store';
|
||||
import { useContactsStore } from '../stores/contacts-store';
|
||||
import { useLocaleStore } from '../stores/locale-store';
|
||||
import { useSettingsStore } from '../stores/settings-store';
|
||||
import { useAccountStore } from '../stores/account-store';
|
||||
import { isGroup } from '../lib/contact-utils';
|
||||
import {
|
||||
getContactDisplayName,
|
||||
@@ -69,7 +70,16 @@ function parseRecipients(input: string): Recipient[] {
|
||||
.split(/[,;\n]/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
.map((email) => ({ name: '', email }));
|
||||
.map((s) => {
|
||||
const match = s.match(/^(.*?)\s*<([^\s@]+@[^\s@]+\.[^\s@]+)>$/);
|
||||
if (match) {
|
||||
return {
|
||||
name: match[1].replace(/^["']|["']$/g, '').trim(),
|
||||
email: match[2].trim(),
|
||||
};
|
||||
}
|
||||
return { name: '', email: s };
|
||||
});
|
||||
}
|
||||
|
||||
function formatBytes(n: number): string {
|
||||
@@ -113,10 +123,11 @@ function RecipientChip({ recipient, onRemove }: { recipient: Recipient; onRemove
|
||||
}
|
||||
|
||||
function SuggestionList({
|
||||
suggestions, onPick,
|
||||
suggestions, onPick, onPressIn,
|
||||
}: {
|
||||
suggestions: Array<{ contact: ContactCard; name: string; email: string }>;
|
||||
onPick: (s: { name: string; email: string }) => void;
|
||||
onPressIn?: () => void;
|
||||
}) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
@@ -127,6 +138,7 @@ function SuggestionList({
|
||||
return (
|
||||
<Pressable
|
||||
key={`${s.contact.id}-${s.email}-${i}`}
|
||||
onPressIn={onPressIn}
|
||||
onPress={() => onPick(s)}
|
||||
style={({ pressed }) => [styles.suggestionRow, pressed && styles.suggestionRowPressed]}
|
||||
>
|
||||
@@ -260,6 +272,7 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
const [identityError, setIdentityError] = React.useState<string | null>(null);
|
||||
const [sending, setSending] = React.useState(false);
|
||||
const [selectedIdentityId, setSelectedIdentityId] = React.useState<string | null>(null);
|
||||
const [identitySheetOpen, setIdentitySheetOpen] = React.useState(false);
|
||||
const [scheduleSheetOpen, setScheduleSheetOpen] = React.useState(false);
|
||||
// Custom date/time picker stage. iOS shows one 'datetime' spinner; Android
|
||||
// can only show one field at a time, so we walk date → time.
|
||||
@@ -343,6 +356,7 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
});
|
||||
|
||||
const editorRef = React.useRef<RichTextEditorHandle>(null);
|
||||
const isPickingSuggestion = React.useRef(false);
|
||||
// Track inline-image placeholders that haven't yet been rewritten to cid:
|
||||
// until send time. Maps cid → blobId/type/name/size.
|
||||
const inlineRegistryRef = React.useRef<Map<string, AttachmentEntry>>(new Map());
|
||||
@@ -375,6 +389,7 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
}, [suggestionQuery, individuals, alreadySelected]);
|
||||
|
||||
const pickSuggestion = (s: { name: string; email: string }) => {
|
||||
isPickingSuggestion.current = true;
|
||||
const recipient: Recipient = { name: s.name, email: s.email };
|
||||
if (activeField === 'cc') {
|
||||
setCcRecipients((prev) => [...prev, recipient]);
|
||||
@@ -405,34 +420,35 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
// original message (matches webmail's reply-identity behaviour).
|
||||
React.useEffect(() => {
|
||||
if (selectedIdentityId || identities.length === 0) return;
|
||||
const activeEmail = useAccountStore.getState().getActiveAccount()?.email || jmapClient.username;
|
||||
const defaultIdentity = identities.find(
|
||||
(i) => i.email.toLowerCase() === activeEmail?.toLowerCase()
|
||||
) ?? identities[0];
|
||||
|
||||
if (autoSelectReplyIdentity && replyTo) {
|
||||
const candidates = [...(replyTo.to ?? []), ...(replyTo.cc ?? [])];
|
||||
const candidateAddrs = new Set(
|
||||
candidates.map((r) => r.email?.toLowerCase()).filter(Boolean) as string[],
|
||||
);
|
||||
const matched = identities.find((i) => candidateAddrs.has(i.email.toLowerCase()));
|
||||
setSelectedIdentityId((matched ?? identities[0]).id);
|
||||
setSelectedIdentityId((matched ?? defaultIdentity).id);
|
||||
} else {
|
||||
setSelectedIdentityId(identities[0].id);
|
||||
setSelectedIdentityId(defaultIdentity.id);
|
||||
}
|
||||
}, [identities, autoSelectReplyIdentity, replyTo, selectedIdentityId]);
|
||||
|
||||
const primaryIdentity =
|
||||
identities.find((i) => i.id === selectedIdentityId) ?? identities[0];
|
||||
const primaryIdentity = React.useMemo(() => {
|
||||
if (identities.length === 0) return null;
|
||||
const activeEmail = useAccountStore.getState().getActiveAccount()?.email || jmapClient.username;
|
||||
const defaultIdentity = identities.find(
|
||||
(i) => i.email.toLowerCase() === activeEmail?.toLowerCase()
|
||||
) ?? identities[0];
|
||||
return identities.find((i) => i.id === selectedIdentityId) ?? defaultIdentity;
|
||||
}, [identities, selectedIdentityId]);
|
||||
|
||||
const openIdentityPicker = () => {
|
||||
if (identities.length <= 1) return;
|
||||
Alert.alert(
|
||||
t('email_composer.from', 'From'),
|
||||
undefined,
|
||||
[
|
||||
...identities.map((i) => ({
|
||||
text: i.name ? `${i.name} <${i.email}>` : i.email,
|
||||
onPress: () => setSelectedIdentityId(i.id),
|
||||
})),
|
||||
{ text: t('email_composer.cancel', 'Cancel'), style: 'cancel' as const },
|
||||
],
|
||||
);
|
||||
setIdentitySheetOpen(true);
|
||||
};
|
||||
|
||||
const commitTyped = () => {
|
||||
@@ -448,11 +464,33 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
const extraTo = parseRecipients(toInput);
|
||||
const extraCc = parseRecipients(ccInput);
|
||||
if (extraTo.length) {
|
||||
setToRecipients((prev) => [...prev, ...extraTo]);
|
||||
setToRecipients((prev) => {
|
||||
const existing = new Set(prev.map((r) => r.email.toLowerCase()));
|
||||
const unique: Recipient[] = [];
|
||||
for (const r of extraTo) {
|
||||
const emailLower = r.email.toLowerCase();
|
||||
if (!existing.has(emailLower)) {
|
||||
existing.add(emailLower);
|
||||
unique.push(r);
|
||||
}
|
||||
}
|
||||
return [...prev, ...unique];
|
||||
});
|
||||
setToInput('');
|
||||
}
|
||||
if (extraCc.length) {
|
||||
setCcRecipients((prev) => [...prev, ...extraCc]);
|
||||
setCcRecipients((prev) => {
|
||||
const existing = new Set(prev.map((r) => r.email.toLowerCase()));
|
||||
const unique: Recipient[] = [];
|
||||
for (const r of extraCc) {
|
||||
const emailLower = r.email.toLowerCase();
|
||||
if (!existing.has(emailLower)) {
|
||||
existing.add(emailLower);
|
||||
unique.push(r);
|
||||
}
|
||||
}
|
||||
return [...prev, ...unique];
|
||||
});
|
||||
setCcInput('');
|
||||
}
|
||||
};
|
||||
@@ -720,13 +758,13 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
// Catch the classic "I forgot the attachment" footgun. Only file attachments
|
||||
// count - inline images don't satisfy the user's intent of attaching a file.
|
||||
// Returns true if it's safe to proceed, false if the user cancelled.
|
||||
const passesAttachmentReminder = async (): Promise<boolean> => {
|
||||
const passesAttachmentReminder = async (html: string): Promise<boolean> => {
|
||||
if (!attachmentReminderEnabled) return true;
|
||||
const hasFileAttachment = attachments.some(
|
||||
(a) => !a.inline && a.blobId && !a.error,
|
||||
);
|
||||
if (hasFileAttachment) return true;
|
||||
const haystack = `${subject}\n${htmlToPlainText(bodyHtml)}`.toLowerCase();
|
||||
const haystack = `${subject}\n${htmlToPlainText(html)}`.toLowerCase();
|
||||
const matchedKeyword = attachmentReminderKeywords.find((kw) => {
|
||||
const k = kw.trim().toLowerCase();
|
||||
if (!k) return false;
|
||||
@@ -840,12 +878,33 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
|
||||
const performSend = async (holdForSeconds?: number, scheduledAt?: Date) => {
|
||||
if (!canSend || !primaryIdentity || !sentMailbox) return;
|
||||
if (!(await passesAttachmentReminder())) return;
|
||||
|
||||
// Read the body straight from the editor DOM at send time. The `change`
|
||||
// messages that feed `bodyHtml` are async and best-effort — trusting them
|
||||
// here once shipped replies with the typed text silently missing when the
|
||||
// page script had died (issue #9). If the editor doesn't answer we abort
|
||||
// loudly rather than send possibly-stale content.
|
||||
let liveBodyHtml: string;
|
||||
try {
|
||||
liveBodyHtml = (await editorRef.current?.getHtml()) ?? bodyHtml;
|
||||
} catch {
|
||||
Alert.alert(
|
||||
t('email_composer.send_failed', 'Send failed'),
|
||||
t(
|
||||
'email_composer.editor_unavailable',
|
||||
'Could not read the message content. Copy your text, then close and reopen the composer.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (liveBodyHtml !== bodyHtml) setBodyHtml(liveBodyHtml);
|
||||
|
||||
if (!(await passesAttachmentReminder(liveBodyHtml))) return;
|
||||
setSending(true);
|
||||
try {
|
||||
const from: EmailAddress[] = [{ name: primaryIdentity.name, email: primaryIdentity.email }];
|
||||
|
||||
const { html: rewrittenHtml, usedCids } = rewriteInlineImages(bodyHtml);
|
||||
const { html: rewrittenHtml, usedCids } = rewriteInlineImages(liveBodyHtml);
|
||||
// Belt-and-suspenders sanitization: the editor uses execCommand which
|
||||
// can preserve pasted <script>/<style>/etc. Strip them before sending.
|
||||
const safeHtml = stripDangerousTags(rewrittenHtml);
|
||||
@@ -976,7 +1035,7 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
<View style={[styles.flex, { paddingBottom: bottomPad }]}>
|
||||
<ScrollView
|
||||
style={styles.flex}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyboardShouldPersistTaps="always"
|
||||
contentContainerStyle={styles.scrollContent}
|
||||
>
|
||||
<View style={styles.fieldRow}>
|
||||
@@ -993,7 +1052,7 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<View style={styles.fieldRow}>
|
||||
<View style={[styles.fieldRow, { zIndex: 5 }]}>
|
||||
<Text style={styles.fieldLabel}>{t('email_composer.to', 'To')}</Text>
|
||||
<View style={styles.recipientField}>
|
||||
{toRecipients.map((r, i) => (
|
||||
@@ -1011,8 +1070,13 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
onChangeText={setToInput}
|
||||
onFocus={() => setActiveField('to')}
|
||||
onBlur={() => {
|
||||
addTyped();
|
||||
setTimeout(() => setActiveField((f) => (f === 'to' ? null : f)), 200);
|
||||
setTimeout(() => {
|
||||
if (!isPickingSuggestion.current) {
|
||||
addTyped();
|
||||
}
|
||||
setActiveField((f) => (f === 'to' ? null : f));
|
||||
isPickingSuggestion.current = false;
|
||||
}, 200);
|
||||
}}
|
||||
onSubmitEditing={addTyped}
|
||||
keyboardType="email-address"
|
||||
@@ -1021,7 +1085,13 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
/>
|
||||
</View>
|
||||
{activeField === 'to' && suggestions.length > 0 && (
|
||||
<SuggestionList suggestions={suggestions} onPick={pickSuggestion} />
|
||||
<SuggestionList
|
||||
suggestions={suggestions}
|
||||
onPick={pickSuggestion}
|
||||
onPressIn={() => {
|
||||
isPickingSuggestion.current = true;
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{!ccVisible && (
|
||||
<Pressable onPress={() => setCcVisible(true)} style={styles.ccToggle}>
|
||||
@@ -1031,7 +1101,7 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
</View>
|
||||
|
||||
{ccVisible && (
|
||||
<View style={styles.fieldRow}>
|
||||
<View style={[styles.fieldRow, { zIndex: 4 }]}>
|
||||
<Text style={styles.fieldLabel}>{t('email_composer.cc', 'Cc')}</Text>
|
||||
<View style={styles.recipientField}>
|
||||
{ccRecipients.map((r, i) => (
|
||||
@@ -1049,8 +1119,13 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
onChangeText={setCcInput}
|
||||
onFocus={() => setActiveField('cc')}
|
||||
onBlur={() => {
|
||||
addTyped();
|
||||
setTimeout(() => setActiveField((f) => (f === 'cc' ? null : f)), 200);
|
||||
setTimeout(() => {
|
||||
if (!isPickingSuggestion.current) {
|
||||
addTyped();
|
||||
}
|
||||
setActiveField((f) => (f === 'cc' ? null : f));
|
||||
isPickingSuggestion.current = false;
|
||||
}, 200);
|
||||
}}
|
||||
onSubmitEditing={addTyped}
|
||||
keyboardType="email-address"
|
||||
@@ -1059,7 +1134,13 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
/>
|
||||
</View>
|
||||
{activeField === 'cc' && suggestions.length > 0 && (
|
||||
<SuggestionList suggestions={suggestions} onPick={pickSuggestion} />
|
||||
<SuggestionList
|
||||
suggestions={suggestions}
|
||||
onPick={pickSuggestion}
|
||||
onPressIn={() => {
|
||||
isPickingSuggestion.current = true;
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
@@ -1293,6 +1374,14 @@ export default function ComposeScreen({ route, navigation }: Props) {
|
||||
onChange={onCustomPickerChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
<IdentitySheet
|
||||
visible={identitySheetOpen}
|
||||
onClose={() => setIdentitySheetOpen(false)}
|
||||
identities={identities}
|
||||
selectedIdentityId={selectedIdentityId}
|
||||
onPick={(identity) => setSelectedIdentityId(identity.id)}
|
||||
/>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
@@ -1332,6 +1421,7 @@ function makeStyles(c: ThemePalette) {
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: c.borderLight,
|
||||
gap: spacing.md,
|
||||
position: 'relative',
|
||||
},
|
||||
fieldLabel: {
|
||||
...typography.body,
|
||||
@@ -1374,12 +1464,16 @@ function makeStyles(c: ThemePalette) {
|
||||
paddingVertical: 6,
|
||||
},
|
||||
suggestionBox: {
|
||||
marginTop: spacing.xs,
|
||||
marginLeft: 60,
|
||||
position: 'absolute',
|
||||
top: '100%',
|
||||
left: spacing.lg + 56 + spacing.md,
|
||||
right: spacing.lg,
|
||||
borderWidth: 1,
|
||||
borderColor: c.borderLight,
|
||||
borderRadius: radius.sm,
|
||||
backgroundColor: c.card,
|
||||
zIndex: 20,
|
||||
elevation: 5,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
suggestionRow: {
|
||||
|
||||
@@ -24,8 +24,8 @@ import { useSettingsStore, type SwipeAction } from '../stores/settings-store';
|
||||
import { useKeywordsStore } from '../stores/keywords-store';
|
||||
import { useLocaleStore } from '../stores/locale-store';
|
||||
import { formatListDate } from '../lib/date-format';
|
||||
import { findTrashMailbox, findArchiveMailbox, findJunkMailbox } from '../lib/mailbox-tree';
|
||||
import type { Email } from '../api/types';
|
||||
|
||||
function getSenderName(email: Email): string {
|
||||
return email.from?.[0]?.name || email.from?.[0]?.email || 'Unknown';
|
||||
}
|
||||
@@ -46,6 +46,9 @@ function isPinned(email: Email): boolean {
|
||||
return !!email.keywords?.$important;
|
||||
}
|
||||
|
||||
// Height of the sender line when the avatar is hidden (extra-compact density),
|
||||
// used to anchor the unread dot on that first line.
|
||||
const UNREAD_DOT_TEXT_LINE = 20;
|
||||
|
||||
const EmailRow = React.memo(function EmailRow({
|
||||
item,
|
||||
@@ -92,6 +95,14 @@ const EmailRow = React.memo(function EmailRow({
|
||||
onLongPress={handleLongPress}
|
||||
delayLongPress={300}
|
||||
>
|
||||
{unread && (
|
||||
<View
|
||||
style={[
|
||||
styles.unreadDot,
|
||||
{ top: density.rowPaddingVertical + (density.showAvatar ? componentSizes.avatarMd : UNREAD_DOT_TEXT_LINE) / 2 - 4 },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
{selectionMode && (
|
||||
<View style={styles.rowCheckboxWrap}>
|
||||
{selected ? (
|
||||
@@ -164,6 +175,7 @@ interface EmailListScreenProps {
|
||||
export default function EmailListScreen({ onEmailPress, onComposePress }: EmailListScreenProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const { t } = useLocaleStore();
|
||||
const [drawerOpen, setDrawerOpen] = React.useState(false);
|
||||
const [filterMenuOpen, setFilterMenuOpen] = React.useState(false);
|
||||
const emails = useEmailStore((s) => s.emails);
|
||||
@@ -232,15 +244,15 @@ export default function EmailListScreen({ onEmailPress, onComposePress }: EmailL
|
||||
}, [emails, disableThreading]);
|
||||
|
||||
const archiveMailboxId = React.useMemo(
|
||||
() => mailboxes.find((m) => m.role === 'archive')?.id ?? null,
|
||||
() => findArchiveMailbox(mailboxes)?.id ?? null,
|
||||
[mailboxes],
|
||||
);
|
||||
const trashMailboxId = React.useMemo(
|
||||
() => mailboxes.find((m) => m.role === 'trash')?.id ?? null,
|
||||
() => findTrashMailbox(mailboxes)?.id ?? null,
|
||||
[mailboxes],
|
||||
);
|
||||
const junkMailboxId = React.useMemo(
|
||||
() => mailboxes.find((m) => m.role === 'junk' || m.role === 'spam')?.id ?? null,
|
||||
() => findJunkMailbox(mailboxes)?.id ?? null,
|
||||
[mailboxes],
|
||||
);
|
||||
|
||||
@@ -336,16 +348,31 @@ export default function EmailListScreen({ onEmailPress, onComposePress }: EmailL
|
||||
case 'archive':
|
||||
if (archiveMailboxId && currentMailboxId !== archiveMailboxId) {
|
||||
void archiveEmailAction(id);
|
||||
} else if (!archiveMailboxId) {
|
||||
Alert.alert(
|
||||
t('email_list.error', 'Error'),
|
||||
t('email_list.no_archive_folder', 'Could not find an Archive folder on the server.'),
|
||||
);
|
||||
}
|
||||
break;
|
||||
case 'delete':
|
||||
if (trashMailboxId) {
|
||||
void deleteEmailAction(id, trashMailboxId, currentMailboxId);
|
||||
} else {
|
||||
Alert.alert(
|
||||
t('email_list.error', 'Error'),
|
||||
t('email_list.no_trash_folder', 'Could not find a Trash folder on the server. Please check your mailbox configuration.'),
|
||||
);
|
||||
}
|
||||
break;
|
||||
case 'spam':
|
||||
if (junkMailboxId && currentMailboxId !== junkMailboxId) {
|
||||
void moveToMailboxAction(id, currentMailboxId, junkMailboxId);
|
||||
} else if (!junkMailboxId) {
|
||||
Alert.alert(
|
||||
t('email_list.error', 'Error'),
|
||||
t('email_list.no_junk_folder', 'Could not find a Spam/Junk folder on the server.'),
|
||||
);
|
||||
}
|
||||
break;
|
||||
case 'read':
|
||||
@@ -365,7 +392,7 @@ export default function EmailListScreen({ onEmailPress, onComposePress }: EmailL
|
||||
}, [
|
||||
currentMailboxId, archiveMailboxId, trashMailboxId, junkMailboxId,
|
||||
moveToMailboxAction, archiveEmailAction, deleteEmailAction,
|
||||
markRead, markUnread, toggleStar, togglePin,
|
||||
markRead, markUnread, toggleStar, togglePin, t,
|
||||
]);
|
||||
|
||||
const renderEmailRow = React.useCallback(
|
||||
@@ -433,7 +460,7 @@ export default function EmailListScreen({ onEmailPress, onComposePress }: EmailL
|
||||
};
|
||||
|
||||
const handleBulkDelete = async () => {
|
||||
const trash = mailboxes.find((m) => m.role === 'trash');
|
||||
const trash = findTrashMailbox(mailboxes);
|
||||
if (!trash || !currentMailboxId) {
|
||||
clearSelection();
|
||||
return;
|
||||
@@ -1349,6 +1376,20 @@ function makeStyles(c: ThemePalette) {
|
||||
},
|
||||
emailRowPressed: { backgroundColor: c.surface },
|
||||
emailRowSelected: { backgroundColor: c.selection },
|
||||
// Mirrors the webmail's unread indicator: an 8px filled circle at the row's
|
||||
// start edge, vertically centered (email-list-item.tsx, fill-unread). The
|
||||
// weight/color change alone is too subtle on some device fonts (#27).
|
||||
// `top` is set per row: the dot is anchored on the row's *first* line (top
|
||||
// padding + half an avatar), not on the row's midpoint, which would drop it
|
||||
// a full line below the checkbox and avatar it reads as a column with.
|
||||
unreadDot: {
|
||||
position: 'absolute',
|
||||
left: 4,
|
||||
width: 8,
|
||||
height: 8,
|
||||
borderRadius: 4,
|
||||
backgroundColor: c.unread,
|
||||
},
|
||||
rowCheckboxWrap: {
|
||||
width: 16,
|
||||
height: componentSizes.avatarMd,
|
||||
|
||||
+195
-208
@@ -1,8 +1,9 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
View, Text, StyleSheet, ScrollView, Pressable, ActivityIndicator,
|
||||
Modal, useWindowDimensions, Animated, Easing, Alert, PanResponder,
|
||||
Modal, useWindowDimensions, Animated, Easing, Alert, FlatList,
|
||||
} from 'react-native';
|
||||
import type { NativeSyntheticEvent, NativeScrollEvent } from 'react-native';
|
||||
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
|
||||
import {
|
||||
@@ -28,6 +29,8 @@ import { setEmailKeywords } from '../api/email';
|
||||
import { shareEmailEml, shareAttachment, downloadAttachment } from '../lib/email-export';
|
||||
import { useKeywordsStore, keywordToken, type KeywordDef } from '../stores/keywords-store';
|
||||
import { useSheetDrag } from '../lib/use-sheet-drag';
|
||||
import { useLocaleStore } from '../stores/locale-store';
|
||||
import { findTrashMailbox } from '../lib/mailbox-tree';
|
||||
import type { Email, Mailbox } from '../api/types';
|
||||
import type { RootStackParamList } from '../navigation/types';
|
||||
|
||||
@@ -35,8 +38,13 @@ type Props = NativeStackScreenProps<RootStackParamList, 'EmailThread'>;
|
||||
|
||||
function formatHeaderDate(iso: string): string {
|
||||
const d = new Date(iso);
|
||||
return d.toLocaleString(undefined, {
|
||||
return d.toLocaleDateString(undefined, {
|
||||
weekday: 'short', year: 'numeric', month: 'short', day: 'numeric',
|
||||
});
|
||||
}
|
||||
|
||||
function formatHeaderTime(iso: string): string {
|
||||
return new Date(iso).toLocaleTimeString(undefined, {
|
||||
hour: '2-digit', minute: '2-digit',
|
||||
});
|
||||
}
|
||||
@@ -59,6 +67,7 @@ function plainTextBody(email: Email): string {
|
||||
export default function EmailThreadScreen({ route, navigation }: Props) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const { t } = useLocaleStore();
|
||||
const { jmapAccountId } = route.params;
|
||||
// The displayed email is tracked in local state (not a route param) so that
|
||||
// swiping / Prev-Next can switch messages in place without remounting the
|
||||
@@ -99,103 +108,65 @@ export default function EmailThreadScreen({ route, navigation }: Props) {
|
||||
[activeEmailId, cacheVersion, detailCache],
|
||||
);
|
||||
|
||||
// --- Swipe / slide navigation between adjacent emails -------------------
|
||||
// A three-pane pager: [prev | current | next] are laid out in a single row of
|
||||
// width 3×screen and kept mounted side by side. `drag` translates the whole
|
||||
// row so the neighbour's real content follows the finger — no blank gap and
|
||||
// no late content-swap. At rest the row is shifted left by one screen so the
|
||||
// middle (current) pane sits on screen. After a settled swipe we re-point
|
||||
// `activeEmailId` at the neighbour and reset `drag` to 0 in the same commit;
|
||||
// because the landed pane already shows that exact message, the recentre is
|
||||
// seamless. Refs keep the (memoised once) PanResponder reading the latest
|
||||
// neighbours / dimensions without being recreated every render.
|
||||
const drag = React.useRef(new Animated.Value(0)).current;
|
||||
const animatingRef = React.useRef(false);
|
||||
const pendingRecentreRef = React.useRef(false);
|
||||
const prevEmailRef = React.useRef(prevEmail);
|
||||
const nextEmailRef = React.useRef(nextEmail);
|
||||
const windowWidthRef = React.useRef(windowWidth);
|
||||
prevEmailRef.current = prevEmail;
|
||||
nextEmailRef.current = nextEmail;
|
||||
windowWidthRef.current = windowWidth;
|
||||
// --- Pager -------------------------------------------------------------
|
||||
// The pager is a horizontal, page-snapping FlatList over the mailbox's
|
||||
// `emails`. Native scroll provides the swipe + snap (and plays nicely with
|
||||
// each pane's vertical body scroll); Prev/Next scroll programmatically. When
|
||||
// scrolling settles, the centred page's id becomes `activeEmailId`, which is
|
||||
// what the toolbar and action handlers operate on.
|
||||
const listRef = React.useRef<FlatList<Email>>(null);
|
||||
// The page to open on mount — the entry point arrives as a route param, so
|
||||
// capture its index once.
|
||||
const initialIndexRef = React.useRef(
|
||||
Math.max(0, emails.findIndex((e) => e.id === route.params.emailId)),
|
||||
);
|
||||
|
||||
const switchEmail = React.useCallback((direction: 'prev' | 'next') => {
|
||||
const target = direction === 'next' ? nextEmailRef.current : prevEmailRef.current;
|
||||
if (!target || animatingRef.current) return;
|
||||
animatingRef.current = true;
|
||||
const w = windowWidthRef.current;
|
||||
// Bring the neighbour pane to centre: next sits to the right (slide row
|
||||
// left → -w), prev sits to the left (slide row right → +w).
|
||||
const out = direction === 'next' ? -w : w;
|
||||
// Coalesced detail fetch: stores the result in the shared cache and bumps the
|
||||
// version so every mounted pane (and the toolbar) re-reads it. Concurrent
|
||||
// calls for the same id share a single in-flight request.
|
||||
const inFlight = React.useRef(new Map<string, Promise<Email | null>>()).current;
|
||||
const ensureDetail = React.useCallback((id: string): Promise<Email | null> => {
|
||||
const pending = inFlight.get(id);
|
||||
if (pending) return pending;
|
||||
const p = getEmailDetail(id, jmapAccountId)
|
||||
.then((fetched) => { detailCache.set(id, fetched); bumpCache(); return fetched; })
|
||||
.catch(() => detailCache.get(id) ?? null)
|
||||
.finally(() => { inFlight.delete(id); });
|
||||
inFlight.set(id, p);
|
||||
return p;
|
||||
}, [getEmailDetail, jmapAccountId, detailCache, bumpCache, inFlight]);
|
||||
|
||||
// Best-effort: ensure the target detail is cached so the recentred pane has
|
||||
// content. Neighbours are normally prefetched, so this is usually a no-op.
|
||||
if (!detailCache.has(target.id)) {
|
||||
getEmailDetail(target.id, jmapAccountId)
|
||||
.then((e) => { detailCache.set(target.id, e); bumpCache(); })
|
||||
.catch(() => { /* the load effect will retry once it becomes active */ });
|
||||
}
|
||||
// Slide to a page by index and reflect it in the toolbar immediately; a swipe
|
||||
// that settles on the same page confirms the same id via onMomentumEnd.
|
||||
const goToIndex = React.useCallback((index: number) => {
|
||||
if (index < 0 || index >= emails.length) return;
|
||||
listRef.current?.scrollToOffset({ offset: index * windowWidth, animated: true });
|
||||
const target = emails[index];
|
||||
if (target) setActiveEmailId(target.id);
|
||||
}, [emails, windowWidth]);
|
||||
|
||||
Animated.timing(drag, {
|
||||
toValue: out, duration: 230, easing: Easing.out(Easing.cubic), useNativeDriver: true,
|
||||
}).start(({ finished }) => {
|
||||
if (!finished) { animatingRef.current = false; return; }
|
||||
// Re-point at the neighbour; the drag reset happens in the layout effect
|
||||
// below, in the same commit that re-keys the panes. Resetting here would
|
||||
// recentre the row while the *old* arrangement is still on screen,
|
||||
// flashing the previous email for a frame until React catches up.
|
||||
pendingRecentreRef.current = true;
|
||||
setActiveEmailId(target.id);
|
||||
});
|
||||
}, [drag, detailCache, getEmailDetail, jmapAccountId, bumpCache]);
|
||||
const switchEmailRef = React.useRef(switchEmail);
|
||||
switchEmailRef.current = switchEmail;
|
||||
// Adopt the centred page as the active message once a swipe settles.
|
||||
const onMomentumEnd = React.useCallback((e: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
const index = Math.round(e.nativeEvent.contentOffset.x / windowWidth);
|
||||
const target = emails[index];
|
||||
if (target && target.id !== activeEmailId) setActiveEmailId(target.id);
|
||||
}, [emails, windowWidth, activeEmailId]);
|
||||
|
||||
// Recentre the row in the same commit that re-pointed the panes: the pane
|
||||
// that slid to centre is now the middle pane (same key, same mounted
|
||||
// WebView), so snapping the translation back to 0 is invisible.
|
||||
// Page offsets are in window-width units, so a rotation / resize invalidates
|
||||
// the scroll position — re-centre the active page after the width changes.
|
||||
React.useLayoutEffect(() => {
|
||||
if (!pendingRecentreRef.current) return;
|
||||
pendingRecentreRef.current = false;
|
||||
drag.setValue(0);
|
||||
animatingRef.current = false;
|
||||
}, [activeEmailId, drag]);
|
||||
const index = emails.findIndex((e) => e.id === activeEmailId);
|
||||
if (index >= 0) listRef.current?.scrollToOffset({ offset: index * windowWidth, animated: false });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [windowWidth]);
|
||||
|
||||
const panResponder = React.useRef(
|
||||
PanResponder.create({
|
||||
onMoveShouldSetPanResponder: (_, g) => {
|
||||
if (animatingRef.current) return false;
|
||||
if (Math.abs(g.dx) < 10) return false;
|
||||
// Only claim clearly-horizontal drags so the body's vertical scroll
|
||||
// (and link taps) keep working.
|
||||
return Math.abs(g.dx) > Math.abs(g.dy) * 1.5;
|
||||
},
|
||||
onPanResponderMove: (_, g) => {
|
||||
let dx = g.dx;
|
||||
// Rubber-band when there's no neighbour to reach in that direction.
|
||||
if ((dx > 0 && !prevEmailRef.current) || (dx < 0 && !nextEmailRef.current)) {
|
||||
dx *= 0.25;
|
||||
}
|
||||
drag.setValue(dx);
|
||||
},
|
||||
onPanResponderRelease: (_, g) => {
|
||||
const w = windowWidthRef.current;
|
||||
const threshold = Math.min(w * 0.28, 120);
|
||||
const fast = Math.abs(g.vx) > 0.5;
|
||||
if ((g.dx <= -threshold || (fast && g.vx < 0)) && nextEmailRef.current) {
|
||||
switchEmailRef.current('next');
|
||||
} else if ((g.dx >= threshold || (fast && g.vx > 0)) && prevEmailRef.current) {
|
||||
switchEmailRef.current('prev');
|
||||
} else {
|
||||
Animated.spring(drag, { toValue: 0, useNativeDriver: true, speed: 20, bounciness: 6 }).start();
|
||||
}
|
||||
},
|
||||
onPanResponderTerminate: () => {
|
||||
Animated.spring(drag, { toValue: 0, useNativeDriver: true, speed: 20, bounciness: 6 }).start();
|
||||
},
|
||||
onPanResponderTerminationRequest: () => true,
|
||||
}),
|
||||
).current;
|
||||
// While the body is pinch-zoomed (or a pinch is in flight) horizontal
|
||||
// gestures pan the zoomed content, so the pager must not treat them as page
|
||||
// swipes. Prev/Next stay usable: programmatic scrollToOffset ignores
|
||||
// scrollEnabled. Reset when the active message changes — the zoomed pane's
|
||||
// WebView can unmount without reporting back.
|
||||
const [pagerLocked, setPagerLocked] = React.useState(false);
|
||||
React.useEffect(() => { setPagerLocked(false); }, [activeEmailId]);
|
||||
|
||||
const mailAttachmentAction = useSettingsStore((s) => s.mailAttachmentAction);
|
||||
const attachmentPosition = useSettingsStore((s) => s.attachmentPosition);
|
||||
@@ -239,30 +210,26 @@ export default function EmailThreadScreen({ route, navigation }: Props) {
|
||||
React.useEffect(() => {
|
||||
let cancelled = false;
|
||||
let readTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
// If we already have this message cached (e.g. it was prefetched as a
|
||||
// neighbour) it renders immediately; otherwise the pane shows a skeleton
|
||||
// until the fetch below lands. Either way, refresh in the background.
|
||||
// Refresh the active message — a cached copy (the pane may have fetched it,
|
||||
// or it was visited before) renders immediately while this lands. Then mark
|
||||
// it read per the user's delay. The pane itself fetches its own detail, so
|
||||
// ensureDetail here usually rides the same in-flight request.
|
||||
setError(null);
|
||||
void (async () => {
|
||||
try {
|
||||
const fetched = await getEmailDetail(activeEmailId, jmapAccountId);
|
||||
if (cancelled) return;
|
||||
detailCache.set(activeEmailId, fetched);
|
||||
bumpCache();
|
||||
if (fetched && !fetched.keywords?.$seen) {
|
||||
if (markAsReadDelay > 0) {
|
||||
readTimer = setTimeout(() => {
|
||||
if (!cancelled) void markRead(activeEmailId, jmapAccountId);
|
||||
}, markAsReadDelay);
|
||||
} else {
|
||||
void markRead(activeEmailId, jmapAccountId);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Only surface the error if we have nothing to show; a cached copy is
|
||||
// better than an error screen when the refresh fails.
|
||||
if (!cancelled && !detailCache.has(activeEmailId)) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load email');
|
||||
const fetched = await ensureDetail(activeEmailId);
|
||||
if (cancelled) return;
|
||||
if (!fetched) {
|
||||
// Only surface an error if there's nothing cached to show.
|
||||
if (!detailCache.has(activeEmailId)) setError('Failed to load email');
|
||||
return;
|
||||
}
|
||||
if (!fetched.keywords?.$seen) {
|
||||
if (markAsReadDelay > 0) {
|
||||
readTimer = setTimeout(() => {
|
||||
if (!cancelled) void markRead(activeEmailId, jmapAccountId);
|
||||
}, markAsReadDelay);
|
||||
} else {
|
||||
void markRead(activeEmailId, jmapAccountId);
|
||||
}
|
||||
}
|
||||
})();
|
||||
@@ -270,20 +237,7 @@ export default function EmailThreadScreen({ route, navigation }: Props) {
|
||||
cancelled = true;
|
||||
if (readTimer) clearTimeout(readTimer);
|
||||
};
|
||||
}, [activeEmailId, jmapAccountId, getEmailDetail, markRead, markAsReadDelay, detailCache, bumpCache]);
|
||||
|
||||
// Prefetch the adjacent messages so their pane is already populated when the
|
||||
// pager slides it into view. Best-effort and silent; bump the cache version
|
||||
// on arrival so the off-screen neighbour pane renders its content.
|
||||
React.useEffect(() => {
|
||||
for (const neighbour of [prevEmail, nextEmail]) {
|
||||
if (neighbour && !detailCache.has(neighbour.id)) {
|
||||
getEmailDetail(neighbour.id, jmapAccountId)
|
||||
.then((e) => { detailCache.set(neighbour.id, e); bumpCache(); })
|
||||
.catch(() => { /* ignore — prefetch is best-effort */ });
|
||||
}
|
||||
}
|
||||
}, [prevEmail, nextEmail, getEmailDetail, jmapAccountId, detailCache, bumpCache]);
|
||||
}, [activeEmailId, ensureDetail, markRead, markAsReadDelay, jmapAccountId, detailCache]);
|
||||
|
||||
const starred = !!email?.keywords?.$flagged;
|
||||
const unread = !!email && !email.keywords?.$seen;
|
||||
@@ -348,8 +302,14 @@ export default function EmailThreadScreen({ route, navigation }: Props) {
|
||||
|
||||
const onDelete = () => {
|
||||
if (!email || !currentMailboxId) return;
|
||||
const trash = mailboxes.find((m) => m.role === 'trash');
|
||||
if (!trash) return;
|
||||
const trash = findTrashMailbox(mailboxes);
|
||||
if (!trash) {
|
||||
Alert.alert(
|
||||
t('email_list.error', 'Error'),
|
||||
t('email_list.no_trash_folder', 'Could not find a Trash folder on the server. Please check your mailbox configuration.'),
|
||||
);
|
||||
return;
|
||||
}
|
||||
void deleteEmail(email.id, trash.id, currentMailboxId);
|
||||
navigation.goBack();
|
||||
};
|
||||
@@ -549,43 +509,53 @@ export default function EmailThreadScreen({ route, navigation }: Props) {
|
||||
</View>
|
||||
) : (
|
||||
<>
|
||||
{/* Three-pane pager: [prev | current | next] live side by side in a
|
||||
row shifted left by one screen, so a horizontal drag slides the
|
||||
neighbour's already-rendered content into view with no gap. */}
|
||||
<View style={styles.pagerViewport}>
|
||||
<Animated.View
|
||||
style={[
|
||||
styles.pagerRow,
|
||||
{ width: windowWidth * 3, left: -windowWidth, transform: [{ translateX: drag }] },
|
||||
]}
|
||||
{...panResponder.panHandlers}
|
||||
>
|
||||
{[prevEmail?.id ?? null, activeEmailId, nextEmail?.id ?? null].map((id, i) => (
|
||||
<View key={id ?? `empty-${i}`} style={{ width: windowWidth }}>
|
||||
{id ? (
|
||||
<EmailPane
|
||||
email={detailCache.get(id) ?? null}
|
||||
c={c}
|
||||
styles={styles}
|
||||
bottomBarHeight={bottomBarHeight}
|
||||
attachmentPosition={attachmentPosition}
|
||||
hideInlineImageAttachments={hideInlineImageAttachments}
|
||||
downloadingBlobId={downloadingBlobId}
|
||||
onToggleStar={toggleStarFor}
|
||||
onPressAttachment={onPressAttachment}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
))}
|
||||
</Animated.View>
|
||||
</View>
|
||||
{/* Pager: a horizontal page-snapping list over the mailbox. Each
|
||||
page is the full-width pane for one message; native scroll slides
|
||||
between them and onMomentumEnd reports the settled page. */}
|
||||
<FlatList
|
||||
ref={listRef}
|
||||
style={styles.pagerViewport}
|
||||
data={emails}
|
||||
extraData={cacheVersion}
|
||||
keyExtractor={(item) => item.id}
|
||||
horizontal
|
||||
pagingEnabled
|
||||
showsHorizontalScrollIndicator={false}
|
||||
initialScrollIndex={initialIndexRef.current}
|
||||
getItemLayout={(_, index) => ({ length: windowWidth, offset: windowWidth * index, index })}
|
||||
windowSize={3}
|
||||
initialNumToRender={1}
|
||||
maxToRenderPerBatch={2}
|
||||
removeClippedSubviews
|
||||
scrollEnabled={!pagerLocked}
|
||||
onMomentumScrollEnd={onMomentumEnd}
|
||||
renderItem={({ item, index }) => (
|
||||
<View style={{ width: windowWidth }}>
|
||||
<EmailPane
|
||||
id={item.id}
|
||||
email={detailCache.get(item.id) ?? null}
|
||||
ensureDetail={ensureDetail}
|
||||
c={c}
|
||||
styles={styles}
|
||||
bottomBarHeight={bottomBarHeight}
|
||||
attachmentPosition={attachmentPosition}
|
||||
hideInlineImageAttachments={hideInlineImageAttachments}
|
||||
downloadingBlobId={downloadingBlobId}
|
||||
onToggleStar={toggleStarFor}
|
||||
onPressAttachment={onPressAttachment}
|
||||
onSwipe={(dir) => goToIndex(dir === 'next' ? index + 1 : index - 1)}
|
||||
onZoomChange={(z) => setPagerLocked(z.pinching || z.zoomed)}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Bottom action bar */}
|
||||
<View style={[styles.bottomBar, { paddingBottom: Math.max(insets.bottom, 4) }]}>
|
||||
<BottomBarButton
|
||||
icon={<ChevronLeft size={20} color={c.textMuted} />}
|
||||
label="Prev"
|
||||
onPress={prevEmail ? () => switchEmail('prev') : undefined}
|
||||
onPress={prevEmail ? () => goToIndex(currentIndex - 1) : undefined}
|
||||
disabled={!prevEmail}
|
||||
/>
|
||||
{bottomActions.map((id) => {
|
||||
@@ -603,7 +573,7 @@ export default function EmailThreadScreen({ route, navigation }: Props) {
|
||||
<BottomBarButton
|
||||
icon={<ChevronRight size={20} color={c.textMuted} />}
|
||||
label="Next"
|
||||
onPress={nextEmail ? () => switchEmail('next') : undefined}
|
||||
onPress={nextEmail ? () => goToIndex(currentIndex + 1) : undefined}
|
||||
disabled={!nextEmail}
|
||||
/>
|
||||
</View>
|
||||
@@ -668,7 +638,9 @@ export default function EmailThreadScreen({ route, navigation }: Props) {
|
||||
}
|
||||
|
||||
interface EmailPaneProps {
|
||||
id: string;
|
||||
email: Email | null;
|
||||
ensureDetail: (id: string) => Promise<Email | null>;
|
||||
c: ThemePalette;
|
||||
styles: ReturnType<typeof makeStyles>;
|
||||
bottomBarHeight: number;
|
||||
@@ -677,6 +649,8 @@ interface EmailPaneProps {
|
||||
downloadingBlobId: string | null;
|
||||
onToggleStar: (email: Email) => void;
|
||||
onPressAttachment: (email: Email, blobId: string, name: string | undefined, type: string | undefined) => void;
|
||||
onSwipe: (direction: 'prev' | 'next') => void;
|
||||
onZoomChange: (zoom: { pinching: boolean; zoomed: boolean }) => void;
|
||||
}
|
||||
|
||||
// One swipeable page: the scrollable subject / sender / attachments / body for a
|
||||
@@ -685,14 +659,25 @@ interface EmailPaneProps {
|
||||
// scroll position and "show all attachments" toggle, and renders directly from
|
||||
// the email passed to it — neighbours show real content, not a placeholder.
|
||||
function EmailPane({
|
||||
email, c, styles, bottomBarHeight, attachmentPosition,
|
||||
hideInlineImageAttachments, downloadingBlobId, onToggleStar, onPressAttachment,
|
||||
id, email, ensureDetail, c, styles, bottomBarHeight, attachmentPosition,
|
||||
hideInlineImageAttachments, downloadingBlobId, onToggleStar, onPressAttachment, onSwipe,
|
||||
onZoomChange,
|
||||
}: EmailPaneProps) {
|
||||
const [attachmentsExpanded, setAttachmentsExpanded] = React.useState(false);
|
||||
// Freeze the pane's vertical scroll while a pinch is in flight so a two-
|
||||
// finger zoom can't fling the page; while merely zoomed, vertical scrolling
|
||||
// stays on — it is how the user pans the (taller) zoomed content vertically.
|
||||
const [pinching, setPinching] = React.useState(false);
|
||||
|
||||
// Detail not fetched yet (initial open, or a neighbour the prefetch hasn't
|
||||
// caught up with). Show a skeleton of the pane layout instead of a spinner
|
||||
// so the transition into real content doesn't jump.
|
||||
// Each pane owns loading its own message: when the list mounts this page and
|
||||
// its detail isn't cached yet, fetch it (coalesced upstream). The shared
|
||||
// cache then re-renders the pane with real content.
|
||||
React.useEffect(() => {
|
||||
if (!email) void ensureDetail(id);
|
||||
}, [id, email, ensureDetail]);
|
||||
|
||||
// Detail not fetched yet. Show a skeleton of the pane layout instead of a
|
||||
// spinner so the transition into real content doesn't jump.
|
||||
if (!email) {
|
||||
return <EmailPaneSkeleton styles={styles} />;
|
||||
}
|
||||
@@ -763,26 +748,19 @@ function EmailPane({
|
||||
<ScrollView
|
||||
style={styles.scroll}
|
||||
contentContainerStyle={{ paddingBottom: bottomBarHeight + spacing.lg }}
|
||||
scrollEnabled={!pinching}
|
||||
>
|
||||
{/* Subject block */}
|
||||
<View style={styles.subjectBlock}>
|
||||
<View style={styles.subjectRow}>
|
||||
<View style={styles.subjectMain}>
|
||||
<Pressable onPress={() => onToggleStar(email)} hitSlop={8} style={styles.subjectStar}>
|
||||
<Star
|
||||
size={18}
|
||||
color={starred ? c.starred : c.textMuted}
|
||||
fill={starred ? c.starred : 'transparent'}
|
||||
/>
|
||||
</Pressable>
|
||||
<Text style={styles.subjectText}>{subject}</Text>
|
||||
</View>
|
||||
<View style={styles.subjectMeta}>
|
||||
<Text style={styles.subjectDate}>{formatHeaderDate(email.receivedAt)}</Text>
|
||||
{email.size > 0 && (
|
||||
<Text style={styles.subjectSize}>{formatSize(email.size)}</Text>
|
||||
)}
|
||||
</View>
|
||||
<Text style={styles.subjectText}>{subject}</Text>
|
||||
<Pressable onPress={() => onToggleStar(email)} hitSlop={8} style={styles.subjectStar}>
|
||||
<Star
|
||||
size={18}
|
||||
color={starred ? c.starred : c.textMuted}
|
||||
fill={starred ? c.starred : 'transparent'}
|
||||
/>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -806,6 +784,13 @@ function EmailPane({
|
||||
{email.to?.map((t) => t.name || t.email).join(', ') || '-'}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.senderMeta}>
|
||||
<Text style={styles.senderDate}>{formatHeaderDate(email.receivedAt)}</Text>
|
||||
<Text style={styles.senderTime}>
|
||||
{formatHeaderTime(email.receivedAt)}
|
||||
{email.size > 0 ? ` · ${formatSize(email.size)}` : ''}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
{attachmentPosition === 'beside-sender' && renderAttachments()}
|
||||
</View>
|
||||
@@ -818,7 +803,12 @@ function EmailPane({
|
||||
|
||||
{/* Body */}
|
||||
<View style={styles.bodyBlock}>
|
||||
<EmailBodyView email={email} senderEmail={from?.email} />
|
||||
<EmailBodyView
|
||||
email={email}
|
||||
senderEmail={from?.email}
|
||||
onSwipe={onSwipe}
|
||||
onZoomChange={(z) => { setPinching(z.pinching); onZoomChange(z); }}
|
||||
/>
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
@@ -845,8 +835,7 @@ function EmailPaneSkeleton({ styles }: { styles: ReturnType<typeof makeStyles> }
|
||||
return (
|
||||
<Animated.View style={[styles.scroll, { opacity: pulse }]}>
|
||||
<View style={styles.subjectBlock}>
|
||||
<View style={[styles.skeletonBone, { height: 20, width: '78%' }]} />
|
||||
<View style={[styles.skeletonBone, { height: 12, width: '36%', marginTop: spacing.sm }]} />
|
||||
<View style={[styles.skeletonBone, { height: 20, width: '88%' }]} />
|
||||
</View>
|
||||
<View style={styles.senderBlock}>
|
||||
<View style={styles.senderRow}>
|
||||
@@ -856,6 +845,10 @@ function EmailPaneSkeleton({ styles }: { styles: ReturnType<typeof makeStyles> }
|
||||
<View style={[styles.skeletonBone, { height: 11, width: '70%', marginTop: 6 }]} />
|
||||
<View style={[styles.skeletonBone, { height: 11, width: '45%', marginTop: 6 }]} />
|
||||
</View>
|
||||
<View style={styles.senderMeta}>
|
||||
<View style={[styles.skeletonBone, { height: 11, width: 86 }]} />
|
||||
<View style={[styles.skeletonBone, { height: 11, width: 64, marginTop: 6 }]} />
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.skeletonBody}>
|
||||
@@ -1188,9 +1181,8 @@ function makeStyles(c: ThemePalette) {
|
||||
padding: spacing.lg,
|
||||
},
|
||||
errorText: { ...typography.body, color: c.error, textAlign: 'center' },
|
||||
// Pager: a clipping viewport with a 3-screen-wide row of panes inside it.
|
||||
pagerViewport: { flex: 1, overflow: 'hidden', backgroundColor: c.background },
|
||||
pagerRow: { position: 'absolute', top: 0, bottom: 0, flexDirection: 'row' },
|
||||
// Pager: the horizontal page-snapping list fills the area between the bars.
|
||||
pagerViewport: { flex: 1, backgroundColor: c.background },
|
||||
scroll: { flex: 1, backgroundColor: c.background },
|
||||
|
||||
// Subject block
|
||||
@@ -1206,12 +1198,6 @@ function makeStyles(c: ThemePalette) {
|
||||
alignItems: 'flex-start',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
subjectMain: {
|
||||
flex: 1,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'flex-start',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
subjectStar: {
|
||||
paddingTop: 4,
|
||||
},
|
||||
@@ -1223,18 +1209,6 @@ function makeStyles(c: ThemePalette) {
|
||||
color: c.text,
|
||||
letterSpacing: -0.2,
|
||||
},
|
||||
subjectMeta: {
|
||||
alignItems: 'flex-end',
|
||||
},
|
||||
subjectDate: {
|
||||
...typography.caption,
|
||||
color: c.textSecondary,
|
||||
},
|
||||
subjectSize: {
|
||||
...typography.caption,
|
||||
color: c.textMuted,
|
||||
marginTop: 2,
|
||||
},
|
||||
|
||||
// Sender block
|
||||
senderBlock: {
|
||||
@@ -1267,6 +1241,19 @@ function makeStyles(c: ThemePalette) {
|
||||
senderRecipientsLabel: {
|
||||
color: c.textMuted,
|
||||
},
|
||||
senderMeta: {
|
||||
alignItems: 'flex-end',
|
||||
paddingTop: 1,
|
||||
},
|
||||
senderDate: {
|
||||
...typography.caption,
|
||||
color: c.textSecondary,
|
||||
},
|
||||
senderTime: {
|
||||
...typography.caption,
|
||||
color: c.textMuted,
|
||||
marginTop: 2,
|
||||
},
|
||||
|
||||
// Attachments
|
||||
attachmentsBlock: {
|
||||
|
||||
+187
-87
@@ -16,7 +16,7 @@ import {
|
||||
import {
|
||||
ChevronLeft, FileText, Folder, FolderPlus, HardDrive, FileImage, FileVideo,
|
||||
FileAudio, FileArchive, FileSpreadsheet, FileCode2, LayoutGrid, List as ListIcon,
|
||||
MoreVertical, Pencil, Share2, Trash2, Upload, X, Download,
|
||||
MoreVertical, Pencil, Share2, Trash2, Upload, Users, X, Download,
|
||||
} from 'lucide-react-native';
|
||||
|
||||
// expo-document-picker is loaded lazily on first upload. Its native module
|
||||
@@ -38,9 +38,8 @@ function loadDocumentPicker(): DocumentPickerModule | null {
|
||||
}
|
||||
|
||||
import {
|
||||
createFolder, deleteWithDescendants, getAllFileNodes, isDirectChildOfPrefix,
|
||||
isDirectory, nodeDisplayName, pathToPrefix, PATH_SEP, renameFileNode,
|
||||
uploadFileNode,
|
||||
createFolder, deleteFileNodes, getAllFileNodesAcrossAccounts, isCrossAccountId,
|
||||
isFolder, renameFileNode, supportsSharing, uploadFileNode,
|
||||
} from '../api/files';
|
||||
import { downloadAttachment, shareAttachment } from '../lib/email-export';
|
||||
import type { FileNode } from '../api/types';
|
||||
@@ -48,9 +47,9 @@ import { spacing, radius, typography, type ThemePalette } from '../theme/tokens'
|
||||
import { useColors } from '../theme/colors';
|
||||
import { useSettingsStore, type FilesViewMode } from '../stores/settings-store';
|
||||
import Dialog from '../components/Dialog';
|
||||
import ShareSheet from '../components/files/ShareSheet';
|
||||
|
||||
// A file row carries the resolved display name alongside the original
|
||||
// server-side name (the path-encoded `node.name` field).
|
||||
// A file row carries the display name alongside the rest of the node.
|
||||
interface FileRow extends FileNode {
|
||||
displayName: string;
|
||||
}
|
||||
@@ -108,7 +107,10 @@ export default function FilesScreen() {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
|
||||
const [path, setPath] = useState<string[]>([]);
|
||||
// Folder navigation stack. Hierarchy is real parentId nesting (#379) — each
|
||||
// entry is the folder's node id (namespaced "accountId:nodeId" inside a
|
||||
// shared-with-me subtree) plus its name for the breadcrumb.
|
||||
const [path, setPath] = useState<{ id: string; name: string }[]>([]);
|
||||
const [allNodes, setAllNodes] = useState<FileNode[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
@@ -124,6 +126,7 @@ export default function FilesScreen() {
|
||||
const [renameTarget, setRenameTarget] = useState<FileRow | null>(null);
|
||||
const [renameValue, setRenameValue] = useState('');
|
||||
const [actionsTarget, setActionsTarget] = useState<FileRow | null>(null);
|
||||
const [shareTarget, setShareTarget] = useState<FileRow | null>(null);
|
||||
|
||||
const showIcons = useSettingsStore((s) => s.filesShowIcons);
|
||||
const coloredIcons = useSettingsStore((s) => s.filesColoredIcons);
|
||||
@@ -137,8 +140,13 @@ export default function FilesScreen() {
|
||||
const viewMode: FilesViewMode = viewOverride ?? defaultViewMode;
|
||||
|
||||
const selectionMode = selection.size > 0;
|
||||
const prefix = useMemo(() => pathToPrefix(path), [path]);
|
||||
const headerName = path.length === 0 ? 'Files' : path[path.length - 1];
|
||||
const currentParentId = path.length === 0 ? null : path[path.length - 1].id;
|
||||
// True while browsing inside a folder another principal shared with us.
|
||||
// Creates/uploads would have to route to the owner's account, which this
|
||||
// screen doesn't do (matches the webmail's Files app); writes are hidden.
|
||||
const inSharedSubtree = isCrossAccountId(currentParentId);
|
||||
const headerName = path.length === 0 ? 'Files' : path[path.length - 1].name;
|
||||
const sharingEnabled = supportsSharing();
|
||||
|
||||
const loadFiles = useCallback(
|
||||
async (mode: 'initial' | 'refresh' = 'initial') => {
|
||||
@@ -146,7 +154,9 @@ export default function FilesScreen() {
|
||||
else setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const nodes = await getAllFileNodes();
|
||||
// One fetch across all accessible accounts: own files plus nodes other
|
||||
// principals shared with us (tagged isShared, ids namespaced).
|
||||
const nodes = await getAllFileNodesAcrossAccounts();
|
||||
setAllNodes(nodes);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load files');
|
||||
@@ -162,33 +172,49 @@ export default function FilesScreen() {
|
||||
void loadFiles();
|
||||
}, [loadFiles]);
|
||||
|
||||
// If we navigated into a folder that no longer exists (it was deleted, or
|
||||
// we never had it), walk back up until we land on one that does. The check
|
||||
// looks for a directory node whose serverName matches the encoded path.
|
||||
// If we navigated into a folder that no longer exists (deleted, or its
|
||||
// share was revoked), cut the stack back to the deepest ancestor that does.
|
||||
useEffect(() => {
|
||||
if (allNodes.length === 0) return;
|
||||
setPath((prev) => {
|
||||
let next = prev;
|
||||
while (next.length > 0) {
|
||||
const parentPrefix = pathToPrefix(next.slice(0, -1));
|
||||
const expectedName = parentPrefix + next[next.length - 1];
|
||||
const exists = allNodes.some((n) => n.name === expectedName && isDirectory(n));
|
||||
if (exists) break;
|
||||
next = next.slice(0, -1);
|
||||
const byId = new Map(allNodes.map((n) => [n.id, n]));
|
||||
let cut = prev.length;
|
||||
for (let i = 0; i < prev.length; i++) {
|
||||
const node = byId.get(prev[i].id);
|
||||
if (!node || !isFolder(node)) {
|
||||
cut = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return next.length === prev.length ? prev : next;
|
||||
return cut === prev.length ? prev : prev.slice(0, cut);
|
||||
});
|
||||
}, [allNodes]);
|
||||
|
||||
const visibleFiles = useMemo<FileRow[]>(() => {
|
||||
const rows = allNodes
|
||||
.filter((n) => isDirectChildOfPrefix(n, prefix))
|
||||
.map<FileRow>((n) => ({ ...n, displayName: nodeDisplayName(n, prefix) }))
|
||||
let nodes: FileNode[];
|
||||
if (currentParentId === null) {
|
||||
// Root: our own top-level nodes, plus the roots of every shared-with-me
|
||||
// subtree (a shared node whose parent isn't visible to us).
|
||||
const idSet = new Set(allNodes.map((n) => n.id));
|
||||
nodes = allNodes.filter((n) =>
|
||||
n.isShared
|
||||
? n.parentId == null || !idSet.has(n.parentId)
|
||||
: (n.parentId ?? null) === null,
|
||||
);
|
||||
} else {
|
||||
nodes = allNodes.filter((n) => (n.parentId ?? null) === currentParentId);
|
||||
}
|
||||
const rows = nodes
|
||||
.map<FileRow>((n) => ({ ...n, displayName: n.name }))
|
||||
.filter((r) => showHiddenFiles || !r.displayName.startsWith('.'));
|
||||
const dir = sortDir === 'desc' ? -1 : 1;
|
||||
return rows.sort((a, b) => {
|
||||
const aDir = isDirectory(a) ? 0 : 1;
|
||||
const bDir = isDirectory(b) ? 0 : 1;
|
||||
// Own content first, shared-with-me entries after (root only).
|
||||
const aShared = a.isShared ? 1 : 0;
|
||||
const bShared = b.isShared ? 1 : 0;
|
||||
if (aShared !== bShared) return aShared - bShared;
|
||||
const aDir = isFolder(a) ? 0 : 1;
|
||||
const bDir = isFolder(b) ? 0 : 1;
|
||||
if (aDir !== bDir) return aDir - bDir;
|
||||
switch (sortKey) {
|
||||
case 'size':
|
||||
@@ -203,15 +229,18 @@ export default function FilesScreen() {
|
||||
return a.displayName.localeCompare(b.displayName) * dir;
|
||||
}
|
||||
});
|
||||
}, [allNodes, prefix, showHiddenFiles, sortKey, sortDir]);
|
||||
}, [allNodes, currentParentId, showHiddenFiles, sortKey, sortDir]);
|
||||
|
||||
const clearSelection = useCallback(() => setSelection(new Set()), []);
|
||||
|
||||
const toggleSelect = useCallback((id: string) => {
|
||||
// Shared-with-me rows stay out of multi-select: batch delete routes to our
|
||||
// own account and would fail (or worse, mismatch) on namespaced ids.
|
||||
const toggleSelect = useCallback((row: FileRow) => {
|
||||
if (row.isShared) return;
|
||||
setSelection((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
if (next.has(row.id)) next.delete(row.id);
|
||||
else next.add(row.id);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
@@ -220,7 +249,7 @@ export default function FilesScreen() {
|
||||
if (!row.blobId) return;
|
||||
setBusyId(row.id);
|
||||
try {
|
||||
await shareAttachment(row.blobId, row.displayName, row.type);
|
||||
await shareAttachment(row.blobId, row.displayName, row.type, undefined, row.accountId);
|
||||
} catch (e) {
|
||||
Alert.alert('Preview failed', e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
@@ -232,7 +261,7 @@ export default function FilesScreen() {
|
||||
if (!row.blobId) return;
|
||||
setBusyId(row.id);
|
||||
try {
|
||||
await downloadAttachment(row.blobId, row.displayName, row.type);
|
||||
await downloadAttachment(row.blobId, row.displayName, row.type, undefined, row.accountId);
|
||||
} catch (e) {
|
||||
Alert.alert('Download failed', e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
@@ -243,11 +272,11 @@ export default function FilesScreen() {
|
||||
const handleRowPress = useCallback(
|
||||
(row: FileRow) => {
|
||||
if (selectionMode) {
|
||||
toggleSelect(row.id);
|
||||
toggleSelect(row);
|
||||
return;
|
||||
}
|
||||
if (isDirectory(row)) {
|
||||
setPath((p) => [...p, row.displayName]);
|
||||
if (isFolder(row)) {
|
||||
setPath((p) => [...p, { id: row.id, name: row.displayName }]);
|
||||
return;
|
||||
}
|
||||
void previewFile(row);
|
||||
@@ -256,7 +285,7 @@ export default function FilesScreen() {
|
||||
);
|
||||
|
||||
const handleRowLongPress = useCallback((row: FileRow) => {
|
||||
toggleSelect(row.id);
|
||||
toggleSelect(row);
|
||||
}, [toggleSelect]);
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
@@ -277,19 +306,19 @@ export default function FilesScreen() {
|
||||
const submitNewFolder = useCallback(async () => {
|
||||
const name = newFolderName.trim();
|
||||
if (!name) return;
|
||||
if (name.includes(PATH_SEP) || name.includes('/')) {
|
||||
if (name.includes('/')) {
|
||||
Alert.alert('Invalid name', 'Folder names cannot contain "/".');
|
||||
return;
|
||||
}
|
||||
setNewFolderOpen(false);
|
||||
setNewFolderName('');
|
||||
try {
|
||||
await createFolder(name, path);
|
||||
await createFolder(name, currentParentId);
|
||||
await loadFiles('refresh');
|
||||
} catch (e) {
|
||||
Alert.alert('Create folder failed', e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}, [newFolderName, path, loadFiles]);
|
||||
}, [newFolderName, currentParentId, loadFiles]);
|
||||
|
||||
const submitRename = useCallback(async () => {
|
||||
if (!renameTarget) return;
|
||||
@@ -298,7 +327,7 @@ export default function FilesScreen() {
|
||||
setRenameTarget(null);
|
||||
return;
|
||||
}
|
||||
if (name.includes(PATH_SEP) || name.includes('/')) {
|
||||
if (name.includes('/')) {
|
||||
Alert.alert('Invalid name', 'Names cannot contain "/".');
|
||||
return;
|
||||
}
|
||||
@@ -306,12 +335,12 @@ export default function FilesScreen() {
|
||||
setRenameTarget(null);
|
||||
setRenameValue('');
|
||||
try {
|
||||
await renameFileNode(target, name, path, allNodes);
|
||||
await renameFileNode(target.id, name);
|
||||
await loadFiles('refresh');
|
||||
} catch (e) {
|
||||
Alert.alert('Rename failed', e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}, [renameTarget, renameValue, path, allNodes, loadFiles]);
|
||||
}, [renameTarget, renameValue, loadFiles]);
|
||||
|
||||
const startUpload = useCallback(async () => {
|
||||
if (uploading) return;
|
||||
@@ -341,7 +370,7 @@ export default function FilesScreen() {
|
||||
asset.uri,
|
||||
asset.name,
|
||||
asset.mimeType || 'application/octet-stream',
|
||||
path,
|
||||
currentParentId,
|
||||
);
|
||||
await loadFiles('refresh');
|
||||
} catch (e) {
|
||||
@@ -349,7 +378,7 @@ export default function FilesScreen() {
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}, [uploading, path, loadFiles]);
|
||||
}, [uploading, currentParentId, loadFiles]);
|
||||
|
||||
const requestDelete = useCallback((rows: FileRow[]) => {
|
||||
if (rows.length === 0) return;
|
||||
@@ -362,12 +391,13 @@ export default function FilesScreen() {
|
||||
setConfirmDelete(null);
|
||||
clearSelection();
|
||||
try {
|
||||
await deleteWithDescendants(targets, allNodes);
|
||||
// The server removes folder descendants (onDestroyRemoveChildren).
|
||||
await deleteFileNodes(targets.map((t) => t.id));
|
||||
await loadFiles('refresh');
|
||||
} catch (e) {
|
||||
Alert.alert('Delete failed', e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}, [confirmDelete, allNodes, clearSelection, loadFiles]);
|
||||
}, [confirmDelete, clearSelection, loadFiles]);
|
||||
|
||||
const renderHeader = () => {
|
||||
const canBack = path.length > 0;
|
||||
@@ -409,27 +439,31 @@ export default function FilesScreen() {
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.headerActions}>
|
||||
<Pressable
|
||||
onPress={() => setNewFolderOpen(true)}
|
||||
hitSlop={8}
|
||||
style={styles.headerBtn}
|
||||
accessibilityLabel="New folder"
|
||||
>
|
||||
<FolderPlus size={20} color={c.text} />
|
||||
</Pressable>
|
||||
<Pressable
|
||||
onPress={() => void startUpload()}
|
||||
hitSlop={8}
|
||||
style={styles.headerBtn}
|
||||
accessibilityLabel="Upload file"
|
||||
disabled={uploading}
|
||||
>
|
||||
{uploading ? (
|
||||
<ActivityIndicator size="small" color={c.text} />
|
||||
) : (
|
||||
<Upload size={20} color={c.text} />
|
||||
)}
|
||||
</Pressable>
|
||||
{!inSharedSubtree ? (
|
||||
<Pressable
|
||||
onPress={() => setNewFolderOpen(true)}
|
||||
hitSlop={8}
|
||||
style={styles.headerBtn}
|
||||
accessibilityLabel="New folder"
|
||||
>
|
||||
<FolderPlus size={20} color={c.text} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
{!inSharedSubtree ? (
|
||||
<Pressable
|
||||
onPress={() => void startUpload()}
|
||||
hitSlop={8}
|
||||
style={styles.headerBtn}
|
||||
accessibilityLabel="Upload file"
|
||||
disabled={uploading}
|
||||
>
|
||||
{uploading ? (
|
||||
<ActivityIndicator size="small" color={c.text} />
|
||||
) : (
|
||||
<Upload size={20} color={c.text} />
|
||||
)}
|
||||
</Pressable>
|
||||
) : null}
|
||||
<Pressable
|
||||
onPress={toggleView}
|
||||
hitSlop={8}
|
||||
@@ -442,7 +476,7 @@ export default function FilesScreen() {
|
||||
</View>
|
||||
{canBack ? (
|
||||
<Text style={styles.breadcrumb} numberOfLines={1}>
|
||||
{['Files', ...path].join(' / ')}
|
||||
{['Files', ...path.map((p) => p.name)].join(' / ')}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
@@ -450,13 +484,14 @@ export default function FilesScreen() {
|
||||
};
|
||||
|
||||
const renderRow = (item: FileRow) => {
|
||||
const isDir = isDirectory(item);
|
||||
const isDir = isFolder(item);
|
||||
const Icon = isDir ? Folder : pickFileIcon(item.displayName);
|
||||
const tint = isDir
|
||||
? (coloredIcons ? c.calendar.blue : c.textMuted)
|
||||
: (coloredIcons ? fileIconColor(item.displayName, c) : c.textMuted);
|
||||
const selected = selection.has(item.id);
|
||||
const busy = busyId === item.id;
|
||||
const sharedOut = !!item.shareWith && Object.keys(item.shareWith).length > 0;
|
||||
return (
|
||||
<Pressable
|
||||
onPress={() => handleRowPress(item)}
|
||||
@@ -470,10 +505,22 @@ export default function FilesScreen() {
|
||||
>
|
||||
{showIcons && <Icon size={20} color={tint} />}
|
||||
<View style={styles.fileInfo}>
|
||||
<Text style={styles.fileName} numberOfLines={1}>
|
||||
{item.displayName}
|
||||
</Text>
|
||||
<View style={styles.fileNameRow}>
|
||||
<Text style={styles.fileName} numberOfLines={1}>
|
||||
{item.displayName}
|
||||
</Text>
|
||||
{item.isShared ? (
|
||||
<Share2 size={13} color={c.primary} />
|
||||
) : sharedOut ? (
|
||||
<Users size={13} color={c.primary} />
|
||||
) : null}
|
||||
</View>
|
||||
<View style={styles.fileMetaRow}>
|
||||
{item.isShared && item.accountName ? (
|
||||
<Text style={styles.fileMeta} numberOfLines={1}>
|
||||
Shared by {item.accountName}
|
||||
</Text>
|
||||
) : null}
|
||||
{item.size != null && !isDir ? (
|
||||
<Text style={styles.fileMeta}>{formatFileSize(item.size)}</Text>
|
||||
) : null}
|
||||
@@ -501,12 +548,13 @@ export default function FilesScreen() {
|
||||
};
|
||||
|
||||
const renderGridCell = (item: FileRow) => {
|
||||
const isDir = isDirectory(item);
|
||||
const isDir = isFolder(item);
|
||||
const Icon = isDir ? Folder : pickFileIcon(item.displayName);
|
||||
const tint = isDir
|
||||
? (coloredIcons ? c.calendar.blue : c.textMuted)
|
||||
: (coloredIcons ? fileIconColor(item.displayName, c) : c.textMuted);
|
||||
const selected = selection.has(item.id);
|
||||
const sharedOut = !!item.shareWith && Object.keys(item.shareWith).length > 0;
|
||||
return (
|
||||
<Pressable
|
||||
onPress={() => handleRowPress(item)}
|
||||
@@ -523,10 +571,21 @@ export default function FilesScreen() {
|
||||
) : (
|
||||
<View style={{ width: 36, height: 36 }} />
|
||||
)}
|
||||
<Text style={styles.gridName} numberOfLines={2}>
|
||||
{item.displayName}
|
||||
</Text>
|
||||
{item.size != null && !isDir ? (
|
||||
<View style={styles.gridNameRow}>
|
||||
<Text style={styles.gridName} numberOfLines={2}>
|
||||
{item.displayName}
|
||||
</Text>
|
||||
{item.isShared ? (
|
||||
<Share2 size={12} color={c.primary} />
|
||||
) : sharedOut ? (
|
||||
<Users size={12} color={c.primary} />
|
||||
) : null}
|
||||
</View>
|
||||
{item.isShared && item.accountName ? (
|
||||
<Text style={styles.gridMeta} numberOfLines={1}>
|
||||
Shared by {item.accountName}
|
||||
</Text>
|
||||
) : item.size != null && !isDir ? (
|
||||
<Text style={styles.gridMeta} numberOfLines={1}>
|
||||
{formatFileSize(item.size)}
|
||||
</Text>
|
||||
@@ -627,6 +686,7 @@ export default function FilesScreen() {
|
||||
|
||||
<ActionsSheet
|
||||
target={actionsTarget}
|
||||
sharingEnabled={sharingEnabled}
|
||||
onClose={() => setActionsTarget(null)}
|
||||
onPreview={(r) => {
|
||||
setActionsTarget(null);
|
||||
@@ -636,6 +696,10 @@ export default function FilesScreen() {
|
||||
setActionsTarget(null);
|
||||
void downloadFile(r);
|
||||
}}
|
||||
onShare={(r) => {
|
||||
setActionsTarget(null);
|
||||
setShareTarget(r);
|
||||
}}
|
||||
onRename={(r) => {
|
||||
setActionsTarget(null);
|
||||
setRenameTarget(r);
|
||||
@@ -647,6 +711,12 @@ export default function FilesScreen() {
|
||||
}}
|
||||
/>
|
||||
|
||||
<ShareSheet
|
||||
node={shareTarget}
|
||||
onClose={() => setShareTarget(null)}
|
||||
onChanged={() => void loadFiles('refresh')}
|
||||
/>
|
||||
|
||||
<Dialog
|
||||
visible={confirmDelete != null}
|
||||
title={
|
||||
@@ -722,18 +792,24 @@ function PromptModal(props: PromptModalProps) {
|
||||
|
||||
interface ActionsSheetProps {
|
||||
target: FileRow | null;
|
||||
sharingEnabled: boolean;
|
||||
onClose: () => void;
|
||||
onPreview: (r: FileRow) => void;
|
||||
onDownload: (r: FileRow) => void;
|
||||
onShare: (r: FileRow) => void;
|
||||
onRename: (r: FileRow) => void;
|
||||
onDelete: (r: FileRow) => void;
|
||||
}
|
||||
|
||||
function ActionsSheet({ target, onClose, onPreview, onDownload, onRename, onDelete }: ActionsSheetProps) {
|
||||
function ActionsSheet({ target, sharingEnabled, onClose, onPreview, onDownload, onShare, onRename, onDelete }: ActionsSheetProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeSheetStyles(c), [c]);
|
||||
if (!target) return null;
|
||||
const isDir = isDirectory(target);
|
||||
const isDir = isFolder(target);
|
||||
// Owned nodes report full rights (or no myRights at all); shared-with-me
|
||||
// nodes are managed by their owner, and write ops would have to route to
|
||||
// the owner's account — so they only get preview/download here.
|
||||
const canShare = sharingEnabled && !target.isShared && (target.myRights?.mayShare ?? true);
|
||||
return (
|
||||
<Modal visible transparent animationType="slide" onRequestClose={onClose}>
|
||||
<TouchableWithoutFeedback onPress={onClose}>
|
||||
@@ -755,14 +831,24 @@ function ActionsSheet({ target, onClose, onPreview, onDownload, onRename, onDele
|
||||
<Text style={styles.actionLabel}>Save to device</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
<Pressable style={styles.action} onPress={() => onRename(target)}>
|
||||
<Pencil size={18} color={c.text} />
|
||||
<Text style={styles.actionLabel}>Rename</Text>
|
||||
</Pressable>
|
||||
<Pressable style={styles.action} onPress={() => onDelete(target)}>
|
||||
<Trash2 size={18} color={c.error} />
|
||||
<Text style={[styles.actionLabel, { color: c.error }]}>Delete</Text>
|
||||
</Pressable>
|
||||
{canShare ? (
|
||||
<Pressable style={styles.action} onPress={() => onShare(target)}>
|
||||
<Users size={18} color={c.text} />
|
||||
<Text style={styles.actionLabel}>Sharing & access</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{!target.isShared ? (
|
||||
<Pressable style={styles.action} onPress={() => onRename(target)}>
|
||||
<Pencil size={18} color={c.text} />
|
||||
<Text style={styles.actionLabel}>Rename</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{!target.isShared ? (
|
||||
<Pressable style={styles.action} onPress={() => onDelete(target)}>
|
||||
<Trash2 size={18} color={c.error} />
|
||||
<Text style={[styles.actionLabel, { color: c.error }]}>Delete</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
</TouchableWithoutFeedback>
|
||||
</View>
|
||||
@@ -856,9 +942,15 @@ function makeStyles(c: ThemePalette) {
|
||||
fileInfo: {
|
||||
flex: 1,
|
||||
},
|
||||
fileNameRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.xs,
|
||||
},
|
||||
fileName: {
|
||||
fontSize: typography.body.fontSize,
|
||||
color: c.text,
|
||||
flexShrink: 1,
|
||||
},
|
||||
fileMetaRow: {
|
||||
flexDirection: 'row',
|
||||
@@ -886,10 +978,18 @@ function makeStyles(c: ThemePalette) {
|
||||
paddingHorizontal: spacing.xs,
|
||||
borderRadius: radius.md,
|
||||
},
|
||||
gridNameRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: 4,
|
||||
maxWidth: '100%',
|
||||
},
|
||||
gridName: {
|
||||
fontSize: typography.caption.fontSize,
|
||||
color: c.text,
|
||||
textAlign: 'center',
|
||||
flexShrink: 1,
|
||||
},
|
||||
gridMeta: {
|
||||
fontSize: typography.small.fontSize,
|
||||
|
||||
+338
-270
@@ -1,16 +1,23 @@
|
||||
import React from 'react';
|
||||
import { View, Text, Pressable, StyleSheet, KeyboardAvoidingView, Platform, Image, Alert } from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import Constants from 'expo-constants';
|
||||
import { Eye, EyeOff, X, QrCode } from 'lucide-react-native';
|
||||
import { spacing, radius, typography, componentSizes, type ThemePalette } from '../theme/tokens';
|
||||
import { useColors } from '../theme/colors';
|
||||
import { Button, Input } from '../components';
|
||||
import { BackHandler } from 'react-native';
|
||||
import { useAuthStore } from '../stores/auth-store';
|
||||
import { useAccountStore } from '../stores/account-store';
|
||||
import { QrScanModal } from '../components/QrScanModal';
|
||||
import { parseQrLoginPayload } from '../lib/oauth';
|
||||
import { useAuthStore } from '../stores/auth-store';
|
||||
|
||||
const APP_VERSION = Constants.expoConfig?.version ?? '0.0.0';
|
||||
import {
|
||||
discoverServerForEmail,
|
||||
emailDomain,
|
||||
isEmailAddress,
|
||||
normalizeServerUrl,
|
||||
} from '../lib/server-discovery';
|
||||
import { describeLoginError, type LoginErrorCopy } from '../lib/login-errors';
|
||||
import LoginShell from './login/LoginShell';
|
||||
import ChooseStep from './login/ChooseStep';
|
||||
import EmailStep from './login/EmailStep';
|
||||
import ServerStep from './login/ServerStep';
|
||||
import ConfirmStep from './login/ConfirmStep';
|
||||
import PasswordStep from './login/PasswordStep';
|
||||
import SigningInStep, { type SigningInPhase } from './login/SigningInStep';
|
||||
|
||||
interface LoginScreenProps {
|
||||
onLogin?: () => void;
|
||||
@@ -18,288 +25,349 @@ interface LoginScreenProps {
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
export default function LoginScreen({ onLogin, isAddMode, onCancel }: LoginScreenProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
type StepName = 'choose' | 'email' | 'server' | 'confirm' | 'password';
|
||||
|
||||
/**
|
||||
* Sign-in, one question per screen, cheapest question first.
|
||||
*
|
||||
* The routes that need no server address — a paired QR code, or an email we
|
||||
* can discover a server from — come first; the manual server + password form
|
||||
* is the fallback rather than the greeting. Every step drives one of the
|
||||
* existing auth-store actions, so the credential handling below is unchanged
|
||||
* from the single-form version this replaced.
|
||||
*/
|
||||
export default function LoginScreen({ onLogin, isAddMode = false, onCancel }: LoginScreenProps) {
|
||||
const login = useAuthStore((state) => state.login);
|
||||
const loginViaWebmail = useAuthStore((state) => state.loginViaWebmail);
|
||||
const loginViaPairing = useAuthStore((state) => state.loginViaPairing);
|
||||
const isLoading = useAuthStore((state) => state.isLoading);
|
||||
const error = useAuthStore((state) => state.error);
|
||||
const clearError = useAuthStore((state) => state.clearError);
|
||||
const storeError = useAuthStore((state) => state.error);
|
||||
|
||||
const [serverUrl, setServerUrl] = React.useState('');
|
||||
const accounts = useAccountStore((state) => state.accounts);
|
||||
const activeAccountId = useAccountStore((state) => state.activeAccountId);
|
||||
|
||||
const [step, setStep] = React.useState<StepName>('choose');
|
||||
const [history, setHistory] = React.useState<StepName[]>([]);
|
||||
const [email, setEmail] = React.useState('');
|
||||
const [serverInput, setServerInput] = React.useState('');
|
||||
const [serverUrl, setServerUrl] = React.useState('');
|
||||
const [password, setPassword] = React.useState('');
|
||||
const [showPassword, setShowPassword] = React.useState(false);
|
||||
const [failedDomain, setFailedDomain] = React.useState<string | null>(null);
|
||||
const [notice, setNotice] = React.useState<LoginErrorCopy | null>(null);
|
||||
const [searching, setSearching] = React.useState(false);
|
||||
const [busy, setBusy] = React.useState<SigningInPhase | null>(null);
|
||||
const [scannerVisible, setScannerVisible] = React.useState(false);
|
||||
|
||||
const canSubmit = Boolean(serverUrl.trim() && email.trim() && password);
|
||||
const canHandoff = Boolean(serverUrl.trim());
|
||||
// Servers we already hold credentials for. Discovery trusts these without a
|
||||
// probe, which makes "second account on the same host" instant.
|
||||
const knownServerUrls = React.useMemo(() => accounts.map((a) => a.serverUrl), [accounts]);
|
||||
const knownServerUrl = React.useMemo(() => {
|
||||
const active = accounts.find((a) => a.id === activeAccountId);
|
||||
return active?.serverUrl ?? accounts[0]?.serverUrl ?? null;
|
||||
}, [accounts, activeAccountId]);
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (!canSubmit) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await login(serverUrl.trim(), email.trim(), password, { addAccount: isAddMode });
|
||||
onLogin?.();
|
||||
} catch {
|
||||
// Store state already contains the user-facing error.
|
||||
}
|
||||
};
|
||||
|
||||
const handleWebmailHandoff = async () => {
|
||||
if (!canHandoff) return;
|
||||
try {
|
||||
const before = useAuthStore.getState().isAuthenticated;
|
||||
await loginViaWebmail(serverUrl.trim(), { addAccount: isAddMode });
|
||||
// loginViaWebmail swallows the "user cancelled the browser" case
|
||||
// silently — only fire the navigation hook when authentication
|
||||
// actually completed.
|
||||
const after = useAuthStore.getState().isAuthenticated;
|
||||
if (after && !before) {
|
||||
onLogin?.();
|
||||
} else if (isAddMode && after) {
|
||||
onLogin?.();
|
||||
}
|
||||
} catch {
|
||||
// Store state already contains the user-facing error.
|
||||
}
|
||||
};
|
||||
|
||||
const handleScanned = async (data: string) => {
|
||||
setScannerVisible(false);
|
||||
const payload = parseQrLoginPayload(data);
|
||||
if (!payload) {
|
||||
Alert.alert('Unrecognized QR code', "That QR code isn't a Bulwark Mail sign-in code.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const before = useAuthStore.getState().isAuthenticated;
|
||||
if (payload.kind === 'connect') {
|
||||
// Server-bootstrap QR: fill the field and run the normal browser
|
||||
// handoff so the user still authenticates in the webmail.
|
||||
setServerUrl(payload.webmailUrl);
|
||||
await loginViaWebmail(payload.webmailUrl, { addAccount: isAddMode });
|
||||
} else {
|
||||
// Cross-device pairing QR: redeem the one-time code for tokens, no
|
||||
// browser round-trip needed.
|
||||
await loginViaPairing(payload.webmailUrl, payload.code, { addAccount: isAddMode });
|
||||
}
|
||||
const after = useAuthStore.getState().isAuthenticated;
|
||||
if ((after && !before) || (isAddMode && after)) {
|
||||
onLogin?.();
|
||||
}
|
||||
} catch {
|
||||
// Store state already contains the user-facing error.
|
||||
}
|
||||
};
|
||||
|
||||
const updateField = React.useCallback(
|
||||
(setter: React.Dispatch<React.SetStateAction<string>>) => (value: string) => {
|
||||
if (useAuthStore.getState().error) {
|
||||
clearError();
|
||||
}
|
||||
setter(value);
|
||||
const goTo = React.useCallback(
|
||||
(next: StepName) => {
|
||||
clearError();
|
||||
setNotice(null);
|
||||
setHistory((prev) => [...prev, step]);
|
||||
setStep(next);
|
||||
},
|
||||
[clearError],
|
||||
[clearError, step],
|
||||
);
|
||||
|
||||
const onChangeServerUrl = React.useMemo(() => updateField(setServerUrl), [updateField]);
|
||||
const onChangeEmail = React.useMemo(() => updateField(setEmail), [updateField]);
|
||||
const onChangePassword = React.useMemo(() => updateField(setPassword), [updateField]);
|
||||
const goBack = React.useCallback(() => {
|
||||
if (history.length === 0) return;
|
||||
clearError();
|
||||
setNotice(null);
|
||||
setStep(history[history.length - 1]);
|
||||
setHistory((prev) => prev.slice(0, -1));
|
||||
}, [clearError, history]);
|
||||
|
||||
// Android hardware back mirrors the on-screen back: one step at a time, and
|
||||
// out of the flow entirely from the first step.
|
||||
React.useEffect(() => {
|
||||
const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
|
||||
if (busy || searching) return true;
|
||||
if (scannerVisible) {
|
||||
setScannerVisible(false);
|
||||
return true;
|
||||
}
|
||||
if (history.length > 0) {
|
||||
goBack();
|
||||
return true;
|
||||
}
|
||||
if (isAddMode && onCancel) {
|
||||
onCancel();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
return () => subscription.remove();
|
||||
}, [busy, searching, scannerVisible, history.length, goBack, isAddMode, onCancel]);
|
||||
|
||||
// ── flows ──────────────────────────────────────────────
|
||||
|
||||
const finishIfSignedIn = React.useCallback(
|
||||
(wasAuthenticated: boolean) => {
|
||||
const isAuthenticated = useAuthStore.getState().isAuthenticated;
|
||||
// In add mode the store was already authenticated before we started, so
|
||||
// the before/after comparison can't be the only signal.
|
||||
if ((isAuthenticated && !wasAuthenticated) || (isAddMode && isAuthenticated)) {
|
||||
onLogin?.();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
[isAddMode, onLogin],
|
||||
);
|
||||
|
||||
const runHandoff = React.useCallback(
|
||||
async (target: string) => {
|
||||
setNotice(null);
|
||||
setBusy('browser');
|
||||
const wasAuthenticated = useAuthStore.getState().isAuthenticated;
|
||||
try {
|
||||
await loginViaWebmail(target, { addAccount: isAddMode });
|
||||
// loginViaWebmail resolves quietly when the user closes the browser —
|
||||
// that's a cancellation, not a failure, so leave them where they were.
|
||||
finishIfSignedIn(wasAuthenticated);
|
||||
} catch (err) {
|
||||
setNotice(describeLoginError(err, { serverUrl: target }));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
},
|
||||
[finishIfSignedIn, isAddMode, loginViaWebmail],
|
||||
);
|
||||
|
||||
const handleEmailContinue = React.useCallback(async () => {
|
||||
const value = email.trim();
|
||||
if (!isEmailAddress(value)) {
|
||||
setNotice({
|
||||
title: 'Enter a full email address',
|
||||
detail: 'Like ada@example.com. If you sign in with a username instead, use “I know my server address”.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setNotice(null);
|
||||
setSearching(true);
|
||||
try {
|
||||
const found = await discoverServerForEmail(value, { knownServerUrls });
|
||||
if (found) {
|
||||
setServerUrl(found);
|
||||
setServerInput(found);
|
||||
goTo('confirm');
|
||||
} else {
|
||||
setFailedDomain(emailDomain(value));
|
||||
setServerInput('');
|
||||
goTo('server');
|
||||
}
|
||||
} finally {
|
||||
setSearching(false);
|
||||
}
|
||||
}, [email, goTo, knownServerUrls]);
|
||||
|
||||
const handleServerContinue = React.useCallback(() => {
|
||||
const normalized = normalizeServerUrl(serverInput);
|
||||
if (!normalized) {
|
||||
setNotice({
|
||||
title: "That doesn't look like a server address",
|
||||
detail: 'Try the address you use for webmail, like mail.example.com.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
setServerUrl(normalized);
|
||||
goTo('confirm');
|
||||
}, [goTo, serverInput]);
|
||||
|
||||
const handlePasswordSubmit = React.useCallback(async () => {
|
||||
const target = serverUrl || normalizeServerUrl(serverInput);
|
||||
if (!target) {
|
||||
setNotice({ title: 'We need a server address first' });
|
||||
return;
|
||||
}
|
||||
if (!email.trim() || !password) {
|
||||
setNotice({ title: 'Enter your email and password' });
|
||||
return;
|
||||
}
|
||||
|
||||
setNotice(null);
|
||||
setBusy('connecting');
|
||||
const wasAuthenticated = useAuthStore.getState().isAuthenticated;
|
||||
try {
|
||||
await login(target, email.trim(), password, { addAccount: isAddMode });
|
||||
finishIfSignedIn(wasAuthenticated);
|
||||
} catch (err) {
|
||||
setNotice(describeLoginError(err, { serverUrl: target }));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}, [email, finishIfSignedIn, isAddMode, login, password, serverInput, serverUrl]);
|
||||
|
||||
const handleScanned = React.useCallback(
|
||||
async (data: string) => {
|
||||
setScannerVisible(false);
|
||||
const payload = parseQrLoginPayload(data);
|
||||
if (!payload) {
|
||||
setNotice({
|
||||
title: "That code isn't a Bulwark sign-in code",
|
||||
detail: 'Open Bulwark on the web, then Settings → Devices to show one.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.kind === 'connect') {
|
||||
// Server-bootstrap code: it carries the address, the user still
|
||||
// authenticates in the webmail.
|
||||
setServerUrl(payload.webmailUrl);
|
||||
setServerInput(payload.webmailUrl);
|
||||
await runHandoff(payload.webmailUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
// Cross-device pairing code: redeem it for tokens, no browser needed.
|
||||
setNotice(null);
|
||||
setBusy('pairing');
|
||||
const wasAuthenticated = useAuthStore.getState().isAuthenticated;
|
||||
try {
|
||||
await loginViaPairing(payload.webmailUrl, payload.code, { addAccount: isAddMode });
|
||||
finishIfSignedIn(wasAuthenticated);
|
||||
} catch (err) {
|
||||
setNotice(describeLoginError(err, { serverUrl: payload.webmailUrl }));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
},
|
||||
[finishIfSignedIn, isAddMode, loginViaPairing, runHandoff],
|
||||
);
|
||||
|
||||
// ── render ─────────────────────────────────────────────
|
||||
|
||||
if (busy) {
|
||||
return (
|
||||
<SigningInStep
|
||||
phase={busy}
|
||||
serverUrl={serverUrl || knownServerUrl}
|
||||
email={email.trim() || null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const canGoBack = history.length > 0;
|
||||
const shellProps = {
|
||||
onBack: canGoBack ? goBack : undefined,
|
||||
onClose: isAddMode && onCancel ? onCancel : undefined,
|
||||
};
|
||||
|
||||
if (step === 'choose') {
|
||||
// A leftover store error ("Session expired") is the reason some people
|
||||
// land back here, so it belongs on this screen.
|
||||
const chooseNotice = notice ?? (storeError ? { title: storeError } : null);
|
||||
return (
|
||||
<>
|
||||
<LoginShell {...shellProps} centered showFooter>
|
||||
<ChooseStep
|
||||
isAddMode={isAddMode}
|
||||
accounts={accounts}
|
||||
knownServerUrl={isAddMode ? knownServerUrl : null}
|
||||
notice={chooseNotice}
|
||||
onScan={() => setScannerVisible(true)}
|
||||
onUseEmail={() => goTo('email')}
|
||||
onUseKnownServer={() => {
|
||||
if (!knownServerUrl) return;
|
||||
setServerUrl(knownServerUrl);
|
||||
setServerInput(knownServerUrl);
|
||||
goTo('confirm');
|
||||
}}
|
||||
onManualSetup={() => {
|
||||
setFailedDomain(null);
|
||||
goTo('server');
|
||||
}}
|
||||
/>
|
||||
</LoginShell>
|
||||
<QrScanModal
|
||||
visible={scannerVisible}
|
||||
onClose={() => setScannerVisible(false)}
|
||||
onScanned={(data) => void handleScanned(data)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container}>
|
||||
{isAddMode && onCancel ? (
|
||||
<Pressable onPress={onCancel} style={styles.cancelButton} hitSlop={10}>
|
||||
<X size={24} color={c.text} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
|
||||
style={styles.keyboardView}
|
||||
>
|
||||
<View style={styles.content}>
|
||||
{/* Logo & Branding */}
|
||||
<View style={styles.branding}>
|
||||
<View style={styles.logoContainer}>
|
||||
<Image
|
||||
source={require('../../assets/logos/Bulwark Logo White.png')}
|
||||
style={styles.logoImage}
|
||||
resizeMode="contain"
|
||||
/>
|
||||
</View>
|
||||
<Text style={styles.appName}>{isAddMode ? 'Add account' : 'Bulwark Mail'}</Text>
|
||||
<Text style={styles.tagline}>
|
||||
{isAddMode ? 'Sign in to a second account' : 'Secure. Private. Yours.'}
|
||||
</Text>
|
||||
</View>
|
||||
<>
|
||||
<LoginShell {...shellProps}>
|
||||
{step === 'email' ? (
|
||||
<EmailStep
|
||||
isAddMode={isAddMode}
|
||||
value={email}
|
||||
onChange={(value) => {
|
||||
setNotice(null);
|
||||
setEmail(value);
|
||||
}}
|
||||
onSubmit={() => void handleEmailContinue()}
|
||||
onKnowServer={() => {
|
||||
setFailedDomain(null);
|
||||
goTo('server');
|
||||
}}
|
||||
isSearching={searching}
|
||||
notice={notice}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{/* Login Form */}
|
||||
<View style={styles.form}>
|
||||
<Input
|
||||
label="Server URL"
|
||||
placeholder="https://mail.example.com"
|
||||
value={serverUrl}
|
||||
onChangeText={onChangeServerUrl}
|
||||
autoCapitalize="none"
|
||||
keyboardType="url"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
{step === 'server' ? (
|
||||
<ServerStep
|
||||
value={serverInput}
|
||||
onChange={(value) => {
|
||||
setNotice(null);
|
||||
setServerInput(value);
|
||||
}}
|
||||
onSubmit={handleServerContinue}
|
||||
onScan={() => setScannerVisible(true)}
|
||||
failedDomain={failedDomain}
|
||||
notice={notice}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Input
|
||||
label="Email or Username"
|
||||
placeholder="you@example.com"
|
||||
value={email}
|
||||
onChangeText={onChangeEmail}
|
||||
autoCapitalize="none"
|
||||
keyboardType="email-address"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
{step === 'confirm' ? (
|
||||
<ConfirmStep
|
||||
serverUrl={serverUrl}
|
||||
onContinue={() => void runHandoff(serverUrl)}
|
||||
onChangeServer={() => {
|
||||
setFailedDomain(null);
|
||||
goTo('server');
|
||||
}}
|
||||
onUsePassword={() => goTo('password')}
|
||||
notice={notice}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Input
|
||||
label="Password"
|
||||
placeholder="Enter your password"
|
||||
value={password}
|
||||
onChangeText={onChangePassword}
|
||||
secureTextEntry={!showPassword}
|
||||
onSubmitEditing={() => {
|
||||
void handleLogin();
|
||||
}}
|
||||
rightIcon={
|
||||
<Pressable onPress={() => setShowPassword(!showPassword)}>
|
||||
{showPassword ? (
|
||||
<EyeOff size={20} color={c.textMuted} />
|
||||
) : (
|
||||
<Eye size={20} color={c.textMuted} />
|
||||
)}
|
||||
</Pressable>
|
||||
}
|
||||
/>
|
||||
|
||||
<Button
|
||||
variant="default"
|
||||
size="lg"
|
||||
onPress={() => {
|
||||
void handleLogin();
|
||||
}}
|
||||
disabled={!canSubmit}
|
||||
loading={isLoading}
|
||||
style={styles.loginButton}
|
||||
>
|
||||
{isLoading ? 'Signing in...' : 'Sign In'}
|
||||
</Button>
|
||||
|
||||
{error ? <Text style={styles.errorText}>{error}</Text> : null}
|
||||
|
||||
{/* OAuth divider */}
|
||||
<View style={styles.divider}>
|
||||
<View style={styles.dividerLine} />
|
||||
<Text style={styles.dividerText}>or continue with</Text>
|
||||
<View style={styles.dividerLine} />
|
||||
</View>
|
||||
|
||||
{/* Webmail-mediated login */}
|
||||
<View style={styles.oauthRow}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="md"
|
||||
onPress={() => {
|
||||
void handleWebmailHandoff();
|
||||
}}
|
||||
disabled={!canHandoff || isLoading}
|
||||
>
|
||||
Sign in via webmail
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="md"
|
||||
onPress={() => setScannerVisible(true)}
|
||||
disabled={isLoading}
|
||||
icon={<QrCode size={18} color={c.text} />}
|
||||
>
|
||||
Scan QR code
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* Footer */}
|
||||
<View style={styles.footer}>
|
||||
<Text style={styles.footerText}>Bulwark Mobile v{APP_VERSION}</Text>
|
||||
<Text style={styles.footerLink}>Privacy Policy</Text>
|
||||
</View>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
{step === 'password' ? (
|
||||
<PasswordStep
|
||||
serverUrl={serverUrl}
|
||||
email={email}
|
||||
password={password}
|
||||
onChangeEmail={(value) => {
|
||||
setNotice(null);
|
||||
setEmail(value);
|
||||
}}
|
||||
onChangePassword={(value) => {
|
||||
setNotice(null);
|
||||
setPassword(value);
|
||||
}}
|
||||
onSubmit={() => void handlePasswordSubmit()}
|
||||
notice={notice}
|
||||
/>
|
||||
) : null}
|
||||
</LoginShell>
|
||||
|
||||
<QrScanModal
|
||||
visible={scannerVisible}
|
||||
onClose={() => setScannerVisible(false)}
|
||||
onScanned={(data) => {
|
||||
void handleScanned(data);
|
||||
}}
|
||||
onScanned={(data) => void handleScanned(data)}
|
||||
/>
|
||||
</SafeAreaView>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
container: { flex: 1, backgroundColor: c.background },
|
||||
cancelButton: {
|
||||
position: 'absolute',
|
||||
top: 50,
|
||||
left: 16,
|
||||
zIndex: 10,
|
||||
padding: 8,
|
||||
},
|
||||
keyboardView: { flex: 1 },
|
||||
content: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: spacing.xxl,
|
||||
},
|
||||
branding: { alignItems: 'center', marginBottom: 40 },
|
||||
logoContainer: {
|
||||
width: 80,
|
||||
height: 80,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginBottom: spacing.lg,
|
||||
},
|
||||
logoImage: {
|
||||
width: 72,
|
||||
height: 72,
|
||||
},
|
||||
appName: { ...typography.h1, color: c.text },
|
||||
tagline: { ...typography.caption, color: c.textMuted, marginTop: spacing.xs },
|
||||
|
||||
form: { gap: spacing.lg },
|
||||
|
||||
loginButton: {
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
errorText: {
|
||||
...typography.caption,
|
||||
color: c.error,
|
||||
textAlign: 'center',
|
||||
},
|
||||
|
||||
divider: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
marginVertical: spacing.md,
|
||||
gap: spacing.md,
|
||||
},
|
||||
dividerLine: { flex: 1, height: 1, backgroundColor: c.border },
|
||||
dividerText: { ...typography.caption, color: c.textMuted },
|
||||
|
||||
oauthRow: { gap: spacing.md },
|
||||
|
||||
footer: { alignItems: 'center', marginTop: 40, gap: spacing.xs },
|
||||
footerText: { ...typography.caption, color: c.textMuted },
|
||||
footerLink: { ...typography.caption, color: c.textLink },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ import { LayoutSettings } from '../components/settings/LayoutSettings';
|
||||
import { DownloadsSettings } from '../components/settings/DownloadsSettings';
|
||||
import { useLocaleStore } from '../stores/locale-store';
|
||||
import { useHasCalendar, useHasContacts, useHasFiles } from '../lib/capabilities';
|
||||
import { supportsSideloadUpdates } from '../lib/platform-capabilities';
|
||||
|
||||
type Tab =
|
||||
| 'account' | 'language' | 'notifications'
|
||||
@@ -138,11 +139,18 @@ const TAB_COMPONENTS: Partial<Record<Tab, React.ComponentType<any>>> = {
|
||||
updates: UpdatesSettings,
|
||||
};
|
||||
|
||||
// Tabs whose feature does not exist on this platform never appear in the list.
|
||||
// The "Updates" pane drives the sideload installer, which is Android-only - the
|
||||
// current version and build are still shown under "About & Data".
|
||||
const AVAILABLE_TABS: TabDef[] = TABS.filter(
|
||||
(t) => t.id !== 'updates' || supportsSideloadUpdates,
|
||||
);
|
||||
|
||||
function groupTabs() {
|
||||
return GROUP_ORDER.map(group => ({
|
||||
group,
|
||||
label: GROUP_LABELS[group],
|
||||
items: TABS.filter(t => t.group === group),
|
||||
items: AVAILABLE_TABS.filter(t => t.group === group),
|
||||
})).filter(g => g.items.length > 0);
|
||||
}
|
||||
|
||||
|
||||
@@ -96,6 +96,7 @@ export default function UnifiedInboxScreen({ navigation }: Props) {
|
||||
onPress={() => onOpen(item)}
|
||||
style={({ pressed }) => [styles.row, pressed && styles.rowPressed]}
|
||||
>
|
||||
{unread && <View style={styles.unreadDot} />}
|
||||
<View style={styles.avatarWrap}>
|
||||
<SenderAvatar
|
||||
name={senderName(item)}
|
||||
@@ -219,6 +220,19 @@ function makeStyles(c: ThemePalette) {
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
rowPressed: { backgroundColor: c.surfaceHover },
|
||||
// Same unread indicator as the mailbox list (and the webmail): an 8px
|
||||
// filled circle in the start gutter (#27). Anchored on the row's *first*
|
||||
// line — top padding + half an avatar — because centring it on the row
|
||||
// drops it a full line below the avatar it reads as a column with.
|
||||
unreadDot: {
|
||||
position: 'absolute',
|
||||
left: 4,
|
||||
top: spacing.md + componentSizes.avatarMd / 2 - 4,
|
||||
width: 8,
|
||||
height: 8,
|
||||
borderRadius: 4,
|
||||
backgroundColor: c.unread,
|
||||
},
|
||||
avatarWrap: { position: 'relative' },
|
||||
accountDot: {
|
||||
position: 'absolute',
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import React from 'react';
|
||||
import { View, Text, Pressable, StyleSheet, Image } from 'react-native';
|
||||
import { QrCode, Mail, Plus, Server } from 'lucide-react-native';
|
||||
import { spacing, radius, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors, useResolvedTheme } from '../../theme/colors';
|
||||
import type { AccountEntry } from '../../stores/account-store';
|
||||
import OptionTile from './OptionTile';
|
||||
import LoginNotice from './LoginNotice';
|
||||
|
||||
// The white mark disappears on the light palette, so pick per theme. `require`
|
||||
// can't take an expression, hence the pair.
|
||||
const LOGO_LIGHT = require('../../../assets/logos/Bulwark Logo Dark.png');
|
||||
const LOGO_DARK = require('../../../assets/logos/Bulwark Logo White.png');
|
||||
|
||||
interface ChooseStepProps {
|
||||
isAddMode: boolean;
|
||||
accounts: AccountEntry[];
|
||||
/** Host of the signed-in account, offered as a shortcut in add mode. */
|
||||
knownServerUrl: string | null;
|
||||
onScan: () => void;
|
||||
onUseEmail: () => void;
|
||||
onUseKnownServer: () => void;
|
||||
onManualSetup: () => void;
|
||||
notice?: { title: string; detail?: string } | null;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
function hostOf(url: string): string {
|
||||
return url.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '').split('/')[0];
|
||||
}
|
||||
|
||||
function initialsOf(account: AccountEntry): string {
|
||||
const source = account.displayName || account.email || account.username;
|
||||
const parts = source.replace(/@.*$/, '').split(/[.\s_-]+/).filter(Boolean);
|
||||
const letters = parts.slice(0, 2).map((part) => part[0]);
|
||||
return (letters.join('') || source[0] || '?').toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry point. Leads with the two routes that don't require knowing a
|
||||
* server address; manual setup stays one tap away for people who do.
|
||||
*/
|
||||
export default function ChooseStep({
|
||||
isAddMode,
|
||||
accounts,
|
||||
knownServerUrl,
|
||||
onScan,
|
||||
onUseEmail,
|
||||
onUseKnownServer,
|
||||
onManualSetup,
|
||||
notice,
|
||||
disabled = false,
|
||||
}: ChooseStepProps) {
|
||||
const c = useColors();
|
||||
const theme = useResolvedTheme();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
|
||||
return (
|
||||
<View style={styles.root}>
|
||||
{isAddMode ? (
|
||||
<View style={styles.addHeading}>
|
||||
<Text style={styles.title}>Add another account</Text>
|
||||
{accounts.length > 0 ? (
|
||||
<Text style={styles.subtitle}>You're signed in to these already.</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<View style={styles.branding}>
|
||||
<Image
|
||||
source={theme === 'light' ? LOGO_LIGHT : LOGO_DARK}
|
||||
style={styles.logo}
|
||||
resizeMode="contain"
|
||||
/>
|
||||
<Text style={styles.appName}>Bulwark Mail</Text>
|
||||
<Text style={styles.tagline}>Secure. Private. Yours.</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{isAddMode && accounts.length > 0 ? (
|
||||
<View style={styles.accountList}>
|
||||
{accounts.map((account) => (
|
||||
<View key={account.id} style={styles.accountRow}>
|
||||
<View style={[styles.avatar, { backgroundColor: account.avatarColor }]}>
|
||||
<Text style={styles.avatarText}>{initialsOf(account)}</Text>
|
||||
</View>
|
||||
<View style={styles.accountText}>
|
||||
<Text style={styles.accountName} numberOfLines={1}>
|
||||
{account.displayName || account.username}
|
||||
</Text>
|
||||
<Text style={styles.accountEmail} numberOfLines={1}>
|
||||
{account.email || account.username}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{notice ? (
|
||||
<View style={styles.notice}>
|
||||
<LoginNotice title={notice.title} detail={notice.detail} />
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<View style={styles.options}>
|
||||
{isAddMode && knownServerUrl ? (
|
||||
<OptionTile
|
||||
emphasis="primary"
|
||||
title={`Another account on ${hostOf(knownServerUrl)}`}
|
||||
description="Server already known — no setup needed"
|
||||
renderIcon={(color, size) => <Plus size={size} color={color} />}
|
||||
onPress={onUseKnownServer}
|
||||
disabled={disabled}
|
||||
/>
|
||||
) : (
|
||||
<OptionTile
|
||||
emphasis="primary"
|
||||
title="Scan a sign-in code"
|
||||
description="Already signed in on the web? Fastest way in."
|
||||
renderIcon={(color, size) => <QrCode size={size} color={color} />}
|
||||
onPress={onScan}
|
||||
disabled={disabled}
|
||||
/>
|
||||
)}
|
||||
|
||||
<OptionTile
|
||||
title={isAddMode ? 'An account somewhere else' : 'Use my email address'}
|
||||
description="We'll find your mail server"
|
||||
renderIcon={(color, size) => <Mail size={size} color={color} />}
|
||||
onPress={onUseEmail}
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
{isAddMode && knownServerUrl ? (
|
||||
<OptionTile
|
||||
title="Scan a sign-in code"
|
||||
renderIcon={(color, size) => <QrCode size={size} color={color} />}
|
||||
onPress={onScan}
|
||||
disabled={disabled}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<Pressable onPress={onManualSetup} disabled={disabled} hitSlop={8} style={styles.manual}>
|
||||
<Server size={14} color={c.textMuted} />
|
||||
<Text style={styles.manualText}>Enter server details manually</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
root: { gap: spacing.xl },
|
||||
branding: { alignItems: 'center', gap: spacing.xs, marginBottom: spacing.md },
|
||||
logo: { width: 64, height: 64, marginBottom: spacing.sm },
|
||||
appName: { ...typography.h1, color: c.text },
|
||||
tagline: { ...typography.caption, color: c.textMuted },
|
||||
|
||||
addHeading: { gap: spacing.xs },
|
||||
title: { ...typography.h1, color: c.text },
|
||||
subtitle: { ...typography.body, color: c.textSecondary },
|
||||
|
||||
accountList: { gap: spacing.md },
|
||||
accountRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.md },
|
||||
avatar: { width: 36, height: 36, borderRadius: radius.full, alignItems: 'center', justifyContent: 'center' },
|
||||
avatarText: { ...typography.captionMedium, color: '#ffffff' },
|
||||
accountText: { flex: 1 },
|
||||
accountName: { ...typography.bodyMedium, color: c.text },
|
||||
accountEmail: { ...typography.caption, color: c.textMuted },
|
||||
|
||||
notice: { marginTop: -spacing.xs },
|
||||
options: { gap: spacing.md },
|
||||
|
||||
manual: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: spacing.sm,
|
||||
paddingVertical: spacing.sm,
|
||||
},
|
||||
manualText: { ...typography.body, color: c.textMuted },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import React from 'react';
|
||||
import { View, Text, Pressable, StyleSheet } from 'react-native';
|
||||
import { Globe } from 'lucide-react-native';
|
||||
import { spacing, radius, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
import { Button } from '../../components';
|
||||
import LoginNotice from './LoginNotice';
|
||||
|
||||
interface ConfirmStepProps {
|
||||
serverUrl: string;
|
||||
onContinue: () => void;
|
||||
onChangeServer: () => void;
|
||||
onUsePassword: () => void;
|
||||
notice?: { title: string; detail?: string } | null;
|
||||
}
|
||||
|
||||
function hostOf(url: string): string {
|
||||
return url.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '').split('/')[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Names the server before the browser opens. A sign-in that jumps to a browser
|
||||
* with no warning reads as a bug; saying which server, and why the password
|
||||
* isn't asked for here, turns the detour into the point.
|
||||
*/
|
||||
export default function ConfirmStep({
|
||||
serverUrl,
|
||||
onContinue,
|
||||
onChangeServer,
|
||||
onUsePassword,
|
||||
notice,
|
||||
}: ConfirmStepProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
|
||||
return (
|
||||
<View style={styles.root}>
|
||||
<View style={styles.heading}>
|
||||
<Text style={styles.title}>Found your mail server</Text>
|
||||
<Text style={styles.subtitle}>Next you'll sign in on your provider's own page.</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.card}>
|
||||
<View style={styles.cardIcon}>
|
||||
<Globe size={19} color={c.primary} />
|
||||
</View>
|
||||
<View style={styles.cardText}>
|
||||
<Text style={styles.cardTitle} numberOfLines={1}>
|
||||
{hostOf(serverUrl)}
|
||||
</Text>
|
||||
<View style={styles.cardMetaRow}>
|
||||
<View style={styles.dot} />
|
||||
<Text style={styles.cardMeta}>
|
||||
{serverUrl.startsWith('https://') ? 'JMAP · secure connection' : 'JMAP · unencrypted connection'}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<LoginNotice
|
||||
tone="info"
|
||||
title="Your password stays with your provider"
|
||||
detail="You'll type it on their page, not into this app. Bulwark keeps a token it can revoke."
|
||||
/>
|
||||
|
||||
{notice ? <LoginNotice title={notice.title} detail={notice.detail} /> : null}
|
||||
|
||||
<Button variant="default" size="lg" onPress={onContinue}>
|
||||
Continue
|
||||
</Button>
|
||||
|
||||
<View style={styles.links}>
|
||||
<Pressable onPress={onUsePassword} hitSlop={8}>
|
||||
<Text style={styles.link}>Sign in with a password instead</Text>
|
||||
</Pressable>
|
||||
<Pressable onPress={onChangeServer} hitSlop={8}>
|
||||
<Text style={styles.linkMuted}>Use a different server</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
root: { gap: spacing.lg },
|
||||
heading: { gap: spacing.sm },
|
||||
title: { ...typography.h1, color: c.text },
|
||||
subtitle: { ...typography.body, color: c.textSecondary },
|
||||
|
||||
card: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.md,
|
||||
borderWidth: 1,
|
||||
borderColor: c.border,
|
||||
backgroundColor: c.surface,
|
||||
borderRadius: radius.lg,
|
||||
padding: spacing.lg,
|
||||
},
|
||||
cardIcon: {
|
||||
width: 38,
|
||||
height: 38,
|
||||
borderRadius: radius.md,
|
||||
backgroundColor: c.primaryBg,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
cardText: { flex: 1, gap: 2 },
|
||||
cardTitle: { ...typography.baseMedium, color: c.text },
|
||||
cardMetaRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
|
||||
dot: { width: 5, height: 5, borderRadius: radius.full, backgroundColor: c.success },
|
||||
cardMeta: { ...typography.caption, color: c.textSecondary },
|
||||
|
||||
links: { alignItems: 'center', gap: spacing.md, paddingVertical: spacing.xs },
|
||||
link: { ...typography.body, color: c.textLink },
|
||||
linkMuted: { ...typography.body, color: c.textMuted },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import React from 'react';
|
||||
import { View, Text, Pressable, StyleSheet } from 'react-native';
|
||||
import { Mail } from 'lucide-react-native';
|
||||
import { spacing, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
import { Button, Input } from '../../components';
|
||||
import LoginNotice from './LoginNotice';
|
||||
|
||||
interface EmailStepProps {
|
||||
isAddMode: boolean;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
onSubmit: () => void;
|
||||
onKnowServer: () => void;
|
||||
isSearching: boolean;
|
||||
notice?: { title: string; detail?: string } | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One field, keyboard already up. The button stays enabled and validates on
|
||||
* press, so nobody is left guessing which field disabled it.
|
||||
*/
|
||||
export default function EmailStep({
|
||||
isAddMode,
|
||||
value,
|
||||
onChange,
|
||||
onSubmit,
|
||||
onKnowServer,
|
||||
isSearching,
|
||||
notice,
|
||||
}: EmailStepProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
|
||||
return (
|
||||
<View style={styles.root}>
|
||||
<View style={styles.heading}>
|
||||
<Text style={styles.title}>
|
||||
{isAddMode ? "What's the other address?" : "What's your email address?"}
|
||||
</Text>
|
||||
<Text style={styles.subtitle}>
|
||||
That's usually all we need — we'll look up the mail server for you.
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<Input
|
||||
placeholder="you@example.com"
|
||||
value={value}
|
||||
onChangeText={onChange}
|
||||
autoFocus
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
autoComplete="email"
|
||||
textContentType="username"
|
||||
keyboardType="email-address"
|
||||
returnKeyType="go"
|
||||
editable={!isSearching}
|
||||
onSubmitEditing={onSubmit}
|
||||
leftIcon={<Mail size={17} color={c.textMuted} />}
|
||||
/>
|
||||
|
||||
<Text style={styles.hint}>Works with Bulwark, Stalwart, and any JMAP mail server.</Text>
|
||||
|
||||
{notice ? <LoginNotice title={notice.title} detail={notice.detail} /> : null}
|
||||
|
||||
<Button variant="default" size="lg" onPress={onSubmit} loading={isSearching}>
|
||||
{isSearching ? 'Looking up your server…' : 'Continue'}
|
||||
</Button>
|
||||
|
||||
<Pressable onPress={onKnowServer} disabled={isSearching} hitSlop={8} style={styles.link}>
|
||||
<Text style={styles.linkText}>I know my server address</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
root: { gap: spacing.lg },
|
||||
heading: { gap: spacing.sm },
|
||||
title: { ...typography.h1, color: c.text },
|
||||
subtitle: { ...typography.body, color: c.textSecondary },
|
||||
hint: { ...typography.caption, color: c.textMuted, marginTop: -spacing.sm },
|
||||
link: { alignItems: 'center', paddingVertical: spacing.sm },
|
||||
linkText: { ...typography.body, color: c.textMuted },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet } from 'react-native';
|
||||
import { AlertTriangle, Lock } from 'lucide-react-native';
|
||||
import { spacing, radius, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
|
||||
interface LoginNoticeProps {
|
||||
title: string;
|
||||
detail?: string;
|
||||
tone?: 'error' | 'info';
|
||||
}
|
||||
|
||||
/** Inline banner for a sign-in failure, or a reassurance about where a
|
||||
* password ends up. Errors lead with what went wrong, then what to do. */
|
||||
export default function LoginNotice({ title, detail, tone = 'error' }: LoginNoticeProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const isError = tone === 'error';
|
||||
const Icon = isError ? AlertTriangle : Lock;
|
||||
|
||||
return (
|
||||
<View
|
||||
style={[styles.banner, isError ? styles.bannerError : styles.bannerInfo]}
|
||||
accessibilityLiveRegion={isError ? 'polite' : 'none'}
|
||||
>
|
||||
<Icon size={16} color={isError ? c.error : c.textMuted} style={styles.icon} />
|
||||
<View style={styles.text}>
|
||||
<Text style={[styles.title, isError ? styles.titleError : styles.titleInfo]}>{title}</Text>
|
||||
{detail ? <Text style={styles.detail}>{detail}</Text> : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
banner: {
|
||||
flexDirection: 'row',
|
||||
gap: spacing.sm,
|
||||
borderRadius: radius.md,
|
||||
padding: spacing.md,
|
||||
},
|
||||
bannerError: { backgroundColor: c.errorBg, borderWidth: 1, borderColor: c.errorBorder },
|
||||
bannerInfo: { backgroundColor: 'transparent', paddingHorizontal: 0 },
|
||||
icon: { marginTop: 1 },
|
||||
text: { flex: 1, gap: 2 },
|
||||
title: { ...typography.captionMedium },
|
||||
titleError: { color: c.error },
|
||||
titleInfo: { color: c.textSecondary },
|
||||
detail: { ...typography.caption, color: c.textSecondary, lineHeight: 17 },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
} from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import Constants from 'expo-constants';
|
||||
import { ArrowLeft, X } from 'lucide-react-native';
|
||||
import { spacing, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
|
||||
const APP_VERSION = Constants.expoConfig?.version ?? '0.0.0';
|
||||
|
||||
interface LoginShellProps {
|
||||
children: React.ReactNode;
|
||||
/** Renders a back chevron. Omit on the first step of the flow. */
|
||||
onBack?: () => void;
|
||||
/** Renders a close X on the right — add-account mode only. */
|
||||
onClose?: () => void;
|
||||
/** Vertically centres the content instead of stacking from the top. */
|
||||
centered?: boolean;
|
||||
showFooter?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared chrome for every sign-in step: safe area, keyboard avoidance, the
|
||||
* back/close affordances, and the version footer. Steps supply only their own
|
||||
* content so they all sit on the same grid.
|
||||
*/
|
||||
export default function LoginShell({
|
||||
children,
|
||||
onBack,
|
||||
onClose,
|
||||
centered = false,
|
||||
showFooter = false,
|
||||
}: LoginShellProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container}>
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
|
||||
style={styles.flex}
|
||||
>
|
||||
<View style={styles.header}>
|
||||
{onBack ? (
|
||||
<Pressable onPress={onBack} hitSlop={12} style={styles.headerButton}>
|
||||
<ArrowLeft size={22} color={c.textSecondary} />
|
||||
</Pressable>
|
||||
) : (
|
||||
<View style={styles.headerButton} />
|
||||
)}
|
||||
{onClose ? (
|
||||
<Pressable onPress={onClose} hitSlop={12} style={styles.headerButton}>
|
||||
<X size={22} color={c.textSecondary} />
|
||||
</Pressable>
|
||||
) : (
|
||||
<View style={styles.headerButton} />
|
||||
)}
|
||||
</View>
|
||||
|
||||
<ScrollView
|
||||
style={styles.flex}
|
||||
contentContainerStyle={[styles.content, centered && styles.contentCentered]}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{children}
|
||||
</ScrollView>
|
||||
|
||||
{showFooter ? (
|
||||
<View style={styles.footer}>
|
||||
<Text style={styles.footerText}>Bulwark Mobile v{APP_VERSION}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</KeyboardAvoidingView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
container: { flex: 1, backgroundColor: c.background },
|
||||
flex: { flex: 1 },
|
||||
header: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
paddingHorizontal: spacing.lg,
|
||||
height: 44,
|
||||
},
|
||||
headerButton: { width: 32, height: 32, alignItems: 'center', justifyContent: 'center' },
|
||||
content: {
|
||||
paddingHorizontal: spacing.xxl,
|
||||
paddingBottom: spacing.xxxl,
|
||||
},
|
||||
contentCentered: { flexGrow: 1, justifyContent: 'center' },
|
||||
footer: { alignItems: 'center', paddingBottom: spacing.lg, gap: spacing.xs },
|
||||
footerText: { ...typography.caption, color: c.textMuted },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import React from 'react';
|
||||
import { View, Text, Pressable, StyleSheet } from 'react-native';
|
||||
import { ChevronRight } from 'lucide-react-native';
|
||||
import { spacing, radius, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
|
||||
interface OptionTileProps {
|
||||
title: string;
|
||||
description?: string;
|
||||
/** Receives the colour the tile's text renders in. */
|
||||
renderIcon: (color: string, size: number) => React.ReactNode;
|
||||
onPress: () => void;
|
||||
emphasis?: 'primary' | 'default';
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A full-width choice on the sign-in screen: icon, what it does, and what it
|
||||
* costs you. Used instead of a stack of buttons so each route can say enough
|
||||
* to be picked without trial and error.
|
||||
*/
|
||||
export default function OptionTile({
|
||||
title,
|
||||
description,
|
||||
renderIcon,
|
||||
onPress,
|
||||
emphasis = 'default',
|
||||
disabled = false,
|
||||
}: OptionTileProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const isPrimary = emphasis === 'primary';
|
||||
const contentColor = isPrimary ? c.primaryForeground : c.text;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
onPress={onPress}
|
||||
disabled={disabled}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={description ? `${title}. ${description}` : title}
|
||||
style={({ pressed }) => [
|
||||
styles.tile,
|
||||
isPrimary ? styles.tilePrimary : styles.tileDefault,
|
||||
pressed && !disabled && (isPrimary ? styles.pressedPrimary : styles.pressedDefault),
|
||||
disabled && styles.disabled,
|
||||
]}
|
||||
>
|
||||
<View style={styles.icon}>{renderIcon(contentColor, 22)}</View>
|
||||
<View style={styles.text}>
|
||||
<Text style={[styles.title, { color: contentColor }]}>{title}</Text>
|
||||
{description ? (
|
||||
<Text
|
||||
style={[
|
||||
styles.description,
|
||||
{ color: isPrimary ? c.primaryForeground : c.textSecondary },
|
||||
isPrimary && styles.descriptionPrimary,
|
||||
]}
|
||||
>
|
||||
{description}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<ChevronRight size={18} color={contentColor} style={styles.chevron} />
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
tile: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.md,
|
||||
borderRadius: radius.lg,
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingVertical: spacing.lg,
|
||||
borderWidth: 1,
|
||||
},
|
||||
tileDefault: { backgroundColor: c.surface, borderColor: c.border },
|
||||
tilePrimary: { backgroundColor: c.primary, borderColor: c.primary },
|
||||
pressedDefault: { backgroundColor: c.surfaceHover },
|
||||
pressedPrimary: { backgroundColor: c.primaryDark },
|
||||
disabled: { opacity: 0.5 },
|
||||
icon: { width: 22, alignItems: 'center' },
|
||||
text: { flex: 1, gap: 2 },
|
||||
title: { ...typography.baseMedium },
|
||||
description: { ...typography.caption },
|
||||
descriptionPrimary: { opacity: 0.8 },
|
||||
chevron: { opacity: 0.5 },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import React from 'react';
|
||||
import { View, Text, Pressable, StyleSheet } from 'react-native';
|
||||
import { Eye, EyeOff } from 'lucide-react-native';
|
||||
import { spacing, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
import { Button, Input } from '../../components';
|
||||
import LoginNotice from './LoginNotice';
|
||||
|
||||
interface PasswordStepProps {
|
||||
serverUrl: string;
|
||||
email: string;
|
||||
password: string;
|
||||
onChangeEmail: (value: string) => void;
|
||||
onChangePassword: (value: string) => void;
|
||||
onSubmit: () => void;
|
||||
notice?: { title: string; detail?: string } | null;
|
||||
}
|
||||
|
||||
function hostOf(url: string): string {
|
||||
return url.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '').split('/')[0];
|
||||
}
|
||||
|
||||
/** The fallback for servers without the browser hand-off — and the only step
|
||||
* where a password is typed into the app. */
|
||||
export default function PasswordStep({
|
||||
serverUrl,
|
||||
email,
|
||||
password,
|
||||
onChangeEmail,
|
||||
onChangePassword,
|
||||
onSubmit,
|
||||
notice,
|
||||
}: PasswordStepProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const [showPassword, setShowPassword] = React.useState(false);
|
||||
|
||||
return (
|
||||
<View style={styles.root}>
|
||||
<View style={styles.heading}>
|
||||
<Text style={styles.title}>Sign in to {hostOf(serverUrl)}</Text>
|
||||
<Text style={styles.subtitle}>
|
||||
Your password is sent to this server only, and stored in the device keychain.
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<Input
|
||||
label="Email or username"
|
||||
placeholder="you@example.com"
|
||||
value={email}
|
||||
onChangeText={onChangeEmail}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
autoComplete="email"
|
||||
textContentType="username"
|
||||
keyboardType="email-address"
|
||||
/>
|
||||
|
||||
<Input
|
||||
label="Password"
|
||||
placeholder="Enter your password"
|
||||
value={password}
|
||||
onChangeText={onChangePassword}
|
||||
autoFocus={Boolean(email)}
|
||||
secureTextEntry={!showPassword}
|
||||
autoComplete="current-password"
|
||||
textContentType="password"
|
||||
returnKeyType="go"
|
||||
onSubmitEditing={onSubmit}
|
||||
rightIcon={
|
||||
<Pressable
|
||||
onPress={() => setShowPassword((v) => !v)}
|
||||
hitSlop={8}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={showPassword ? 'Hide password' : 'Show password'}
|
||||
>
|
||||
{showPassword ? <EyeOff size={20} color={c.textMuted} /> : <Eye size={20} color={c.textMuted} />}
|
||||
</Pressable>
|
||||
}
|
||||
/>
|
||||
|
||||
{notice ? <LoginNotice title={notice.title} detail={notice.detail} /> : null}
|
||||
|
||||
<Button variant="default" size="lg" onPress={onSubmit}>
|
||||
Sign in
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
root: { gap: spacing.lg },
|
||||
heading: { gap: spacing.sm },
|
||||
title: { ...typography.h1, color: c.text },
|
||||
subtitle: { ...typography.body, color: c.textSecondary },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import React from 'react';
|
||||
import { View, Text, Pressable, StyleSheet } from 'react-native';
|
||||
import { Globe, QrCode } from 'lucide-react-native';
|
||||
import { spacing, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors } from '../../theme/colors';
|
||||
import { Button, Input } from '../../components';
|
||||
import LoginNotice from './LoginNotice';
|
||||
|
||||
interface ServerStepProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
onSubmit: () => void;
|
||||
onScan: () => void;
|
||||
/** Set when we got here because discovery came back empty for this domain. */
|
||||
failedDomain?: string | null;
|
||||
notice?: { title: string; detail?: string } | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks for the address people actually know — the one they type in the browser
|
||||
* to reach their webmail — not the JMAP session endpoint. The scheme and the
|
||||
* `/.well-known/jmap` suffix are our problem, not theirs.
|
||||
*/
|
||||
export default function ServerStep({
|
||||
value,
|
||||
onChange,
|
||||
onSubmit,
|
||||
onScan,
|
||||
failedDomain,
|
||||
notice,
|
||||
}: ServerStepProps) {
|
||||
const c = useColors();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
|
||||
return (
|
||||
<View style={styles.root}>
|
||||
<View style={styles.heading}>
|
||||
<Text style={styles.title}>Where does your mail live?</Text>
|
||||
<Text style={styles.subtitle}>
|
||||
{failedDomain
|
||||
? `We couldn't find a server for ${failedDomain}. If you self-host, the address is the one you use for webmail.`
|
||||
: 'Enter the address you use to reach your webmail.'}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<Input
|
||||
label="Server address"
|
||||
placeholder="mail.example.com"
|
||||
value={value}
|
||||
onChangeText={onChange}
|
||||
autoFocus
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
keyboardType="url"
|
||||
returnKeyType="go"
|
||||
onSubmitEditing={onSubmit}
|
||||
leftIcon={<Globe size={17} color={c.textMuted} />}
|
||||
/>
|
||||
|
||||
<Text style={styles.hint}>Same address you type in the browser. We'll add https:// for you.</Text>
|
||||
|
||||
{notice ? <LoginNotice title={notice.title} detail={notice.detail} /> : null}
|
||||
|
||||
<Button variant="default" size="lg" onPress={onSubmit}>
|
||||
Continue
|
||||
</Button>
|
||||
|
||||
<Pressable onPress={onScan} hitSlop={8} style={styles.scanRow}>
|
||||
<QrCode size={15} color={c.textMuted} />
|
||||
<Text style={styles.scanText}>
|
||||
Not sure? Scan a sign-in code instead — it carries the address with it.
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
root: { gap: spacing.lg },
|
||||
heading: { gap: spacing.sm },
|
||||
title: { ...typography.h1, color: c.text },
|
||||
subtitle: { ...typography.body, color: c.textSecondary },
|
||||
hint: { ...typography.caption, color: c.textMuted, marginTop: -spacing.sm },
|
||||
scanRow: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm, paddingVertical: spacing.sm },
|
||||
scanText: { ...typography.caption, color: c.textMuted, flex: 1, lineHeight: 17 },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet, ActivityIndicator, Image } from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { spacing, radius, typography, type ThemePalette } from '../../theme/tokens';
|
||||
import { useColors, useResolvedTheme } from '../../theme/colors';
|
||||
|
||||
// The white mark disappears on the light palette, so pick per theme.
|
||||
const LOGO_LIGHT = require('../../../assets/logos/Bulwark Logo Dark.png');
|
||||
const LOGO_DARK = require('../../../assets/logos/Bulwark Logo White.png');
|
||||
|
||||
export type SigningInPhase = 'browser' | 'connecting' | 'pairing';
|
||||
|
||||
interface SigningInStepProps {
|
||||
phase: SigningInPhase;
|
||||
serverUrl: string | null;
|
||||
email: string | null;
|
||||
}
|
||||
|
||||
function hostOf(url: string | null): string {
|
||||
if (!url) return 'your server';
|
||||
return url.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '').split('/')[0];
|
||||
}
|
||||
|
||||
function initialsOf(email: string): string {
|
||||
const local = email.replace(/@.*$/, '');
|
||||
const parts = local.split(/[.\s_-]+/).filter(Boolean);
|
||||
const letters = parts.slice(0, 2).map((part) => part[0]);
|
||||
return (letters.join('') || local[0] || '?').toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Covers the wait while a sign-in is in flight. Naming the server and the
|
||||
* current stage makes a slow first connection legible instead of a bare
|
||||
* spinner that could mean anything.
|
||||
*/
|
||||
export default function SigningInStep({ phase, serverUrl, email }: SigningInStepProps) {
|
||||
const c = useColors();
|
||||
const theme = useResolvedTheme();
|
||||
const styles = React.useMemo(() => makeStyles(c), [c]);
|
||||
const host = hostOf(serverUrl);
|
||||
|
||||
const copy: Record<SigningInPhase, { title: string; detail: string }> = {
|
||||
browser: {
|
||||
title: `Opening ${host}`,
|
||||
detail: 'Finish signing in on the page that just opened. We’ll take it from there.',
|
||||
},
|
||||
connecting: { title: `Connecting to ${host}`, detail: 'Setting up your mailbox…' },
|
||||
pairing: { title: 'Redeeming your sign-in code', detail: `Pairing this device with ${host}…` },
|
||||
};
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container}>
|
||||
<View style={styles.content}>
|
||||
{email ? (
|
||||
<View style={styles.avatar}>
|
||||
<Text style={styles.avatarText}>{initialsOf(email)}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<Image
|
||||
source={theme === 'light' ? LOGO_LIGHT : LOGO_DARK}
|
||||
style={styles.logo}
|
||||
resizeMode="contain"
|
||||
/>
|
||||
)}
|
||||
|
||||
{email ? <Text style={styles.email}>{email}</Text> : null}
|
||||
<Text style={styles.title}>{copy[phase].title}</Text>
|
||||
<Text style={styles.detail}>{copy[phase].detail}</Text>
|
||||
|
||||
<ActivityIndicator size="small" color={c.primary} style={styles.spinner} />
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
function makeStyles(c: ThemePalette) {
|
||||
return StyleSheet.create({
|
||||
container: { flex: 1, backgroundColor: c.background },
|
||||
content: {
|
||||
flex: 1,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: spacing.xxl,
|
||||
gap: spacing.xs,
|
||||
},
|
||||
avatar: {
|
||||
width: 60,
|
||||
height: 60,
|
||||
borderRadius: radius.full,
|
||||
backgroundColor: c.primary,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
avatarText: { ...typography.h2, color: c.primaryForeground },
|
||||
logo: { width: 60, height: 60, marginBottom: spacing.md },
|
||||
email: { ...typography.caption, color: c.textMuted },
|
||||
title: { ...typography.h2, color: c.text, textAlign: 'center' },
|
||||
detail: { ...typography.body, color: c.textSecondary, textAlign: 'center' },
|
||||
spinner: { marginTop: spacing.xl },
|
||||
});
|
||||
}
|
||||
@@ -7,6 +7,7 @@ vi.mock('../../api/calendar', () => ({
|
||||
createEvent: vi.fn(),
|
||||
updateEvent: vi.fn(),
|
||||
deleteEvents: vi.fn(),
|
||||
setDefaultCalendar: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@react-native-async-storage/async-storage', () => ({
|
||||
@@ -37,12 +38,15 @@ const mockGetEvents = calendarApi.getEvents as ReturnType<typeof vi.fn>;
|
||||
const mockCreateEvent = calendarApi.createEvent as ReturnType<typeof vi.fn>;
|
||||
const mockUpdateEvent = calendarApi.updateEvent as ReturnType<typeof vi.fn>;
|
||||
const mockDeleteEvents = calendarApi.deleteEvents as ReturnType<typeof vi.fn>;
|
||||
const mockSetDefaultCalendar = calendarApi.setDefaultCalendar as ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useCalendarStore.setState({
|
||||
calendars: [],
|
||||
events: [],
|
||||
tasks: [],
|
||||
taskOnlyCalendarIds: [],
|
||||
hiddenCalendarIds: [],
|
||||
loadedRange: null,
|
||||
loading: false,
|
||||
@@ -99,6 +103,105 @@ describe('calendar-store', () => {
|
||||
expect(useCalendarStore.getState().events).toEqual([]);
|
||||
expect(mockGetEvents).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('namespaces shared/group event ids by owning account and keeps the real id in originalId', async () => {
|
||||
// A shared calendar lives in another account; its event id ("ev1") can
|
||||
// collide with one of the user's own events, so the store must namespace
|
||||
// it. Mirrors webmail's mapServerEventToStoreEvent.
|
||||
useCalendarStore.setState({
|
||||
calendars: [
|
||||
{ id: 'cal-1', name: 'Personal' } as any,
|
||||
{ id: 'shared-cal', name: 'Team', accountId: 'acc-2', isShared: true } as any,
|
||||
],
|
||||
});
|
||||
mockQueryEvents.mockImplementation(async (_ids: string[], _a: string, _b: string, accountId?: string) =>
|
||||
accountId === 'acc-2' ? ['ev1'] : [],
|
||||
);
|
||||
mockGetEvents.mockImplementation(async (_ids: string[], accountId?: string) =>
|
||||
accountId === 'acc-2'
|
||||
? [{ id: 'ev1', title: 'Standup', start: '2026-03-15T10:00:00', calendarIds: { 'shared-cal': true } }]
|
||||
: [],
|
||||
);
|
||||
|
||||
await useCalendarStore.getState().fetchEvents(['cal-1', 'shared-cal'], '2026-03-01', '2026-03-31');
|
||||
|
||||
const stored = useCalendarStore.getState().events;
|
||||
expect(stored).toHaveLength(1);
|
||||
expect(stored[0].id).toBe('acc-2:ev1');
|
||||
expect(stored[0].originalId).toBe('ev1');
|
||||
expect(stored[0].accountId).toBe('acc-2');
|
||||
});
|
||||
|
||||
it('classifies calendars whose contents are all Tasks as task lists (#28)', async () => {
|
||||
// VTODO-only CalDAV collections (Todoist imports, Thunderbird task
|
||||
// lists) must be flagged so the drawer can keep them out of the
|
||||
// calendar list. Mixed calendars, calendars with start-less Events,
|
||||
// and empty calendars all stay ordinary calendars.
|
||||
mockQueryEvents.mockResolvedValue(['t1', 'e1', 't2', 'startless']);
|
||||
mockGetEvents.mockResolvedValue([
|
||||
{ id: 't1', '@type': 'Task', title: 'Buy milk', calendarIds: { 'cal-tasks': true } },
|
||||
{ id: 'e1', '@type': 'Event', start: '2026-03-15T10:00:00', calendarIds: { 'cal-mixed': true } },
|
||||
{ id: 't2', '@type': 'Task', title: 'Ship it', calendarIds: { 'cal-mixed': true } },
|
||||
{ id: 'startless', '@type': 'Event', calendarIds: { 'cal-startless': true } },
|
||||
]);
|
||||
|
||||
await useCalendarStore.getState().fetchEvents(
|
||||
['cal-tasks', 'cal-mixed', 'cal-startless', 'cal-empty'],
|
||||
'2026-03-01',
|
||||
'2026-03-31',
|
||||
);
|
||||
|
||||
expect(useCalendarStore.getState().taskOnlyCalendarIds).toEqual(['cal-tasks']);
|
||||
expect(useCalendarStore.getState().tasks.map((t) => t.id)).toEqual(['t1', 't2']);
|
||||
});
|
||||
|
||||
it('reclassifies task lists on refetch instead of accumulating stale ids', async () => {
|
||||
useCalendarStore.setState({ taskOnlyCalendarIds: ['cal-old'] });
|
||||
mockQueryEvents.mockResolvedValue(['e1']);
|
||||
mockGetEvents.mockResolvedValue([
|
||||
{ id: 'e1', '@type': 'Event', start: '2026-03-15T10:00:00', calendarIds: { 'cal-old': true } },
|
||||
]);
|
||||
|
||||
await useCalendarStore.getState().fetchEvents(['cal-old'], '2026-03-01', '2026-03-31');
|
||||
|
||||
expect(useCalendarStore.getState().taskOnlyCalendarIds).toEqual([]);
|
||||
});
|
||||
|
||||
it('routes queries by account when own and shared calendars share a raw id', async () => {
|
||||
// The user's own "default" calendar and a family group's "default"
|
||||
// calendar collide on the raw JMAP id. The shared one is namespaced
|
||||
// (`acc-2:default`, originalId "default"); the query must use the raw id
|
||||
// against acc-2, and the returned event's calendarIds must be remapped to
|
||||
// the namespaced store id so it isn't hidden with the personal calendar.
|
||||
useCalendarStore.setState({
|
||||
calendars: [
|
||||
{ id: 'default', name: 'Personal' } as any,
|
||||
{ id: 'acc-2:default', originalId: 'default', name: 'Family', accountId: 'acc-2', isShared: true } as any,
|
||||
],
|
||||
});
|
||||
const queried: Record<string, string[]> = {};
|
||||
mockQueryEvents.mockImplementation(async (ids: string[], _a: string, _b: string, accountId?: string) => {
|
||||
queried[accountId ?? 'primary'] = ids;
|
||||
return accountId === 'acc-2' ? ['fam1'] : [];
|
||||
});
|
||||
mockGetEvents.mockImplementation(async (_ids: string[], accountId?: string) =>
|
||||
accountId === 'acc-2'
|
||||
? [{ id: 'fam1', title: 'Soccer', start: '2026-03-20T15:00:00', calendarIds: { default: true } }]
|
||||
: [],
|
||||
);
|
||||
|
||||
await useCalendarStore.getState().fetchEvents(['default', 'acc-2:default'], '2026-03-01', '2026-03-31');
|
||||
|
||||
// The shared account is queried with the raw calendar id, not the prefix.
|
||||
expect(queried['acc-2']).toEqual(['default']);
|
||||
const ev = useCalendarStore.getState().events[0];
|
||||
expect(ev.calendarIds).toEqual({ 'acc-2:default': true });
|
||||
|
||||
// Hiding the personal "default" must not hide the family event.
|
||||
useCalendarStore.setState({ hiddenCalendarIds: ['default'] });
|
||||
const visible = selectVisibleEvents(useCalendarStore.getState());
|
||||
expect(visible.map((e) => e.id)).toContain('acc-2:fam1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ensureRange', () => {
|
||||
@@ -110,7 +213,8 @@ describe('calendar-store', () => {
|
||||
|
||||
await useCalendarStore.getState().ensureRange('2026-03-01', '2026-03-31');
|
||||
|
||||
expect(mockQueryEvents).toHaveBeenCalledWith(['cal-1'], '2026-03-01', '2026-03-31');
|
||||
// 4th arg is the owning account — undefined for primary-account calendars.
|
||||
expect(mockQueryEvents).toHaveBeenCalledWith(['cal-1'], '2026-03-01', '2026-03-31', undefined);
|
||||
});
|
||||
|
||||
it('should skip refetch when loaded range covers requested', async () => {
|
||||
@@ -134,7 +238,7 @@ describe('calendar-store', () => {
|
||||
|
||||
await useCalendarStore.getState().ensureRange('2026-04-01', '2026-04-30');
|
||||
|
||||
expect(mockQueryEvents).toHaveBeenCalledWith(['cal-1'], '2026-03-01', '2026-04-30');
|
||||
expect(mockQueryEvents).toHaveBeenCalledWith(['cal-1'], '2026-03-01', '2026-04-30', undefined);
|
||||
});
|
||||
|
||||
it('should fetch calendars first when none are loaded', async () => {
|
||||
@@ -144,7 +248,7 @@ describe('calendar-store', () => {
|
||||
await useCalendarStore.getState().ensureRange('2026-03-01', '2026-03-31');
|
||||
|
||||
expect(mockGetCalendars).toHaveBeenCalled();
|
||||
expect(mockQueryEvents).toHaveBeenCalledWith(['cal-1'], '2026-03-01', '2026-03-31');
|
||||
expect(mockQueryEvents).toHaveBeenCalledWith(['cal-1'], '2026-03-01', '2026-03-31', undefined);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -273,8 +377,31 @@ describe('calendar-store', () => {
|
||||
);
|
||||
|
||||
// The third arg is the iMIP scheduling flag — undefined here since the
|
||||
// event has no participants to notify.
|
||||
expect(mockUpdateEvent).toHaveBeenCalledWith('master', { title: 'New' }, undefined);
|
||||
// event has no participants to notify. The fourth is the owning
|
||||
// account — undefined for primary-account events.
|
||||
expect(mockUpdateEvent).toHaveBeenCalledWith('master', { title: 'New' }, undefined, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setDefaultCalendar', () => {
|
||||
it('flips isDefault to the chosen calendar within the same account', async () => {
|
||||
useCalendarStore.setState({
|
||||
calendars: [
|
||||
{ id: 'cal-1', name: 'A', isDefault: true } as any,
|
||||
{ id: 'cal-2', name: 'B' } as any,
|
||||
{ id: 'cal-3', name: 'Shared', isShared: true, accountId: 'acc-2', isDefault: true } as any,
|
||||
],
|
||||
});
|
||||
mockSetDefaultCalendar.mockResolvedValue(undefined);
|
||||
|
||||
await useCalendarStore.getState().setDefaultCalendar('cal-2');
|
||||
|
||||
expect(mockSetDefaultCalendar).toHaveBeenCalledWith('cal-2', undefined);
|
||||
const calendars = useCalendarStore.getState().calendars;
|
||||
expect(calendars.find((c) => c.id === 'cal-1')?.isDefault).toBe(false);
|
||||
expect(calendars.find((c) => c.id === 'cal-2')?.isDefault).toBe(true);
|
||||
// Defaults in other accounts are untouched.
|
||||
expect(calendars.find((c) => c.id === 'cal-3')?.isDefault).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -111,6 +111,7 @@ import { useEmailStore } from '../email-store';
|
||||
|
||||
const mockGetMailboxesWithState = emailApi.getMailboxesWithState as ReturnType<typeof vi.fn>;
|
||||
const mockQueryEmails = emailApi.queryEmails as ReturnType<typeof vi.fn>;
|
||||
const mockGetEmailQueryChanges = emailApi.getEmailQueryChanges as ReturnType<typeof vi.fn>;
|
||||
const mockGetEmails = emailApi.getEmails as ReturnType<typeof vi.fn>;
|
||||
const mockGetEmailsWithState = emailApi.getEmailsWithState as ReturnType<typeof vi.fn>;
|
||||
const mockGetFullEmail = emailApi.getFullEmail as ReturnType<typeof vi.fn>;
|
||||
@@ -313,6 +314,149 @@ describe('email-store', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// Issue #6: the "Unread" tri-state filter must reach Email/query as a
|
||||
// notKeyword condition and force the full re-query path (the incremental
|
||||
// path only serves the unfiltered base view).
|
||||
describe('filters (issue #6)', () => {
|
||||
it('applies the unread filter to the mailbox query', async () => {
|
||||
useEmailStore.setState({
|
||||
currentMailboxId: 'mb-1',
|
||||
emails: [],
|
||||
totalEmails: 0,
|
||||
searchQuery: '',
|
||||
filters: { isUnread: true },
|
||||
mailboxSnapshots: {
|
||||
'mb-1': { emails: [{ id: 'e9' } as any], total: 1, queryState: 'q-base' },
|
||||
},
|
||||
});
|
||||
mockQueryEmails.mockResolvedValue({ ids: ['e1'], total: 1, queryState: 'q-unread' });
|
||||
mockGetEmailsWithState.mockResolvedValue({ list: [{ id: 'e1' } as any], state: 'em-1' });
|
||||
|
||||
await useEmailStore.getState().refreshEmails();
|
||||
|
||||
expect(mockGetEmailQueryChanges).not.toHaveBeenCalled();
|
||||
const [mailboxId, opts] = mockQueryEmails.mock.calls[0];
|
||||
expect(mailboxId).toBe('mb-1');
|
||||
expect(opts.filter).toEqual({
|
||||
operator: 'AND',
|
||||
conditions: [{ inMailbox: 'mb-1' }, { notKeyword: '$seen' }],
|
||||
});
|
||||
// Filter results must not leak into the base-view snapshot.
|
||||
expect(useEmailStore.getState().mailboxSnapshots['mb-1'].emails).toEqual([{ id: 'e9' }]);
|
||||
});
|
||||
});
|
||||
|
||||
// Issue #10: after searching, the inbox stayed stuck on the search results.
|
||||
// Root cause: the incremental Email/queryChanges refresh diffed against the
|
||||
// on-screen list (search results) instead of the cached base view, then
|
||||
// wrote the result back into the persisted mailbox snapshot.
|
||||
describe('search / return to inbox (issue #10)', () => {
|
||||
const base = [
|
||||
{ id: 'e1', subject: 'One' } as any,
|
||||
{ id: 'e2', subject: 'Two' } as any,
|
||||
];
|
||||
|
||||
it('incremental refresh diffs against the snapshot, not on-screen search results', async () => {
|
||||
// Screen still shows a (stale) search-result list, but searchQuery is
|
||||
// already '' — the cold-start / just-cleared-search shape.
|
||||
useEmailStore.setState({
|
||||
currentMailboxId: 'mb-1',
|
||||
emails: [base[1]],
|
||||
totalEmails: 1,
|
||||
searchQuery: '',
|
||||
filters: {},
|
||||
mailboxSnapshots: { 'mb-1': { emails: base, total: 2, queryState: 'q-base' } },
|
||||
});
|
||||
mockGetEmailQueryChanges.mockResolvedValue({
|
||||
oldQueryState: 'q-base',
|
||||
newQueryState: 'q-2',
|
||||
total: 2,
|
||||
removed: [],
|
||||
added: [],
|
||||
});
|
||||
|
||||
await useEmailStore.getState().refreshEmails();
|
||||
|
||||
const state = useEmailStore.getState();
|
||||
expect(state.emails).toEqual(base);
|
||||
expect(state.mailboxSnapshots['mb-1'].emails).toEqual(base);
|
||||
expect(mockQueryEmails).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not write search results into the mailbox snapshot', async () => {
|
||||
useEmailStore.setState({
|
||||
currentMailboxId: 'mb-1',
|
||||
emails: base,
|
||||
totalEmails: 2,
|
||||
searchQuery: 'two',
|
||||
filters: {},
|
||||
queryState: 'q-base',
|
||||
mailboxSnapshots: { 'mb-1': { emails: base, total: 2, queryState: 'q-base' } },
|
||||
});
|
||||
mockQueryEmails.mockResolvedValue({ ids: ['e2'], total: 1, queryState: 'q-search' });
|
||||
mockGetEmailsWithState.mockResolvedValue({ list: [base[1]], state: 'em-1' });
|
||||
|
||||
await useEmailStore.getState().refreshEmails();
|
||||
|
||||
const state = useEmailStore.getState();
|
||||
expect(state.emails).toEqual([base[1]]);
|
||||
// Base-view cache must survive the search untouched.
|
||||
expect(state.mailboxSnapshots['mb-1'].emails).toEqual(base);
|
||||
expect(state.queryState).toBe('q-base');
|
||||
expect(mockGetEmailQueryChanges).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clearSearchAndFilters restores the cached base view immediately', () => {
|
||||
useEmailStore.setState({
|
||||
currentMailboxId: 'mb-1',
|
||||
emails: [base[1]],
|
||||
totalEmails: 1,
|
||||
searchQuery: 'two',
|
||||
filters: {},
|
||||
mailboxSnapshots: { 'mb-1': { emails: base, total: 2, queryState: 'q-base' } },
|
||||
});
|
||||
mockGetEmailQueryChanges.mockResolvedValue({
|
||||
oldQueryState: 'q-base',
|
||||
newQueryState: 'q-2',
|
||||
total: 2,
|
||||
removed: [],
|
||||
added: [],
|
||||
});
|
||||
|
||||
useEmailStore.getState().clearSearchAndFilters();
|
||||
|
||||
// Synchronously back on the base view — no waiting for the network.
|
||||
const state = useEmailStore.getState();
|
||||
expect(state.searchQuery).toBe('');
|
||||
expect(state.emails).toEqual(base);
|
||||
expect(state.totalEmails).toBe(2);
|
||||
});
|
||||
|
||||
it('falls back to a full re-query when the snapshot window is incomplete', async () => {
|
||||
// A pre-fix install could have a poisoned snapshot: a handful of search
|
||||
// results stored against the base view's total. It can't be patched
|
||||
// incrementally — the refresh must rebuild it from the server.
|
||||
useEmailStore.setState({
|
||||
currentMailboxId: 'mb-1',
|
||||
emails: [base[1]],
|
||||
totalEmails: 1,
|
||||
searchQuery: '',
|
||||
filters: {},
|
||||
mailboxSnapshots: { 'mb-1': { emails: [base[1]], total: 50, queryState: 'q-base' } },
|
||||
});
|
||||
mockQueryEmails.mockResolvedValue({ ids: ['e1', 'e2'], total: 50, queryState: 'q-new' });
|
||||
mockGetEmailsWithState.mockResolvedValue({ list: base, state: 'em-2' });
|
||||
|
||||
await useEmailStore.getState().refreshEmails();
|
||||
|
||||
const state = useEmailStore.getState();
|
||||
expect(mockGetEmailQueryChanges).not.toHaveBeenCalled();
|
||||
expect(state.emails).toEqual(base);
|
||||
expect(state.mailboxSnapshots['mb-1'].emails).toEqual(base);
|
||||
expect(state.mailboxSnapshots['mb-1'].queryState).toBe('q-new');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getEmailDetail', () => {
|
||||
it('should fetch full email', async () => {
|
||||
const fullEmail = { id: 'e1', subject: 'Test', bodyValues: { html: { value: '<p>Hi</p>' } } };
|
||||
|
||||
+151
-19
@@ -12,6 +12,7 @@ import {
|
||||
batchCreateEvents as apiBatchCreateEvents,
|
||||
rsvpEvent as apiRsvpEvent,
|
||||
createCalendar as apiCreateCalendar,
|
||||
setDefaultCalendar as apiSetDefaultCalendar,
|
||||
} from '../api/calendar';
|
||||
import { jmapClient } from '../api/jmap-client';
|
||||
import { expandRecurringEvents } from '../lib/recurrence-expansion';
|
||||
@@ -24,6 +25,37 @@ function hasSchedulingParticipants(event?: Partial<CalendarEvent> | null): boole
|
||||
|
||||
const HIDDEN_CALENDARS_STORAGE_KEY = 'webmail:calendar:hidden:v1';
|
||||
|
||||
// Map a server CalendarEvent onto its store representation. For events from a
|
||||
// shared/group account the JMAP id is only unique within that account, so we
|
||||
// namespace `id` (stashing the real id in originalId) and remap the event's
|
||||
// `calendarIds` from raw server ids onto the namespaced store calendar ids so
|
||||
// visibility filtering and per-calendar colour lookup line up. Events from the
|
||||
// primary account are returned unchanged. Mirrors webmail's
|
||||
// mapServerEventToStoreEvent.
|
||||
function mapServerEventToStoreEvent(
|
||||
event: CalendarEvent,
|
||||
calendars: Calendar[],
|
||||
accountId?: string,
|
||||
): CalendarEvent {
|
||||
if (!accountId) return event;
|
||||
const mapped: Record<string, boolean> = {};
|
||||
for (const [calId, included] of Object.entries(event.calendarIds || {})) {
|
||||
const cal = calendars.find(
|
||||
(c) => (c.originalId || c.id) === calId && c.accountId === accountId,
|
||||
);
|
||||
mapped[cal?.id || calId] = included;
|
||||
}
|
||||
return {
|
||||
...event,
|
||||
id: `${accountId}:${event.id}`,
|
||||
originalId: event.id,
|
||||
originalCalendarIds: event.calendarIds,
|
||||
calendarIds: Object.keys(mapped).length > 0 ? mapped : event.calendarIds,
|
||||
accountId,
|
||||
isShared: true,
|
||||
};
|
||||
}
|
||||
|
||||
export interface LoadedRange {
|
||||
after: string;
|
||||
before: string;
|
||||
@@ -33,6 +65,12 @@ export interface CalendarState {
|
||||
calendars: Calendar[];
|
||||
events: CalendarEvent[];
|
||||
tasks: CalendarEvent[];
|
||||
// Store ids of calendars that hold only Task objects (VTODO-only CalDAV
|
||||
// collections, e.g. Thunderbird/Todoist task lists). JMAP Calendar/get
|
||||
// doesn't expose the CalDAV supported-calendar-component-set, so the
|
||||
// collection kind is inferred from contents: ≥1 task and no events.
|
||||
// Empty calendars are treated as ordinary event calendars. (#28)
|
||||
taskOnlyCalendarIds: string[];
|
||||
hiddenCalendarIds: string[];
|
||||
loadedRange: LoadedRange | null;
|
||||
loading: boolean;
|
||||
@@ -57,6 +95,7 @@ export interface CalendarState {
|
||||
) => Promise<void>;
|
||||
importEvents: (events: Partial<CalendarEvent>[], calendarId: string) => Promise<number>;
|
||||
createCalendar: (name: string, color?: string) => Promise<Calendar>;
|
||||
setDefaultCalendar: (id: string) => Promise<void>;
|
||||
// Tasks
|
||||
createTask: (task: Partial<CalendarEvent>, calendarId: string) => Promise<void>;
|
||||
updateTask: (id: string, changes: Partial<CalendarEvent>) => Promise<void>;
|
||||
@@ -91,6 +130,7 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
calendars: [],
|
||||
events: [],
|
||||
tasks: [],
|
||||
taskOnlyCalendarIds: [],
|
||||
hiddenCalendarIds: [],
|
||||
loadedRange: null,
|
||||
loading: false,
|
||||
@@ -131,8 +171,37 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
if (!jmapClient.isConnected) return;
|
||||
set({ loading: true, error: null });
|
||||
try {
|
||||
const ids = (await queryEvents(calendarIds, after, before)) ?? [];
|
||||
const raw = ids.length > 0 ? ((await fetchEvents(ids)) ?? []) : [];
|
||||
// Group the requested calendars by owning account: the primary account
|
||||
// (calendars without an accountId tag) plus one group per shared
|
||||
// account, since CalendarEvent/query is scoped to a single account. The
|
||||
// incoming ids are store ids (shared calendars are namespaced
|
||||
// `${accountId}:${id}`); map them back to the raw server ids the query
|
||||
// filter expects.
|
||||
const calendars = get().calendars;
|
||||
const byId = new Map(calendars.map((c) => [c.id, c]));
|
||||
const groups = new Map<string | undefined, string[]>();
|
||||
for (const id of calendarIds) {
|
||||
const cal = byId.get(id);
|
||||
const accountId = cal?.accountId;
|
||||
const serverId = cal?.originalId || id;
|
||||
const group = groups.get(accountId);
|
||||
if (group) group.push(serverId);
|
||||
else groups.set(accountId, [serverId]);
|
||||
}
|
||||
if (groups.size === 0) groups.set(undefined, []);
|
||||
|
||||
const raw: CalendarEvent[] = [];
|
||||
for (const [accountId, ids] of groups) {
|
||||
try {
|
||||
const eventIds = (await queryEvents(ids, after, before, accountId)) ?? [];
|
||||
if (eventIds.length === 0) continue;
|
||||
const fetched = (await fetchEvents(eventIds, accountId)) ?? [];
|
||||
raw.push(...fetched.map((e) => mapServerEventToStoreEvent(e, calendars, accountId)));
|
||||
} catch (err) {
|
||||
// A failing shared account must not hide the user's own events.
|
||||
if (!accountId) throw err;
|
||||
}
|
||||
}
|
||||
// Stalwart returns both Events and Tasks from CalendarEvent/query. Events
|
||||
// have a `start`; tasks are surfaced separately so they don't pollute the
|
||||
// grid (they're shown in the task list with their due date instead).
|
||||
@@ -141,8 +210,23 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
return (t === 'Event' || t === undefined) && !!e.start;
|
||||
});
|
||||
const tasks = raw.filter((e) => (e as { '@type'?: string })['@type'] === 'Task');
|
||||
// Classify VTODO-only task lists from the full (undated) object set:
|
||||
// a calendar counts as a task list when every object in it is a Task.
|
||||
// Anything that isn't a Task — including start-less Events — keeps the
|
||||
// calendar in the ordinary event-calendar bucket.
|
||||
const eventCalendarIds = new Set<string>();
|
||||
const taskCalendarIds = new Set<string>();
|
||||
for (const obj of raw) {
|
||||
const isTask = (obj as { '@type'?: string })['@type'] === 'Task';
|
||||
for (const calId of Object.keys(obj.calendarIds || {})) {
|
||||
(isTask ? taskCalendarIds : eventCalendarIds).add(calId);
|
||||
}
|
||||
}
|
||||
const taskOnlyCalendarIds = [...taskCalendarIds].filter(
|
||||
(calId) => !eventCalendarIds.has(calId),
|
||||
);
|
||||
const events = expandRecurringEvents(onlyEvents, after, before);
|
||||
set({ events, tasks, loadedRange: { after, before }, loading: false });
|
||||
set({ events, tasks, taskOnlyCalendarIds, loadedRange: { after, before }, loading: false });
|
||||
} catch (err) {
|
||||
set({ loading: false, error: err instanceof Error ? err.message : 'Failed to load events' });
|
||||
}
|
||||
@@ -176,12 +260,19 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
|
||||
handleStateChange: async (change) => {
|
||||
if (!jmapClient.isConnected) return;
|
||||
const accountId = jmapClient.accountId;
|
||||
const accountChanges = change.changed?.[accountId];
|
||||
if (!accountChanges) return;
|
||||
|
||||
const calendarChanged = 'Calendar' in accountChanges;
|
||||
const eventChanged = 'CalendarEvent' in accountChanges;
|
||||
// Watch the primary account plus every shared account we show calendars
|
||||
// from, so edits the owner makes to a shared calendar refresh the view.
|
||||
const known = new Set<string>([jmapClient.accountId]);
|
||||
for (const cal of get().calendars) {
|
||||
if (cal.accountId) known.add(cal.accountId);
|
||||
}
|
||||
let calendarChanged = false;
|
||||
let eventChanged = false;
|
||||
for (const [accountId, types] of Object.entries(change.changed ?? {})) {
|
||||
if (!known.has(accountId)) continue;
|
||||
if ('Calendar' in types) calendarChanged = true;
|
||||
if ('CalendarEvent' in types) eventChanged = true;
|
||||
}
|
||||
if (!calendarChanged && !eventChanged) return;
|
||||
|
||||
if (calendarChanged) {
|
||||
@@ -193,12 +284,22 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
},
|
||||
|
||||
createEvent: async (event, calendarId) => {
|
||||
// Shared calendars live in the owner's account — route the create there,
|
||||
// and against the calendar's raw server id (calendarId is the namespaced
|
||||
// store id for shared calendars).
|
||||
const calendars = get().calendars;
|
||||
const cal = calendars.find((c) => c.id === calendarId);
|
||||
const accountId = cal?.accountId;
|
||||
const created = await apiCreateEvent(
|
||||
event,
|
||||
calendarId,
|
||||
cal?.originalId || calendarId,
|
||||
hasSchedulingParticipants(event) ? true : undefined,
|
||||
accountId,
|
||||
);
|
||||
set({ events: [...get().events, created] });
|
||||
// Map the same way fetchEvents does so the optimistic insert doesn't
|
||||
// collide with the user's own events and stays visible under the right
|
||||
// calendar filter.
|
||||
set({ events: [...get().events, mapServerEventToStoreEvent(created, calendars, accountId)] });
|
||||
return created;
|
||||
},
|
||||
|
||||
@@ -210,7 +311,7 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
// carry participants.
|
||||
const schedule =
|
||||
hasSchedulingParticipants(changes) || hasSchedulingParticipants(storeEvent);
|
||||
await apiUpdateEvent(realId, changes, schedule ? true : undefined);
|
||||
await apiUpdateEvent(realId, changes, schedule ? true : undefined, storeEvent?.accountId);
|
||||
set({
|
||||
events: get().events.map((e) => (e.id === id ? { ...e, ...changes } : e)),
|
||||
});
|
||||
@@ -222,6 +323,7 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
await apiDeleteEvents(
|
||||
[realId],
|
||||
hasSchedulingParticipants(storeEvent) ? true : undefined,
|
||||
storeEvent?.accountId,
|
||||
);
|
||||
set({ events: get().events.filter((e) => e.id !== id) });
|
||||
},
|
||||
@@ -232,7 +334,7 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
}
|
||||
const storeEvent = get().events.find((e) => e.id === eventId);
|
||||
const realId = storeEvent?.originalId || eventId;
|
||||
await apiRsvpEvent(realId, participantId, status, replyTo);
|
||||
await apiRsvpEvent(realId, participantId, status, replyTo, storeEvent?.accountId);
|
||||
set({
|
||||
events: get().events.map((e) => {
|
||||
if (e.id !== eventId || !e.participants?.[participantId]) return e;
|
||||
@@ -249,20 +351,26 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
|
||||
importEvents: async (events, calendarId) => {
|
||||
if (events.length === 0) return 0;
|
||||
// Shared calendars live in the owner's account and carry a namespaced
|
||||
// store id — resolve the raw server id + owning account so dedup and
|
||||
// create target the right place.
|
||||
const cal = get().calendars.find((c) => c.id === calendarId);
|
||||
const accountId = cal?.accountId;
|
||||
const serverCalendarId = cal?.originalId || calendarId;
|
||||
// Stalwart enforces UID uniqueness across calendars. Skip events whose UID
|
||||
// already exists; create the rest. (We don't attempt cross-calendar linking
|
||||
// on mobile — a duplicate is simply skipped.)
|
||||
let toCreate = events;
|
||||
try {
|
||||
const existingIds = await queryEvents([], '', '');
|
||||
const existing = existingIds.length > 0 ? await fetchEvents(existingIds) : [];
|
||||
const existingIds = await queryEvents([], '', '', accountId);
|
||||
const existing = existingIds.length > 0 ? await fetchEvents(existingIds, accountId) : [];
|
||||
const seenUids = new Set(existing.map((e) => e.uid).filter(Boolean) as string[]);
|
||||
toCreate = events.filter((e) => !e.uid || !seenUids.has(e.uid));
|
||||
} catch {
|
||||
// Couldn't dedupe — proceed and let the server reject genuine dupes.
|
||||
}
|
||||
if (toCreate.length === 0) return 0;
|
||||
const count = await apiBatchCreateEvents(toCreate, calendarId);
|
||||
const count = await apiBatchCreateEvents(toCreate, serverCalendarId, accountId);
|
||||
await get().refresh();
|
||||
return count;
|
||||
},
|
||||
@@ -273,15 +381,37 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
return created;
|
||||
},
|
||||
|
||||
setDefaultCalendar: async (id) => {
|
||||
const cal = get().calendars.find((c) => c.id === id);
|
||||
await apiSetDefaultCalendar(cal?.originalId || id, cal?.accountId);
|
||||
set({
|
||||
calendars: get().calendars.map((c) => {
|
||||
if (c.id === id) return { ...c, isDefault: true };
|
||||
// Only one default per account — clear the flag on siblings within
|
||||
// the same account scope.
|
||||
if (c.isDefault && (c.accountId ?? null) === (cal?.accountId ?? null)) {
|
||||
return { ...c, isDefault: false };
|
||||
}
|
||||
return c;
|
||||
}),
|
||||
});
|
||||
},
|
||||
|
||||
createTask: async (task, calendarId) => {
|
||||
await apiCreateEvent({ ...task, '@type': 'Task' }, calendarId);
|
||||
const cal = get().calendars.find((c) => c.id === calendarId);
|
||||
await apiCreateEvent(
|
||||
{ ...task, '@type': 'Task' },
|
||||
cal?.originalId || calendarId,
|
||||
undefined,
|
||||
cal?.accountId,
|
||||
);
|
||||
await get().refresh();
|
||||
},
|
||||
|
||||
updateTask: async (id, changes) => {
|
||||
const task = get().tasks.find((t) => t.id === id);
|
||||
const realId = task?.originalId || id;
|
||||
await apiUpdateEvent(realId, changes);
|
||||
await apiUpdateEvent(realId, changes, undefined, task?.accountId);
|
||||
set({ tasks: get().tasks.map((t) => (t.id === id ? { ...t, ...changes } : t)) });
|
||||
},
|
||||
|
||||
@@ -298,7 +428,7 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
deleteTask: async (id) => {
|
||||
const task = get().tasks.find((t) => t.id === id);
|
||||
const realId = task?.originalId || id;
|
||||
await apiDeleteEvents([realId]);
|
||||
await apiDeleteEvents([realId], undefined, task?.accountId);
|
||||
set({ tasks: get().tasks.filter((t) => t.id !== id) });
|
||||
},
|
||||
|
||||
@@ -326,6 +456,7 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
calendars: [],
|
||||
events: [],
|
||||
tasks: [],
|
||||
taskOnlyCalendarIds: [],
|
||||
loadedRange: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
@@ -341,6 +472,7 @@ export const useCalendarStore = create<CalendarState>()(
|
||||
calendars: state.calendars,
|
||||
events: state.events,
|
||||
tasks: state.tasks,
|
||||
taskOnlyCalendarIds: state.taskOnlyCalendarIds,
|
||||
loadedRange: state.loadedRange,
|
||||
}),
|
||||
},
|
||||
|
||||
+96
-13
@@ -223,6 +223,17 @@ function isBaseView(searchQuery: string, filters: EmailFilters): boolean {
|
||||
return !searchQuery.trim() && Object.keys(filters).length === 0;
|
||||
}
|
||||
|
||||
// View fields to apply when returning from a search/filter to the base view:
|
||||
// the cached base-view snapshot, shown immediately so the list doesn't keep
|
||||
// displaying search results while the refresh is in flight (issue #10).
|
||||
function restoredBaseView(state: EmailState): Partial<EmailState> {
|
||||
const snap = state.currentMailboxId
|
||||
? state.mailboxSnapshots[state.currentMailboxId]
|
||||
: undefined;
|
||||
if (!snap) return {};
|
||||
return { emails: snap.emails, totalEmails: snap.total, queryState: snap.queryState };
|
||||
}
|
||||
|
||||
function snapshotFromActive(state: EmailState): AccountSnapshot {
|
||||
// Persist the currently-visible mailbox into its snapshot before tucking
|
||||
// the whole account away.
|
||||
@@ -642,7 +653,7 @@ export const useEmailStore = create<EmailState>()(
|
||||
|
||||
refreshEmails: async () => {
|
||||
const state = get();
|
||||
const { currentMailboxId, searchQuery, filters, emails: existing, queryState, emailState, activeAccountId } = state;
|
||||
const { currentMailboxId, searchQuery, filters, emails: existing, emailState, activeAccountId } = state;
|
||||
if (!currentMailboxId) return;
|
||||
if (!jmapClientServesActiveAccount(activeAccountId)) return;
|
||||
set({ loading: true, error: null });
|
||||
@@ -651,13 +662,37 @@ export const useEmailStore = create<EmailState>()(
|
||||
const limit = useSettingsStore.getState().emailsPerPage;
|
||||
const baseView = isBaseView(searchQuery, filters);
|
||||
|
||||
// A response that lands after the user switched account/mailbox or
|
||||
// changed search/filters must not overwrite the newer view.
|
||||
const viewChanged = () =>
|
||||
get().activeAccountId !== activeAccountId ||
|
||||
get().currentMailboxId !== currentMailboxId ||
|
||||
get().searchQuery !== searchQuery ||
|
||||
get().filters !== filters;
|
||||
|
||||
// The incremental path diffs against the *base-view* list, which lives in
|
||||
// the per-mailbox snapshot — NOT `emails`, which may still hold search or
|
||||
// filter results (right after clearing a search, or after a cold start
|
||||
// that rehydrated a persisted search-result list). Diffing against a
|
||||
// non-base list lets Email/queryChanges "confirm" the search results as
|
||||
// the whole mailbox and bakes them into the snapshot (issue #10). The
|
||||
// snapshot is only trusted when its window is plausibly complete —
|
||||
// anything shorter can't be patched incrementally and needs the full
|
||||
// re-query below to rebuild it.
|
||||
const snap = state.mailboxSnapshots[currentMailboxId];
|
||||
|
||||
try {
|
||||
// Incremental sync path: requires the base unfiltered view AND a known
|
||||
// queryState (so Email/queryChanges has something to diff against).
|
||||
// Anything else — search, filter active, first-ever load — falls
|
||||
// through to a full re-query.
|
||||
if (baseView && queryState) {
|
||||
const queryChanges = await getEmailQueryChanges(currentMailboxId, queryState, {
|
||||
if (
|
||||
baseView &&
|
||||
snap?.queryState &&
|
||||
snap.emails.length >= Math.min(limit, snap.total)
|
||||
) {
|
||||
const baseEmails = snap.emails;
|
||||
const queryChanges = await getEmailQueryChanges(currentMailboxId, snap.queryState, {
|
||||
filter: undefined,
|
||||
});
|
||||
if (queryChanges) {
|
||||
@@ -687,9 +722,9 @@ export const useEmailStore = create<EmailState>()(
|
||||
}
|
||||
|
||||
// Fetch only what we don't already have. `addedIds` are new to the
|
||||
// window; `updatedIds` may already be in `existing` but their
|
||||
// window; `updatedIds` may already be in the base list but their
|
||||
// keywords/mailboxIds need refreshing.
|
||||
const existingById = new Map(existing.map((e) => [e.id, e]));
|
||||
const existingById = new Map(baseEmails.map((e) => [e.id, e]));
|
||||
const idsToFetch = [
|
||||
...addedIds.filter((id) => !existingById.has(id)),
|
||||
...updatedIds.filter((id) => existingById.has(id)),
|
||||
@@ -705,7 +740,7 @@ export const useEmailStore = create<EmailState>()(
|
||||
// Rebuild the visible window order: start with existing emails,
|
||||
// drop removed/destroyed, then splice added at their indices.
|
||||
const allDestroyed = new Set([...destroyedExtra, ...removed]);
|
||||
const kept = existing.filter((e) => !allDestroyed.has(e.id));
|
||||
const kept = baseEmails.filter((e) => !allDestroyed.has(e.id));
|
||||
// Map updated entries onto kept array
|
||||
const fetchedById = new Map(fetched.map((e) => [e.id, e]));
|
||||
const updatedKept = kept.map((e) => fetchedById.get(e.id) ?? e);
|
||||
@@ -727,7 +762,7 @@ export const useEmailStore = create<EmailState>()(
|
||||
const nextQueryState = queryChanges.newQueryState;
|
||||
const nextTotal = queryChanges.total;
|
||||
|
||||
if (get().activeAccountId !== activeAccountId || get().currentMailboxId !== currentMailboxId) return;
|
||||
if (viewChanged()) return;
|
||||
|
||||
set({
|
||||
emails: trimmed,
|
||||
@@ -758,7 +793,7 @@ export const useEmailStore = create<EmailState>()(
|
||||
? await getEmailsWithState(queryRes.ids)
|
||||
: { list: [], state: undefined as string | undefined };
|
||||
|
||||
if (get().currentMailboxId !== currentMailboxId) return;
|
||||
if (viewChanged()) return;
|
||||
|
||||
const updates: Partial<EmailState> = {
|
||||
emails: fetched.list,
|
||||
@@ -836,19 +871,31 @@ export const useEmailStore = create<EmailState>()(
|
||||
},
|
||||
|
||||
setSearchQuery: (query) => {
|
||||
set({ searchQuery: query });
|
||||
const state = get();
|
||||
const backToBase =
|
||||
!isBaseView(state.searchQuery, state.filters) && isBaseView(query, state.filters);
|
||||
set({
|
||||
searchQuery: query,
|
||||
...(backToBase ? restoredBaseView(state) : {}),
|
||||
});
|
||||
void get().refreshEmails();
|
||||
},
|
||||
|
||||
setFilters: (filters) => {
|
||||
set({ filters });
|
||||
const state = get();
|
||||
const backToBase =
|
||||
!isBaseView(state.searchQuery, state.filters) && isBaseView(state.searchQuery, filters);
|
||||
set({
|
||||
filters,
|
||||
...(backToBase ? restoredBaseView(state) : {}),
|
||||
});
|
||||
void get().refreshEmails();
|
||||
},
|
||||
|
||||
clearSearchAndFilters: () => {
|
||||
const { searchQuery, filters } = get();
|
||||
if (!searchQuery && Object.keys(filters).length === 0) return;
|
||||
set({ searchQuery: '', filters: {} });
|
||||
const state = get();
|
||||
if (!state.searchQuery && Object.keys(state.filters).length === 0) return;
|
||||
set({ searchQuery: '', filters: {}, ...restoredBaseView(state) });
|
||||
void get().refreshEmails();
|
||||
},
|
||||
|
||||
@@ -1330,6 +1377,42 @@ export const useEmailStore = create<EmailState>()(
|
||||
// refresh once the session is ready.
|
||||
name: 'email-cache',
|
||||
storage: createJSONStorage(() => AsyncStorage),
|
||||
version: 1,
|
||||
// v0 → v1: drop every cached queryState. Pre-v1 builds could persist a
|
||||
// search-result list next to the base view's queryState, and the
|
||||
// incremental sync path would then "confirm" those search results as
|
||||
// the whole mailbox and bake them into the snapshot (issue #10).
|
||||
// Without a queryState the next refresh does a full re-query, which
|
||||
// rebuilds any poisoned window from the server.
|
||||
migrate: (persisted, version) => {
|
||||
if (version >= 1) return persisted as EmailState;
|
||||
const s = persisted as Pick<
|
||||
EmailState,
|
||||
'accountSnapshots' | 'mailboxSnapshots' | 'queryState'
|
||||
> & Record<string, unknown>;
|
||||
const stripQueryStates = (
|
||||
snaps: Record<string, MailboxSnapshot> | undefined,
|
||||
): Record<string, MailboxSnapshot> =>
|
||||
Object.fromEntries(
|
||||
Object.entries(snaps ?? {}).map(([id, snap]) => [
|
||||
id,
|
||||
{ ...snap, queryState: undefined },
|
||||
]),
|
||||
);
|
||||
const accountSnapshots: Record<string, AccountSnapshot> = {};
|
||||
for (const [id, acc] of Object.entries(s.accountSnapshots ?? {})) {
|
||||
accountSnapshots[id] = {
|
||||
...acc,
|
||||
mailboxSnapshots: stripQueryStates(acc.mailboxSnapshots),
|
||||
};
|
||||
}
|
||||
return {
|
||||
...s,
|
||||
accountSnapshots,
|
||||
mailboxSnapshots: stripQueryStates(s.mailboxSnapshots),
|
||||
queryState: undefined,
|
||||
} as unknown as EmailState;
|
||||
},
|
||||
partialize: (state) => ({
|
||||
accountSnapshots: state.accountSnapshots,
|
||||
activeAccountId: state.activeAccountId,
|
||||
|
||||
@@ -169,6 +169,10 @@ interface PersistedSettings {
|
||||
showBirthdayCalendar: boolean;
|
||||
enableCalendarTasks: boolean;
|
||||
showTasksOnCalendar: boolean;
|
||||
// Per-viewer color overrides for shared calendars, keyed by
|
||||
// sharedCalendarColorKey(). Lets the user recolor calendars shared with
|
||||
// them without changing the owner's color (parity with webmail #345).
|
||||
sharedCalendarColors: Record<string, string>;
|
||||
|
||||
// Files
|
||||
filesFolderLayout: FilesFolderLayout;
|
||||
@@ -276,6 +280,7 @@ const DEFAULT_PERSISTED: PersistedSettings = {
|
||||
showBirthdayCalendar: true,
|
||||
enableCalendarTasks: false,
|
||||
showTasksOnCalendar: true,
|
||||
sharedCalendarColors: {},
|
||||
|
||||
filesFolderLayout: 'inline',
|
||||
filesDefaultViewMode: 'list',
|
||||
@@ -353,6 +358,10 @@ export interface SettingsState extends PersistedSettings {
|
||||
removeTrustedSender: (email: string) => void;
|
||||
isSenderTrusted: (email: string) => boolean;
|
||||
|
||||
// Shared-calendar color overrides
|
||||
setSharedCalendarColor: (key: string, color: string) => void;
|
||||
removeSharedCalendarColor: (key: string) => void;
|
||||
|
||||
// Sidebar apps
|
||||
addSidebarApp: (app: Omit<SidebarApp, 'id'>) => void;
|
||||
updateSidebarApp: (id: string, updates: Partial<Omit<SidebarApp, 'id'>>) => void;
|
||||
@@ -475,6 +484,17 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
return get().trustedSenders.includes(normalized);
|
||||
},
|
||||
|
||||
setSharedCalendarColor: (key, color) => {
|
||||
set({ sharedCalendarColors: { ...get().sharedCalendarColors, [key]: color } });
|
||||
persist(snapshot(get()));
|
||||
},
|
||||
|
||||
removeSharedCalendarColor: (key) => {
|
||||
const { [key]: _removed, ...rest } = get().sharedCalendarColors;
|
||||
set({ sharedCalendarColors: rest });
|
||||
persist(snapshot(get()));
|
||||
},
|
||||
|
||||
addSidebarApp: (app) => {
|
||||
const id = `app-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
|
||||
set({ sidebarApps: [...get().sidebarApps, { ...app, id }] });
|
||||
|
||||
@@ -4,6 +4,7 @@ import Constants from 'expo-constants';
|
||||
import { fetchLatestRelease, type LatestRelease } from '../api/updates';
|
||||
import { isNewer } from '../lib/version-compare';
|
||||
import { downloadAndInstallApk, type InstallProgress } from '../lib/install-update';
|
||||
import { supportsSideloadUpdates } from '../lib/platform-capabilities';
|
||||
|
||||
const STORAGE_KEY = 'webmail:updates:v1';
|
||||
const MIN_CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
||||
@@ -80,6 +81,10 @@ export const useUpdatesStore = create<UpdatesState>((set, get) => ({
|
||||
},
|
||||
|
||||
checkNow: async (opts) => {
|
||||
// On platforms without sideloading there is nothing actionable to report,
|
||||
// so skip the GitHub round-trip entirely rather than caching a release the
|
||||
// user can never install.
|
||||
if (!supportsSideloadUpdates) return;
|
||||
const s = get();
|
||||
if (s.checking) return;
|
||||
const now = Date.now();
|
||||
@@ -104,6 +109,7 @@ export const useUpdatesStore = create<UpdatesState>((set, get) => ({
|
||||
},
|
||||
|
||||
installLatest: async () => {
|
||||
if (!supportsSideloadUpdates) return;
|
||||
const s = get();
|
||||
if (s.installing || !s.cachedLatest?.apkAsset) return;
|
||||
set({ installing: true, error: null, installProgress: { phase: 'downloading', progress: 0 } });
|
||||
@@ -142,6 +148,7 @@ export const useUpdatesStore = create<UpdatesState>((set, get) => ({
|
||||
currentVersion: () => Constants.expoConfig?.version ?? '0.0.0',
|
||||
|
||||
hasUpdate: () => {
|
||||
if (!supportsSideloadUpdates) return false;
|
||||
const s = get();
|
||||
if (!s.cachedLatest) return false;
|
||||
const current = Constants.expoConfig?.version ?? '0.0.0';
|
||||
|
||||
Reference in New Issue
Block a user