diff --git a/.github/actions/moksha-render/action.yml b/.github/actions/moksha-render/action.yml new file mode 100644 index 0000000..b8604df --- /dev/null +++ b/.github/actions/moksha-render/action.yml @@ -0,0 +1,77 @@ +# Renders raw captures into finished store images with moksha. +# +# moksha is a checkout, not a dependency: it is a separate tool maintained on +# its own, and pinning a ref here means a change there cannot silently alter +# this app's listing. +# +# It validates every asset against the store it targets and exits non-zero on a +# violation, so the run fails here rather than at upload. The three that +# produce a perfectly valid PNG a store still refuses: an alpha channel, a Play +# aspect ratio over 2:1, and a dimension Apple does not recognise. + +name: Render store assets +description: Frame captures with moksha and place them for upload + +inputs: + job: + description: Path to the moksha job JSON + required: true + captures: + description: Directory holding the raw captures + default: build/screenshots + destination: + description: Where the finished images should end up + required: true + moksha-ref: + description: Git ref of moksha to render with + default: main + +runs: + using: composite + steps: + - uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Check out moksha + shell: bash + run: | + rm -rf "$RUNNER_TEMP/moksha" + git clone --depth 1 --branch "${{ inputs.moksha-ref }}" \ + https://github.com/lohanidamodar/moksha.git "$RUNNER_TEMP/moksha" + cd "$RUNNER_TEMP/moksha" && npm ci --silent + + - name: Render + shell: bash + env: + JOB: ${{ inputs.job }} + CAPTURES: ${{ inputs.captures }} + DESTINATION: ${{ inputs.destination }} + run: | + set -euo pipefail + + count=$(find "$CAPTURES" -name '*.png' 2>/dev/null | wc -l) + echo "captured $count screenshot(s)" + # A green run with an empty listing is indistinguishable from a working + # one. That is the failure this whole harness exists to prevent. + if [ "$count" -eq 0 ]; then + echo "::error::no screenshots were captured" + exit 1 + fi + + out="$RUNNER_TEMP/rendered" + rm -rf "$out" + + cd "$RUNNER_TEMP/moksha" + npm run render -- \ + --job "$GITHUB_WORKSPACE/$JOB" \ + --images "$GITHUB_WORKSPACE/$CAPTURES" \ + --out "$out" + + cd "$GITHUB_WORKSPACE" + # Replaced wholesale rather than merged: a screenshot removed from the + # test should disappear from the listing too. + rm -rf "$DESTINATION" + mkdir -p "$DESTINATION" + cp "$out"/*.png "$DESTINATION/" + ls -la "$DESTINATION" diff --git a/.github/actions/open-screenshot-pr/action.yml b/.github/actions/open-screenshot-pr/action.yml new file mode 100644 index 0000000..379ee79 --- /dev/null +++ b/.github/actions/open-screenshot-pr/action.yml @@ -0,0 +1,58 @@ +# Opens a pull request with the regenerated images. +# +# A PR rather than a push to the branch: store images are a visual change and +# the diff is the review. It also means the workflow does not need write access +# to a protected branch. + +name: Open screenshot PR +description: Commit the rendered assets on a branch and open a pull request + +inputs: + paths: + description: Paths to stage + required: true + title: + description: Pull request title + required: true + branch: + description: Branch name to push + required: true + +runs: + using: composite + steps: + - shell: bash + env: + PATHS: ${{ inputs.paths }} + TITLE: ${{ inputs.title }} + BRANCH: ${{ inputs.branch }} + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + + git add $PATHS + if git diff --staged --quiet; then + echo "images unchanged; nothing to open a PR for" + exit 0 + fi + + git checkout -b "$BRANCH" + git commit -m "$TITLE" + git push --force-with-lease origin "$BRANCH" + + # A PR may already exist if this ran twice for the same branch. + if [ -z "$(gh pr list --head "$BRANCH" --json number --jq '.[0].number')" ]; then + gh pr create \ + --head "$BRANCH" \ + --title "$TITLE" \ + --body "Regenerated by the screenshot workflow. + + Every image was validated against the store's upload rules before this + PR was opened — no alpha channel, Play's 2:1 aspect limit, and Apple's + accepted dimensions. What that cannot check is whether they *look* + right, so open a few before merging." + else + echo "PR for $BRANCH already open; pushed an update to it" + fi diff --git a/.github/workflows/screenshots-android.yml b/.github/workflows/screenshots-android.yml new file mode 100644 index 0000000..8b37dca --- /dev/null +++ b/.github/workflows/screenshots-android.yml @@ -0,0 +1,100 @@ +# Capture, frame and open a PR with the Play store phone screenshots. +# +# Manual only: it rewrites listing images, so it runs when you decide the +# listing needs refreshing. Ported from momo-pasal; see screenshots/README.md. +# +# Ubuntu, not macOS: the emulator action's own guidance is that Ubuntu runners +# with KVM are 2-3x faster and much cheaper. +# +# The capture reads the live feed from Appwrite, so the shots show real +# stories. Analytics is compiled out (ANALYTICS_PROPERTY_ID empty) so these +# runs never land in the app's stats. + +name: Screenshots (Android) + +on: + workflow_dispatch: + inputs: + locale: + description: "Play listing locale" + type: choice + default: en-US + options: + - en-US + +permissions: + contents: write + pull-requests: write + +jobs: + screenshots: + runs-on: ubuntu-latest + timeout-minutes: 60 + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + + - uses: subosito/flutter-action@v2 + with: + flutter-version: "3.47.1" + channel: stable + cache: true + + - name: Install dependencies + run: flutter pub get + + - name: Enable KVM + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' \ + | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + + - name: Capture + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: 34 + arch: x86_64 + profile: pixel_6 + disable-animations: true + script: | + flutter drive \ + --driver=test_driver/integration_test.dart \ + --target=integration_test/screenshot_test.dart \ + --dart-define=ANALYTICS_PROPERTY_ID= \ + -d emulator-5554 + + - name: Build the moksha job + run: | + dart run tool/screenshot_job.dart \ + --asset-type android-phone-screenshot \ + --size-id android-phone \ + --locale ${{ inputs.locale }} \ + --out "$RUNNER_TEMP/job.json" + + - name: Render + uses: ./.github/actions/moksha-render + with: + job: ${{ runner.temp }}/job.json + destination: android/fastlane/metadata/android/${{ inputs.locale }}/images/phoneScreenshots + + - name: Open a PR + uses: ./.github/actions/open-screenshot-pr + with: + paths: android/fastlane/metadata + title: "chore: refresh Play phone screenshots (${{ inputs.locale }})" + branch: screenshots/play-phone-${{ inputs.locale }} + + - uses: actions/upload-artifact@v4 + if: always() + with: + name: play-phone-${{ inputs.locale }} + path: | + build/screenshots/ + android/fastlane/metadata/android/${{ inputs.locale }}/images/phoneScreenshots/ + if-no-files-found: warn diff --git a/.github/workflows/screenshots-ios.yml b/.github/workflows/screenshots-ios.yml new file mode 100644 index 0000000..d0a07f4 --- /dev/null +++ b/.github/workflows/screenshots-ios.yml @@ -0,0 +1,149 @@ +# Capture, frame and open a PR with the App Store screenshots. +# +# macOS, because the iOS simulator has no Linux equivalent. Ported from +# momo-pasal; see screenshots/README.md. +# +# The app is universal (TARGETED_DEVICE_FAMILY = 1,2), so App Store Connect +# wants a 6.9" iPhone set and a 13" iPad set. Each is captured on a matching +# simulator and framed by moksha at a size App Store Connect accepts, into +# ios/fastlane/screenshots/framed//, which is where the fastlane +# upload_screenshots / upload_listing lanes read from. + +name: Screenshots (iOS) + +on: + workflow_dispatch: + inputs: + locale: + description: "App Store locale" + type: choice + default: en-US + options: + - en-US + families: + description: "Which device families to regenerate" + type: choice + default: iphone+ipad + options: + - iphone+ipad + - iphone + +permissions: + contents: write + pull-requests: write + +jobs: + screenshots: + runs-on: macos-latest + timeout-minutes: 90 + + strategy: + max-parallel: 1 + fail-fast: false + matrix: + include: + - family: iphone + simulator: "iPhone 17 Pro Max" + asset_type: iphone-screenshot + size_id: "ios-6.9" + - family: ipad + simulator: "iPad Pro 13-inch (M4)" + asset_type: ipad-screenshot + size_id: "ipad-13" + + steps: + - uses: actions/checkout@v4 + + - name: Skip families that were not asked for + id: want + run: | + if [ "${{ matrix.family }}" = "ipad" ] && \ + [ "${{ inputs.families }}" != "iphone+ipad" ]; then + echo "run=false" >> "$GITHUB_OUTPUT" + else + echo "run=true" >> "$GITHUB_OUTPUT" + fi + + - uses: subosito/flutter-action@v2 + if: steps.want.outputs.run == 'true' + with: + flutter-version: "3.47.1" + channel: stable + cache: true + + - name: Install dependencies + if: steps.want.outputs.run == 'true' + run: flutter pub get + + - name: Boot the simulator + if: steps.want.outputs.run == 'true' + id: sim + run: | + set -euo pipefail + xcrun simctl list devicetypes | grep -i -E 'iphone|ipad' || true + udid=$(xcrun simctl create shots "${{ matrix.simulator }}") + xcrun simctl boot "$udid" + xcrun simctl bootstatus "$udid" -b + echo "udid=$udid" >> "$GITHUB_OUTPUT" + + - name: Capture + if: steps.want.outputs.run == 'true' + run: | + flutter drive \ + --driver=test_driver/integration_test.dart \ + --target=integration_test/screenshot_test.dart \ + --dart-define=ANALYTICS_PROPERTY_ID= \ + -d ${{ steps.sim.outputs.udid }} + + - name: Build the moksha job + if: steps.want.outputs.run == 'true' + run: | + dart run tool/screenshot_job.dart \ + --asset-type ${{ matrix.asset_type }} \ + --size-id ${{ matrix.size_id }} \ + --locale ${{ inputs.locale }} \ + --out "$RUNNER_TEMP/job.json" + + # Each family renders into its own temporary folder first: moksha-render + # replaces its destination wholesale, and both families share the + # locale folder deliver reads. + - name: Render + if: steps.want.outputs.run == 'true' + uses: ./.github/actions/moksha-render + with: + job: ${{ runner.temp }}/job.json + destination: build/rendered/${{ matrix.family }} + + - name: Place for deliver + if: steps.want.outputs.run == 'true' + run: | + set -euo pipefail + dest="ios/fastlane/screenshots/framed/${{ inputs.locale }}" + mkdir -p "$dest" + # Replace only this family's images, prefixed so they never collide. + rm -f "$dest"/${{ matrix.family }}_*.png + for f in build/rendered/${{ matrix.family }}/*.png; do + cp "$f" "$dest/${{ matrix.family }}_$(basename "$f")" + done + ls -la "$dest" + + - name: Open a PR + if: steps.want.outputs.run == 'true' + uses: ./.github/actions/open-screenshot-pr + with: + paths: ios/fastlane/screenshots + title: "chore: refresh App Store ${{ matrix.family }} screenshots (${{ inputs.locale }})" + branch: screenshots/appstore-${{ matrix.family }}-${{ inputs.locale }} + + - name: Shut the simulator down + if: always() && steps.want.outputs.run == 'true' + run: xcrun simctl delete ${{ steps.sim.outputs.udid }} || true + + - uses: actions/upload-artifact@v4 + if: always() && steps.want.outputs.run == 'true' + with: + name: appstore-${{ matrix.family }}-${{ inputs.locale }} + path: | + build/screenshots/ + build/rendered/${{ matrix.family }}/ + if-no-files-found: warn diff --git a/.gitignore b/.gitignore index cc830c6..36bd899 100644 --- a/.gitignore +++ b/.gitignore @@ -62,8 +62,10 @@ app.*.map.json .env *.env -# Local-only documentation (design specs, setup notes) — kept out of the repo. -docs/ +# Local-only documentation (design specs, setup notes) — kept out of the repo, +# except the brand sources the app's look is built from. +docs/* +!docs/BRANDING.md # Fastlane — generated docs, run reports and locally installed gems. **/fastlane/README.md diff --git a/README.md b/README.md index 8072445..eb6c114 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Refetch — Mobile & Desktop App -> Open-source alternative to YC-controlled HN, featuring curated tech news, -> discussions, and community-driven content. +> The front page for builders. Open-source alternative to YC-controlled HN, +> featuring curated tech news, discussions, and community-driven content. The official **Flutter** client for [Refetch](https://refetch.io), bringing the feed, threads, voting, and notifications to Android, iOS, macOS, Windows, and @@ -15,20 +15,36 @@ Linux on top of the same [Appwrite](https://appwrite.io) backend as the web app. - 📰 Curated feed — Top, New, Show, and Mines tabs - 💬 Threaded comments with replies - ⬆️ Voting on posts and comments -- ✍️ Submit links or "Show" posts +- ✍️ Share links, with a note that starts the discussion +- 📤 Share any story's discussion to other apps - 🔐 Email/password accounts - 🔔 Push notifications — replies and an opt-in weekly digest -- 🌗 Material 3 light/dark theming +- 🌗 The refetch.io look, light and dark ## Architecture -A **hybrid client** that reuses the existing Refetch backend: **auth** goes -through the Appwrite Dart SDK (sessions + JWT), while **reads and mutations** go -through the `refetch.io` REST API authenticated with that JWT. **Push** uses FCM -on Android and APNS directly on iOS (no Firebase on iOS) via the -[`push`](https://pub.dev/packages/push) plugin. +A **hybrid client** on the same [Appwrite](https://appwrite.io) project as the +web app: + +- **Reads** (feeds, stories, comments) come straight from Appwrite TablesDB, + which the public can read, with the same queries refetch.io runs. +- **Writes and private data** (votes, comments, submissions, your own votes) + go through the refetch.io app API, `/api/app/*`, authenticated with a + short-lived Appwrite JWT. It runs the website's own server code, so rate + limits, counters and notifications stay in one place. See + [`docs/APP_API.md`](https://github.com/refetch-io/refetch/blob/main/docs/APP_API.md) + in the web repo. +- **Auth** is the Appwrite Dart SDK (email/password sessions). +- **Push** uses FCM on Android and APNS directly on iOS (no Firebase on iOS) + via the [`push`](https://pub.dev/packages/push) plugin. +- **Analytics** is Appwrite Analytics, behind `AnalyticsService` + (`lib/core/analytics/`). Events are anonymous, carry no user id or text the + person wrote, and stop when the switch in Account › Privacy is off. The + property id is `AppConfig.analyticsPropertyId`; build with + `--dart-define=ANALYTICS_PROPERTY_ID=` (empty) to compile analytics out. Built with Flutter, Riverpod, go_router, `http`, and the `appwrite` Dart SDK. +Brand values and where they came from: [`docs/BRANDING.md`](docs/BRANDING.md). ## Getting started @@ -44,10 +60,13 @@ and the topic/provider ids in `lib/core/config/app_config.dart`. Release signing is read from `android/key.properties` (gitignored); see `android/key.properties.example`. -Launcher icons are generated from `assets/icon/` (sources also kept as SVG): +Launcher icons, the splash and the Play listing art are generated from the +logo mark (see [`docs/BRANDING.md`](docs/BRANDING.md#regenerating-the-art)): ```bash +python tool/render_brand_assets.py dart run flutter_launcher_icons +dart run flutter_native_splash:create ``` Releases are cut by the maintainers from **Actions → Android Release / iOS diff --git a/android/app/src/main/res/drawable-hdpi/android12splash.png b/android/app/src/main/res/drawable-hdpi/android12splash.png new file mode 100644 index 0000000..7e599a9 Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/android12splash.png differ diff --git a/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png index 8575d25..65a62d1 100644 Binary files a/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png and b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-hdpi/ic_launcher_monochrome.png b/android/app/src/main/res/drawable-hdpi/ic_launcher_monochrome.png index 8575d25..ce73216 100644 Binary files a/android/app/src/main/res/drawable-hdpi/ic_launcher_monochrome.png and b/android/app/src/main/res/drawable-hdpi/ic_launcher_monochrome.png differ diff --git a/android/app/src/main/res/drawable-hdpi/splash.png b/android/app/src/main/res/drawable-hdpi/splash.png new file mode 100644 index 0000000..7e599a9 Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-mdpi/android12splash.png b/android/app/src/main/res/drawable-mdpi/android12splash.png new file mode 100644 index 0000000..cb6df2b Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/android12splash.png differ diff --git a/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png index fb7a910..8f70ebc 100644 Binary files a/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png and b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-mdpi/ic_launcher_monochrome.png b/android/app/src/main/res/drawable-mdpi/ic_launcher_monochrome.png index fb7a910..99d3a02 100644 Binary files a/android/app/src/main/res/drawable-mdpi/ic_launcher_monochrome.png and b/android/app/src/main/res/drawable-mdpi/ic_launcher_monochrome.png differ diff --git a/android/app/src/main/res/drawable-mdpi/splash.png b/android/app/src/main/res/drawable-mdpi/splash.png new file mode 100644 index 0000000..cb6df2b Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-night-hdpi/android12splash.png b/android/app/src/main/res/drawable-night-hdpi/android12splash.png new file mode 100644 index 0000000..7e599a9 Binary files /dev/null and b/android/app/src/main/res/drawable-night-hdpi/android12splash.png differ diff --git a/android/app/src/main/res/drawable-night-hdpi/splash.png b/android/app/src/main/res/drawable-night-hdpi/splash.png new file mode 100644 index 0000000..7e599a9 Binary files /dev/null and b/android/app/src/main/res/drawable-night-hdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-night-mdpi/android12splash.png b/android/app/src/main/res/drawable-night-mdpi/android12splash.png new file mode 100644 index 0000000..cb6df2b Binary files /dev/null and b/android/app/src/main/res/drawable-night-mdpi/android12splash.png differ diff --git a/android/app/src/main/res/drawable-night-mdpi/splash.png b/android/app/src/main/res/drawable-night-mdpi/splash.png new file mode 100644 index 0000000..cb6df2b Binary files /dev/null and b/android/app/src/main/res/drawable-night-mdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-night-v21/background.png b/android/app/src/main/res/drawable-night-v21/background.png new file mode 100644 index 0000000..4e72ef3 Binary files /dev/null and b/android/app/src/main/res/drawable-night-v21/background.png differ diff --git a/android/app/src/main/res/drawable-night-v21/launch_background.xml b/android/app/src/main/res/drawable-night-v21/launch_background.xml new file mode 100644 index 0000000..3cc4948 --- /dev/null +++ b/android/app/src/main/res/drawable-night-v21/launch_background.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/android/app/src/main/res/drawable-night-xhdpi/android12splash.png b/android/app/src/main/res/drawable-night-xhdpi/android12splash.png new file mode 100644 index 0000000..f9a27a1 Binary files /dev/null and b/android/app/src/main/res/drawable-night-xhdpi/android12splash.png differ diff --git a/android/app/src/main/res/drawable-night-xhdpi/splash.png b/android/app/src/main/res/drawable-night-xhdpi/splash.png new file mode 100644 index 0000000..f9a27a1 Binary files /dev/null and b/android/app/src/main/res/drawable-night-xhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png b/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png new file mode 100644 index 0000000..f2f5023 Binary files /dev/null and b/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png differ diff --git a/android/app/src/main/res/drawable-night-xxhdpi/splash.png b/android/app/src/main/res/drawable-night-xxhdpi/splash.png new file mode 100644 index 0000000..f2f5023 Binary files /dev/null and b/android/app/src/main/res/drawable-night-xxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png b/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png new file mode 100644 index 0000000..74ae6e4 Binary files /dev/null and b/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png differ diff --git a/android/app/src/main/res/drawable-night-xxxhdpi/splash.png b/android/app/src/main/res/drawable-night-xxxhdpi/splash.png new file mode 100644 index 0000000..74ae6e4 Binary files /dev/null and b/android/app/src/main/res/drawable-night-xxxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-night/background.png b/android/app/src/main/res/drawable-night/background.png new file mode 100644 index 0000000..4e72ef3 Binary files /dev/null and b/android/app/src/main/res/drawable-night/background.png differ diff --git a/android/app/src/main/res/drawable-night/launch_background.xml b/android/app/src/main/res/drawable-night/launch_background.xml new file mode 100644 index 0000000..3cc4948 --- /dev/null +++ b/android/app/src/main/res/drawable-night/launch_background.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/android/app/src/main/res/drawable-v21/background.png b/android/app/src/main/res/drawable-v21/background.png new file mode 100644 index 0000000..22d865e Binary files /dev/null and b/android/app/src/main/res/drawable-v21/background.png differ diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml index f74085f..3cc4948 100644 --- a/android/app/src/main/res/drawable-v21/launch_background.xml +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -1,12 +1,9 @@ - - - - - + + + + + + diff --git a/android/app/src/main/res/drawable-xhdpi/android12splash.png b/android/app/src/main/res/drawable-xhdpi/android12splash.png new file mode 100644 index 0000000..f9a27a1 Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/android12splash.png differ diff --git a/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png index b2d30af..631af26 100644 Binary files a/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png and b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xhdpi/ic_launcher_monochrome.png b/android/app/src/main/res/drawable-xhdpi/ic_launcher_monochrome.png index b2d30af..a00d020 100644 Binary files a/android/app/src/main/res/drawable-xhdpi/ic_launcher_monochrome.png and b/android/app/src/main/res/drawable-xhdpi/ic_launcher_monochrome.png differ diff --git a/android/app/src/main/res/drawable-xhdpi/splash.png b/android/app/src/main/res/drawable-xhdpi/splash.png new file mode 100644 index 0000000..f9a27a1 Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/android12splash.png b/android/app/src/main/res/drawable-xxhdpi/android12splash.png new file mode 100644 index 0000000..f2f5023 Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/android12splash.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png index 3976768..cfe95bf 100644 Binary files a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png and b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_monochrome.png b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_monochrome.png index 3976768..47576d9 100644 Binary files a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_monochrome.png and b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_monochrome.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/splash.png b/android/app/src/main/res/drawable-xxhdpi/splash.png new file mode 100644 index 0000000..f2f5023 Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/android12splash.png b/android/app/src/main/res/drawable-xxxhdpi/android12splash.png new file mode 100644 index 0000000..74ae6e4 Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/android12splash.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png index 12c3555..e1a7310 100644 Binary files a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png and b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_monochrome.png b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_monochrome.png index 12c3555..b8de828 100644 Binary files a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_monochrome.png and b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_monochrome.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/splash.png b/android/app/src/main/res/drawable-xxxhdpi/splash.png new file mode 100644 index 0000000..74ae6e4 Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable/background.png b/android/app/src/main/res/drawable/background.png new file mode 100644 index 0000000..22d865e Binary files /dev/null and b/android/app/src/main/res/drawable/background.png differ diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml index 304732f..3cc4948 100644 --- a/android/app/src/main/res/drawable/launch_background.xml +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -1,12 +1,9 @@ - - - - - + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png index 7da9a8d..889011e 100644 Binary files a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png index e103a4b..efaa1a3 100644 Binary files a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png index 225341f..bb1f1cf 100644 Binary files a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png index 2e4ef3e..6576dc2 100644 Binary files a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png index ddbadd3..1797f61 100644 Binary files a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night-v31/styles.xml b/android/app/src/main/res/values-night-v31/styles.xml new file mode 100644 index 0000000..591c4f3 --- /dev/null +++ b/android/app/src/main/res/values-night-v31/styles.xml @@ -0,0 +1,21 @@ + + + + + + + diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml index 06952be..dbc9ea9 100644 --- a/android/app/src/main/res/values-night/styles.xml +++ b/android/app/src/main/res/values-night/styles.xml @@ -5,6 +5,10 @@ @drawable/launch_background + false + false + false + shortEdges + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml index 9303e0b..c5d5899 100644 --- a/android/app/src/main/res/values/colors.xml +++ b/android/app/src/main/res/values/colors.xml @@ -1,4 +1,4 @@ - #5A00FF + #FFFFFF \ No newline at end of file diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml index cb1ef88..0d1fa8f 100644 --- a/android/app/src/main/res/values/styles.xml +++ b/android/app/src/main/res/values/styles.xml @@ -5,6 +5,10 @@ @drawable/launch_background + false + false + false + shortEdges + NSPrivacyCollectedDataTypes - + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeProductInteraction + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAnalytics + + + NSPrivacyAccessedAPITypes diff --git a/ios/fastlane/metadata/en-US/description.txt b/ios/fastlane/metadata/en-US/description.txt index 26f8e94..4a0a071 100644 --- a/ios/fastlane/metadata/en-US/description.txt +++ b/ios/fastlane/metadata/en-US/description.txt @@ -1,15 +1,16 @@ -Refetch is a community-driven, open-source alternative to Hacker News — your daily drop of curated tech news, with signal over noise. +Refetch is the front page for builders: an open-source alternative to YC-controlled Hacker News, with curated tech news and the discussions around it. -Discover the best of technology: AI, startups, open source, security, science, and programming, surfaced from 20+ trusted sources and ranked by a transparent, community-driven algorithm. +Stories come from trusted sources across AI, startups, open source, security, science and programming, and are ranked by a transparent algorithm you can read on GitHub. The community votes, comments and shares the rest. FEATURES -• Curated feed — browse Top, New, and Show stories, plus your own submissions -• Discussions — threaded comments with replies -• Voting — upvote and downvote stories and comments -• Submit — share a link or a "Show" post with the community -• Notifications — replies to you and an opt-in weekly digest of top stories -• Fast and clean, built for both mobile and desktop - -Refetch is fully open source and privacy-focused, powered by Appwrite. Free from YC control — open, transparent, and community-run. +• Top, New and Show: today's front page, the latest stories, and what people are building +• Discussions: threaded comments and replies on every story +• Voting: upvote and downvote stories and comments +• Share a story: post a link with a note that starts the conversation +• Share anywhere: send a story's discussion to friends from any app +• Notifications: replies to you, and an optional weekly digest of top stories +• Light and dark themes, in the Refetch purple + +Refetch is free, open source and built on Appwrite. Anonymous usage analytics help us improve the app, and you can turn them off any time in Account. Learn more at https://refetch.io diff --git a/ios/fastlane/metadata/en-US/keywords.txt b/ios/fastlane/metadata/en-US/keywords.txt index 801753e..fd16bd1 100644 --- a/ios/fastlane/metadata/en-US/keywords.txt +++ b/ios/fastlane/metadata/en-US/keywords.txt @@ -1 +1 @@ -tech news,hacker news,programming,developer,startups,open source,security,HN,community +tech news,hacker news,programming,developer,startups,open source,builders,AI,HN diff --git a/ios/fastlane/metadata/en-US/name.txt b/ios/fastlane/metadata/en-US/name.txt index 6d351d4..68f7e61 100644 --- a/ios/fastlane/metadata/en-US/name.txt +++ b/ios/fastlane/metadata/en-US/name.txt @@ -1 +1 @@ -Refetch - Tech News +Refetch: Tech News diff --git a/ios/fastlane/metadata/en-US/privacy_url.txt b/ios/fastlane/metadata/en-US/privacy_url.txt index 6ca2756..6f5cf83 100644 --- a/ios/fastlane/metadata/en-US/privacy_url.txt +++ b/ios/fastlane/metadata/en-US/privacy_url.txt @@ -1 +1 @@ -https://refetch.io/privacy +https://appwrite.io/privacy diff --git a/ios/fastlane/metadata/en-US/promotional_text.txt b/ios/fastlane/metadata/en-US/promotional_text.txt index 6d35204..c90d3d4 100644 --- a/ios/fastlane/metadata/en-US/promotional_text.txt +++ b/ios/fastlane/metadata/en-US/promotional_text.txt @@ -1 +1 @@ -Refetch is a community-driven, open-source alternative to Hacker News — curated tech stories, discussions, and voting, with signal over noise. +The front page for builders. Curated tech news, ranked in the open, with the discussions around it. Now in the new Refetch look. diff --git a/ios/fastlane/metadata/en-US/release_notes.txt b/ios/fastlane/metadata/en-US/release_notes.txt index 81fe995..0b6d19c 100644 --- a/ios/fastlane/metadata/en-US/release_notes.txt +++ b/ios/fastlane/metadata/en-US/release_notes.txt @@ -1 +1,4 @@ -Initial release of Refetch: a curated tech-news feed with discussions, voting, submissions, and push notifications — for mobile and desktop. +A fresh look to match refetch.io: the new logo, colours and type, in light and dark. +Stories load from the new Refetch, so the feed, threads, votes and comments work again. +Share any story from the feed or its thread. +Anonymous usage analytics, which you can turn off in Account. diff --git a/ios/fastlane/metadata/en-US/subtitle.txt b/ios/fastlane/metadata/en-US/subtitle.txt index 1ec6778..5bdbcb5 100644 --- a/ios/fastlane/metadata/en-US/subtitle.txt +++ b/ios/fastlane/metadata/en-US/subtitle.txt @@ -1 +1 @@ -Curated tech news, no noise +The front page for builders diff --git a/lib/app.dart b/lib/app.dart index b57e109..5858fac 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -1,13 +1,14 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'core/analytics/analytics_providers.dart'; import 'core/push/push_providers.dart'; import 'core/router/app_router.dart'; import 'core/theme/app_theme.dart'; import 'features/auth/presentation/auth_controller.dart'; -/// Root widget: wires the router and themes into [MaterialApp.router], and -/// drives push-notification setup off authentication state. +/// Root widget: wires the router and themes into [MaterialApp.router], starts +/// analytics, and drives push-notification setup off authentication state. class RefetchApp extends ConsumerStatefulWidget { const RefetchApp({super.key}); @@ -19,6 +20,10 @@ class _RefetchAppState extends ConsumerState { @override void initState() { super.initState(); + // Analytics: start the lifecycle events, then apply the saved choice + // (nothing is sent until it has been read). + ref.read(analyticsProvider).start(); + ref.read(analyticsConsentProvider); // Initialize push handling after first frame so the router exists. WidgetsBinding.instance.addPostFrameCallback((_) { final router = ref.read(routerProvider); diff --git a/lib/core/analytics/analytics_providers.dart b/lib/core/analytics/analytics_providers.dart new file mode 100644 index 0000000..89af3ed --- /dev/null +++ b/lib/core/analytics/analytics_providers.dart @@ -0,0 +1,107 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../appwrite/appwrite_providers.dart'; +import '../config/app_config.dart'; +import 'analytics_service.dart'; +import 'appwrite_analytics.dart'; + +/// Remembers whether the user allows anonymous usage analytics. On by +/// default, matching refetch.io; switched off in Account. +class AnalyticsConsentStore { + static const _key = 'analytics.enabled'; + + Future read() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getBool(_key) ?? true; + } + + Future write(bool enabled) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_key, enabled); + } +} + +final analyticsConsentStoreProvider = Provider( + (ref) => AnalyticsConsentStore(), +); + +/// The analytics backend before consent is applied: Appwrite when a property +/// is configured, otherwise nothing. Override this to swap backends. +final analyticsBackendProvider = Provider((ref) { + if (AppConfig.analyticsPropertyId.isEmpty) return const NoopAnalytics(); + return AppwriteAnalyticsService.forClient( + ref.watch(appwriteClientProvider), + AppConfig.analyticsPropertyId, + ); +}); + +/// The service the app uses. Holds events until the saved choice is read +/// (see [AnalyticsConsentController]), so nothing leaves before we know. +final analyticsProvider = Provider((ref) { + final analytics = ConsentedAnalytics( + ref.watch(analyticsBackendProvider), + enabled: null, + ); + ref.onDispose(analytics.stop); + return analytics; +}); + +/// The user's analytics choice, applied to [analyticsProvider]. +class AnalyticsConsentController extends AsyncNotifier { + @override + Future build() async { + final enabled = await ref.read(analyticsConsentStoreProvider).read(); + ref.read(analyticsProvider).enabled = enabled; + return enabled; + } + + Future setEnabled(bool enabled) async { + final analytics = ref.read(analyticsProvider); + // Record the change only while allowed: opting out sends nothing, opting + // in is recorded once it is on. + if (!enabled) analytics.enabled = false; + await ref.read(analyticsConsentStoreProvider).write(enabled); + analytics.enabled = enabled; + if (enabled) { + analytics.track( + AnalyticsEvents.settingChanged, + props: {'setting': 'analytics', 'value': true}, + ); + } + state = AsyncData(enabled); + } +} + +final analyticsConsentProvider = + AsyncNotifierProvider( + AnalyticsConsentController.new, + ); + +/// Sends a screen view whenever a named route becomes the visible one. +/// go_router names each page after its route's `name` (or its path pattern), +/// so ids never reach analytics. +class AnalyticsRouteObserver extends NavigatorObserver { + AnalyticsRouteObserver(this._analytics); + + final AnalyticsService _analytics; + + void _view(Route? route) { + final name = route?.settings.name; + if (route is! PageRoute || name == null || name.isEmpty) return; + _analytics.screenView(name); + } + + @override + void didPush(Route route, Route? previousRoute) => + _view(route); + + @override + void didReplace({Route? newRoute, Route? oldRoute}) => + _view(newRoute); + + @override + void didPop(Route route, Route? previousRoute) => + _view(previousRoute); +} diff --git a/lib/core/analytics/analytics_service.dart b/lib/core/analytics/analytics_service.dart new file mode 100644 index 0000000..fa15f9a --- /dev/null +++ b/lib/core/analytics/analytics_service.dart @@ -0,0 +1,141 @@ +/// The app's analytics, behind an interface so the backend can be swapped or +/// switched off. The app only ever talks to an [AnalyticsService]; today the +/// implementation is Appwrite Analytics ([AppwriteAnalyticsService]), wrapped +/// in [ConsentedAnalytics] so the user's choice in Account always wins. +/// +/// Privacy rules every implementation keeps: +/// * no user id, email, name or free text (titles, comments) in events; +/// * ids of public stories are fine — they are public anyway; +/// * nothing is sent while the user has analytics turned off. +abstract interface class AnalyticsService { + /// Begin automatic events (app foregrounded/backgrounded). + void start(); + + /// Stop automatic events. Explicit calls after this are dropped too. + void stop(); + + /// A screen came into view. [screen] is a route name such as `thread`. + void screenView(String screen, {Map? props}); + + /// A custom event. Names are `snake_case` (see [AnalyticsEvents]). + void track(String name, {Map? props}); +} + +/// Event names, kept stable so their history stays comparable. +abstract final class AnalyticsEvents { + static const feedLoaded = 'feed_loaded'; + static const feedLoadFailed = 'feed_load_failed'; + static const threadLoadFailed = 'thread_load_failed'; + static const storyOpened = 'story_opened'; + static const articleOpened = 'article_opened'; + static const storyShared = 'story_shared'; + static const voteCast = 'vote_cast'; + static const commentPosted = 'comment_posted'; + static const storySubmitted = 'story_submitted'; + static const signedIn = 'signed_in'; + static const signedUp = 'signed_up'; + static const signInFailed = 'sign_in_failed'; + static const signedOut = 'signed_out'; + static const settingChanged = 'setting_changed'; +} + +/// Does nothing. Used when no analytics property is configured, and in tests. +class NoopAnalytics implements AnalyticsService { + const NoopAnalytics(); + + @override + void start() {} + + @override + void stop() {} + + @override + void screenView(String screen, {Map? props}) {} + + @override + void track(String name, {Map? props}) {} +} + +/// Forwards to [delegate] only while the user allows analytics. +/// +/// Until the saved choice is known ([enabled] is null) events are held, up to +/// [maxPending], so the first screen view isn't lost at startup; they are sent +/// if the choice turns out to be "on" and dropped if it is "off". Turning it +/// off stops the automatic events at once and drops everything after. +class ConsentedAnalytics implements AnalyticsService { + ConsentedAnalytics(this.delegate, {this._enabled = true}); + + static const maxPending = 20; + + final AnalyticsService delegate; + bool? _enabled; + bool _started = false; + final List _pending = []; + + /// Null while the saved choice hasn't been read yet. + bool? get enabled => _enabled; + + set enabled(bool? value) { + if (value == _enabled) return; + final wasOn = _enabled == true; + _enabled = value; + if (value == true) { + if (_started && !wasOn) delegate.start(); + for (final send in _pending) { + send(); + } + } else if (value == false && _started && wasOn) { + delegate.stop(); + } + if (value != null) _pending.clear(); + } + + void _send(void Function() send) { + switch (_enabled) { + case true: + send(); + case null: + if (_pending.length < maxPending) _pending.add(send); + case false: + break; + } + } + + @override + void start() { + _started = true; + if (_enabled == true) delegate.start(); + } + + @override + void stop() { + _started = false; + delegate.stop(); + } + + @override + void screenView(String screen, {Map? props}) => + _send(() => delegate.screenView(screen, props: props)); + + @override + void track(String name, {Map? props}) => + _send(() => delegate.track(name, props: props)); +} + +/// Props as the endpoint wants them: non-null values only, at most +/// [maxPairs] pairs (the API takes 32 flattened entries; one pair is left +/// for the `screen` key the screen-view helper adds). +Map cleanProps( + Map? props, { + int maxPairs = 15, +}) { + if (props == null) return const {}; + final out = {}; + for (final entry in props.entries) { + final value = entry.value; + if (value == null) continue; + if (out.length >= maxPairs) break; + out[entry.key] = value; + } + return out; +} diff --git a/lib/core/analytics/appwrite_analytics.dart b/lib/core/analytics/appwrite_analytics.dart new file mode 100644 index 0000000..6610485 --- /dev/null +++ b/lib/core/analytics/appwrite_analytics.dart @@ -0,0 +1,96 @@ +import 'package:appwrite/appwrite.dart'; +import 'package:flutter/foundation.dart'; + +import 'analytics_service.dart'; + +/// [AnalyticsService] on Appwrite Analytics, through the SDK's [Tracking] +/// helper: it sends `createEvent` calls, flattens props, reports the viewport +/// width, adds `app_backgrounded`/`app_foregrounded` with engagement time, and +/// swallows network errors so analytics never breaks the app. +/// +/// Events are anonymous: no `userId` is ever passed (the endpoint only takes +/// one from an API key), and the session cookie the client carries is not used +/// to attribute events. +class AppwriteAnalyticsService implements AnalyticsService { + AppwriteAnalyticsService(this._tracking); + + /// Builds the tracker for [propertyId] on [client]. + factory AppwriteAnalyticsService.forClient( + Client client, + String propertyId, + ) => AppwriteAnalyticsService( + Tracking( + kDebugMode ? DebugLoggingAnalytics(client) : Analytics(client), + propertyId, + ), + ); + + final Tracking _tracking; + + @override + void start() => _tracking.enableAutoLifecycleEvents(); + + @override + void stop() => _tracking.disableAutoLifecycleEvents(); + + @override + void screenView(String screen, {Map? props}) { + // The screen name doubles as the event URL path (`app://android/thread`). + _tracking.screenView(screen, props: cleanProps(props)); + } + + @override + void track(String name, {Map? props}) { + _tracking.event(name, props: cleanProps(props, maxPairs: 16)); + } +} + +/// Debug builds only: logs each event and what the server answered, since +/// [Tracking] deliberately swallows failures. `flutter logs` then shows +/// `[analytics] screen_view -> sent` or the error (e.g. a 404 for a wrong +/// property id, a 403 for an origin allowlist). +class DebugLoggingAnalytics extends Analytics { + DebugLoggingAnalytics(super.client); + + @override + Future createEvent({ + required String propertyId, + required String name, + required String url, + String? domain, + String? referrer, + int? screenWidth, + String? sessionHash, + int? scrollDepth, + int? engagementTime, + List? props, + String? userId, + String? ip, + String? userAgent, + bool? interactive, + }) async { + try { + final result = await super.createEvent( + propertyId: propertyId, + name: name, + url: url, + domain: domain, + referrer: referrer, + screenWidth: screenWidth, + sessionHash: sessionHash, + scrollDepth: scrollDepth, + engagementTime: engagementTime, + props: props, + userId: userId, + ip: ip, + userAgent: userAgent, + interactive: interactive, + ); + debugPrint('[analytics] $name $url ${props ?? const []} -> sent'); + return result; + } catch (error) { + debugPrint('[analytics] $name $url -> FAILED: $error'); + rethrow; + } + } +} diff --git a/lib/core/appwrite/appwrite_providers.dart b/lib/core/appwrite/appwrite_providers.dart index 3b4de6a..8b4236c 100644 --- a/lib/core/appwrite/appwrite_providers.dart +++ b/lib/core/appwrite/appwrite_providers.dart @@ -14,3 +14,8 @@ final appwriteClientProvider = Provider((ref) { final accountProvider = Provider((ref) { return Account(ref.watch(appwriteClientProvider)); }); + +/// Appwrite [TablesDB] service — public reads of posts and comments. +final tablesDbProvider = Provider((ref) { + return TablesDB(ref.watch(appwriteClientProvider)); +}); diff --git a/lib/core/config/app_config.dart b/lib/core/config/app_config.dart index 44c727c..4201a38 100644 --- a/lib/core/config/app_config.dart +++ b/lib/core/config/app_config.dart @@ -1,8 +1,10 @@ /// Static configuration for the Refetch app. /// /// The app talks to two backends: -/// * Appwrite (auth only) via the Dart SDK. -/// * The existing refetch.io REST API for reads and mutations. +/// * Appwrite via the Dart SDK: auth, push, analytics, and public reads +/// (posts, comments) straight from TablesDB. +/// * The refetch.io app API (`/api/app/*`, documented in the web repo's +/// `docs/APP_API.md`) for writes and the signed-in person's votes. class AppConfig { AppConfig._(); @@ -12,14 +14,27 @@ class AppConfig { /// Refetch Appwrite project id. static const String appwriteProjectId = '63ef1792594ff4f50de2'; - /// Base URL of the refetch.io Next.js API. + /// Public site; the base URL of the app API and of shared thread links. static const String apiBaseUrl = 'https://refetch.io'; + /// TablesDB ids, as in the web repo's `env.example`. + static const String databaseId = '688f787e002c78bd299f'; + static const String postsTableId = '688f78a20022f61836ff'; + static const String commentsTableId = '68993e6c003af0fe657f'; + + /// Appwrite Analytics property for the apps (separate from the website's). + /// Override at build time with `--dart-define=ANALYTICS_PROPERTY_ID=...`; + /// an empty value turns analytics off entirely. + static const String analyticsPropertyId = String.fromEnvironment( + 'ANALYTICS_PROPERTY_ID', + defaultValue: '6aeff5fb00101bdbf718', + ); + /// Page size used for feed pagination. static const int feedPageSize = 25; - /// Brand colour (refetch purple). - static const int brandColor = 0xFF7C3AED; + /// Brand colour (refetch purple, `--brand` on refetch.io; see docs/BRANDING.md). + static const int brandColor = 0xFF4E1CB3; /// Appwrite Messaging topic ids the device subscribes its push target to /// (client-side, via `Messaging.createSubscriber`). Empty ids are skipped. diff --git a/lib/core/format/time_ago.dart b/lib/core/format/time_ago.dart new file mode 100644 index 0000000..3a3d620 --- /dev/null +++ b/lib/core/format/time_ago.dart @@ -0,0 +1,27 @@ +/// Short relative time, the way refetch.io writes it ("just now", "5m ago", +/// "3h ago", "2d ago"), falling back to a date after a month. +String timeAgo(DateTime time, {DateTime? now}) { + final current = now ?? DateTime.now(); + final diff = current.difference(time); + if (diff.isNegative || diff.inSeconds < 60) return 'just now'; + if (diff.inMinutes < 60) return '${diff.inMinutes}m ago'; + if (diff.inHours < 24) return '${diff.inHours}h ago'; + if (diff.inDays < 30) return '${diff.inDays}d ago'; + const months = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', + ]; + final local = time.toLocal(); + final sameYear = local.year == current.toLocal().year; + return '${months[local.month - 1]} ${local.day}${sameYear ? '' : ', ${local.year}'}'; +} diff --git a/lib/core/network/api_client.dart b/lib/core/network/api_client.dart index 0f16a91..31f0b03 100644 --- a/lib/core/network/api_client.dart +++ b/lib/core/network/api_client.dart @@ -7,10 +7,12 @@ import '../auth/jwt_service.dart'; import '../config/app_config.dart'; import 'api_exception.dart'; -/// Thin wrapper around [http.Client] for the refetch.io REST API. +/// Thin wrapper around [http.Client] for the refetch.io app API (`/api/app/*`, +/// see the web repo's `docs/APP_API.md`). /// -/// Handles JSON encoding/decoding, error mapping to [ApiException], and -/// injecting the cached Appwrite JWT as a Bearer token on authenticated calls. +/// Handles JSON encoding/decoding, unwrapping the `{ "data": … }` envelope, +/// error mapping to [ApiException], and injecting the cached Appwrite JWT as a +/// Bearer token on authenticated calls. class ApiClient { ApiClient({ required this.baseUrl, @@ -28,7 +30,10 @@ class ApiClient { bool auth = false, }) async { final uri = Uri.parse('$baseUrl$path').replace(queryParameters: query); - return _send(auth, () async => _http.get(uri, headers: await _headers(auth))); + return _send( + auth, + () async => _http.get(uri, headers: await _headers(auth)), + ); } Future post(String path, {Object? body, bool auth = true}) async { @@ -99,7 +104,11 @@ class ApiClient { } final ok = response.statusCode >= 200 && response.statusCode < 300; - if (ok) return decoded; + if (ok) { + return decoded is Map && decoded.containsKey('data') + ? decoded['data'] + : decoded; + } final message = decoded is Map ? (decoded['message'] ?? decoded['error'] ?? 'Request failed') diff --git a/lib/core/network/error_message.dart b/lib/core/network/error_message.dart index 0f21e7c..7852b63 100644 --- a/lib/core/network/error_message.dart +++ b/lib/core/network/error_message.dart @@ -4,8 +4,8 @@ import 'api_exception.dart'; /// Extracts a human-readable message from any error raised by the app's two /// backends: -/// * [ApiException] — from the refetch.io REST client. -/// * [AppwriteException] — from the Appwrite SDK (auth, push targets). +/// * [ApiException] — from the refetch.io app API client (writes). +/// * [AppwriteException] — from the Appwrite SDK (reads, auth, push targets). /// /// Falls back to [fallback] only when no useful message is available, so the /// user sees the real reason (e.g. "Invalid credentials") instead of a generic @@ -27,12 +27,47 @@ String messageForError( return error.message.trim().isNotEmpty ? error.message : fallback; } if (error is AppwriteException) { + // The SDK wraps transport failures (no network, DNS, TLS) in an + // exception with no status code and the raw socket text as its message. + if (_isAppwriteTransport(error)) { + return "Can't reach Refetch. Check your connection and try again."; + } + if ((error.code ?? 0) >= 500) { + return 'Refetch is having trouble right now. Please try again shortly.'; + } final message = error.message?.trim(); if (message != null && message.isNotEmpty) return message; } return fallback; } +/// The SDK rethrows transport failures as `AppwriteException(e.toString())`: +/// no status code, and the socket/HTTP-client error text as the message. +bool _isAppwriteTransport(AppwriteException error) { + if (error.code != null && error.code != 0) return false; + final message = error.message ?? ''; + return RegExp( + 'SocketException|ClientException|HandshakeException|TimeoutException|' + 'Failed host lookup|Connection (refused|reset|closed)|Network is unreachable', + ).hasMatch(message); +} + +/// A coarse category for analytics: `network`, `server`, `client` (4xx) or +/// `unknown`. Never includes the message, which may carry user input. +String errorKind(Object? error) { + if (error is ApiException) { + if (error.isNetworkFailure) return 'network'; + if (error.isServerError) return 'server'; + return 'client'; + } + if (error is AppwriteException) { + if (_isAppwriteTransport(error)) return 'network'; + if ((error.code ?? 0) >= 500) return 'server'; + return 'client'; + } + return 'unknown'; +} + /// A short technical detail to show alongside the friendly message, so a user /// reporting a problem can say something more useful than "it didn't work". /// Returns null when there is nothing worth showing. @@ -44,8 +79,13 @@ String? detailForError(Object? error) { return 'HTTP ${error.statusCode}'; } if (error is AppwriteException) { - final code = error.code; - return code == null ? null : 'Appwrite $code'; + if (_isAppwriteTransport(error)) { + return _transportDetail(error.message ?? ''); + } + final type = error.type; + return type == null || type.isEmpty + ? 'Appwrite ${error.code}' + : 'Appwrite ${error.code} $type'; } return null; } diff --git a/lib/core/router/app_router.dart b/lib/core/router/app_router.dart index 3d13866..17b87ed 100644 --- a/lib/core/router/app_router.dart +++ b/lib/core/router/app_router.dart @@ -1,6 +1,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; +import '../analytics/analytics_providers.dart'; + import '../../features/auth/presentation/sign_in_screen.dart'; import '../../features/auth/presentation/sign_up_screen.dart'; import '../../features/feed/presentation/feed_screen.dart'; @@ -13,27 +15,38 @@ import '../../features/thread/presentation/thread_screen.dart'; final routerProvider = Provider((ref) { return GoRouter( initialLocation: '/', + // Route names double as analytics screen names; ids never reach analytics. + observers: [AnalyticsRouteObserver(ref.read(analyticsProvider))], routes: [ - GoRoute(path: '/', builder: (context, state) => const FeedScreen()), + GoRoute( + path: '/', + name: 'feed', + builder: (context, state) => const FeedScreen(), + ), GoRoute( path: '/thread/:id', + name: 'thread', builder: (context, state) => ThreadScreen(postId: state.pathParameters['id']!), ), GoRoute( path: '/signin', + name: 'sign_in', builder: (context, state) => const SignInScreen(), ), GoRoute( path: '/signup', + name: 'sign_up', builder: (context, state) => const SignUpScreen(), ), GoRoute( path: '/submit', + name: 'submit', builder: (context, state) => const SubmitScreen(), ), GoRoute( path: '/profile', + name: 'account', builder: (context, state) => const ProfileScreen(), ), ], diff --git a/lib/core/share/share_story.dart b/lib/core/share/share_story.dart new file mode 100644 index 0000000..db88c3c --- /dev/null +++ b/lib/core/share/share_story.dart @@ -0,0 +1,41 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:share_plus/share_plus.dart'; + +import '../../features/feed/domain/post.dart'; +import '../analytics/analytics_providers.dart'; +import '../analytics/analytics_service.dart'; + +/// Opens the system share sheet with the story's refetch.io thread link, +/// and records whether the person went through with it. +Future shareStory( + BuildContext context, + WidgetRef ref, + Post post, { + required String source, +}) async { + // iPad and macOS anchor the sheet to the button that opened it. + final box = context.findRenderObject() as RenderBox?; + final origin = box == null || !box.hasSize + ? null + : box.localToGlobal(Offset.zero) & box.size; + final analytics = ref.read(analyticsProvider); + + final result = await SharePlus.instance.share( + ShareParams( + uri: Uri.parse(post.threadUrl), + subject: post.title, + title: post.title, + sharePositionOrigin: origin, + ), + ); + analytics.track( + AnalyticsEvents.storyShared, + props: { + 'post_id': post.id, + 'source': source, + 'method': 'native', + 'result': result.status.name, + }, + ); +} diff --git a/lib/core/theme/app_theme.dart b/lib/core/theme/app_theme.dart index 9b24929..08bbbe0 100644 --- a/lib/core/theme/app_theme.dart +++ b/lib/core/theme/app_theme.dart @@ -1,39 +1,344 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import '../config/app_config.dart'; +/// Refetch's colour tokens, copied from refetch.io (`src/styles/app.css`, +/// documented in the web repo's DESIGN.md). Where each value came from is +/// recorded in docs/BRANDING.md. +@immutable +class RefetchColors extends ThemeExtension { + const RefetchColors({ + required this.brand, + required this.brandText, + required this.brandTint, + required this.logoWordmark, + required this.bg, + required this.surface, + required this.surfaceSecondary, + required this.label, + required this.labelSecondary, + required this.labelTertiary, + required this.labelQuaternary, + required this.separator, + required this.fill, + required this.up, + required this.upTint, + required this.down, + required this.downTint, + }); -/// Light and dark Material 3 themes seeded from the refetch purple brand color. + /// The logo mark, primary buttons, selection. Same in both themes. + final Color brand; + + /// Links and accents on surfaces; lifted in dark mode for contrast. + final Color brandText; + final Color brandTint; + final Color logoWordmark; + final Color bg; + final Color surface; + final Color surfaceSecondary; + final Color label; + final Color labelSecondary; + final Color labelTertiary; + final Color labelQuaternary; + final Color separator; + final Color fill; + final Color up; + final Color upTint; + final Color down; + final Color downTint; + + static const light = RefetchColors( + brand: Color(0xFF4E1CB3), + brandText: Color(0xFF4E1CB3), + brandTint: Color(0xFFF3EEFF), + logoWordmark: Color(0xFF1D1D1F), + bg: Color(0xFFF5F5F7), + surface: Color(0xFFFFFFFF), + surfaceSecondary: Color(0xFFF5F5F7), + label: Color(0xFF1D1D1F), + labelSecondary: Color(0xFF6E6E73), + labelTertiary: Color(0xFF86868B), + labelQuaternary: Color(0xFFAEAEB2), + separator: Color(0x14000000), + fill: Color(0x1F767680), + up: Color(0xFF16A34A), + upTint: Color(0xFFE9F8EF), + down: Color(0xFFDC2626), + downTint: Color(0xFFFDEDED), + ); + + static const dark = RefetchColors( + brand: Color(0xFF4E1CB3), + brandText: Color(0xFF9B7CF6), + brandTint: Color(0x524E1CB3), + logoWordmark: Color(0xFFFFFFFF), + bg: Color(0xFF0E0D13), + surface: Color(0xFF17161E), + surfaceSecondary: Color(0xFF1F1E28), + label: Color(0xFFF3F2F7), + labelSecondary: Color(0xFFA9A7B5), + labelTertiary: Color(0xFF7A788A), + labelQuaternary: Color(0xFF4F4D5E), + separator: Color(0x12FFFFFF), + fill: Color(0x12FFFFFF), + up: Color(0xFF30D158), + upTint: Color(0x2430D158), + down: Color(0xFFFF453A), + downTint: Color(0x24FF453A), + ); + + @override + RefetchColors copyWith() => this; + + @override + RefetchColors lerp(RefetchColors? other, double t) { + if (other == null) return this; + Color c(Color a, Color b) => Color.lerp(a, b, t)!; + return RefetchColors( + brand: c(brand, other.brand), + brandText: c(brandText, other.brandText), + brandTint: c(brandTint, other.brandTint), + logoWordmark: c(logoWordmark, other.logoWordmark), + bg: c(bg, other.bg), + surface: c(surface, other.surface), + surfaceSecondary: c(surfaceSecondary, other.surfaceSecondary), + label: c(label, other.label), + labelSecondary: c(labelSecondary, other.labelSecondary), + labelTertiary: c(labelTertiary, other.labelTertiary), + labelQuaternary: c(labelQuaternary, other.labelQuaternary), + separator: c(separator, other.separator), + fill: c(fill, other.fill), + up: c(up, other.up), + upTint: c(upTint, other.upTint), + down: c(down, other.down), + downTint: c(downTint, other.downTint), + ); + } +} + +extension RefetchTheme on BuildContext { + RefetchColors get colors => Theme.of(this).extension()!; +} + +/// Light and dark themes in the refetch.io look: grey grouped canvas, white +/// rounded cards, the Refetch purple for the one primary action, Poppins for +/// titles and Inter (system font on Apple platforms) for everything else. class AppTheme { AppTheme._(); - static const Color _seed = Color(AppConfig.brandColor); + /// Card radius (`rounded-card`) and control radius (`rounded-control`). + static const double cardRadius = 20; + static const double controlRadius = 12; + + static const display = 'Poppins'; + + /// Apple platforms use the system font (SF Pro), as the site does via + /// `-apple-system`; everywhere else, bundled Inter. + static String? get _body => switch (defaultTargetPlatform) { + TargetPlatform.iOS || TargetPlatform.macOS => null, + _ => 'Inter', + }; - static ThemeData get light => _build(Brightness.light); - static ThemeData get dark => _build(Brightness.dark); + static ThemeData get light => _build(Brightness.light, RefetchColors.light); + static ThemeData get dark => _build(Brightness.dark, RefetchColors.dark); - static ThemeData _build(Brightness brightness) { - final colorScheme = ColorScheme.fromSeed( - seedColor: _seed, + static ThemeData _build(Brightness brightness, RefetchColors c) { + final scheme = ColorScheme( brightness: brightness, + primary: c.brandText, + onPrimary: brightness == Brightness.light + ? Colors.white + : const Color(0xFF0E0D13), + primaryContainer: c.brandTint, + onPrimaryContainer: c.brandText, + secondary: c.labelSecondary, + onSecondary: c.surface, + error: c.down, + onError: Colors.white, + surface: c.surface, + onSurface: c.label, + onSurfaceVariant: c.labelSecondary, + surfaceContainerLowest: c.bg, + surfaceContainerLow: c.bg, + surfaceContainer: c.surface, + surfaceContainerHigh: c.surfaceSecondary, + surfaceContainerHighest: c.surfaceSecondary, + outline: c.labelQuaternary, + outlineVariant: c.separator, ); - return ThemeData( + + final base = ThemeData( useMaterial3: true, - colorScheme: colorScheme, - scaffoldBackgroundColor: colorScheme.surface, + brightness: brightness, + colorScheme: scheme, + fontFamily: _body, + ); + final text = _textTheme(base.textTheme, c); + + // One filled action per view, in the logo purple with white text, in + // both themes (`brand` / `on-brand`). + final filled = FilledButton.styleFrom( + backgroundColor: c.brand, + foregroundColor: Colors.white, + shape: const StadiumBorder(), + textStyle: text.labelLarge, + minimumSize: const Size(64, 44), + ); + + return base.copyWith( + textTheme: text, + extensions: [c], + scaffoldBackgroundColor: c.bg, + canvasColor: c.bg, + dividerTheme: DividerThemeData( + color: c.separator, + thickness: 0.5, + space: 0.5, + ), appBarTheme: AppBarTheme( - backgroundColor: colorScheme.surface, - foregroundColor: colorScheme.onSurface, + backgroundColor: c.bg, + foregroundColor: c.label, + surfaceTintColor: Colors.transparent, elevation: 0, - scrolledUnderElevation: 1, + scrolledUnderElevation: 0, centerTitle: false, + titleTextStyle: text.titleLarge, ), - cardTheme: const CardThemeData( + tabBarTheme: TabBarThemeData( + labelColor: c.label, + unselectedLabelColor: c.labelTertiary, + labelStyle: text.titleSmall, + unselectedLabelStyle: text.titleSmall, + indicatorColor: c.brand, + indicatorSize: TabBarIndicatorSize.label, + dividerColor: Colors.transparent, + overlayColor: WidgetStatePropertyAll(c.fill), + ), + cardTheme: CardThemeData( + color: c.surface, elevation: 0, margin: EdgeInsets.zero, + surfaceTintColor: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(cardRadius), + ), + clipBehavior: Clip.antiAlias, + ), + filledButtonTheme: FilledButtonThemeData(style: filled), + outlinedButtonTheme: OutlinedButtonThemeData( + style: OutlinedButton.styleFrom( + foregroundColor: c.label, + backgroundColor: c.fill, + side: BorderSide.none, + shape: const StadiumBorder(), + textStyle: text.labelLarge, + minimumSize: const Size(64, 44), + ), + ), + textButtonTheme: TextButtonThemeData( + style: TextButton.styleFrom( + foregroundColor: c.brandText, + textStyle: text.labelLarge, + ), + ), + floatingActionButtonTheme: FloatingActionButtonThemeData( + backgroundColor: c.brand, + foregroundColor: Colors.white, + shape: const StadiumBorder(), + elevation: 2, + ), + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: c.fill, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(controlRadius), + borderSide: BorderSide.none, + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(controlRadius), + borderSide: BorderSide(color: c.brandText, width: 1.5), + ), + errorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(controlRadius), + borderSide: BorderSide(color: c.down), + ), + labelStyle: TextStyle(color: c.labelSecondary), + hintStyle: TextStyle(color: c.labelTertiary), + ), + snackBarTheme: SnackBarThemeData( + behavior: SnackBarBehavior.floating, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(controlRadius), + ), ), - inputDecorationTheme: const InputDecorationTheme( - border: OutlineInputBorder(), + switchTheme: SwitchThemeData( + trackColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.selected) ? c.up : c.fill, + ), + thumbColor: const WidgetStatePropertyAll(Colors.white), + trackOutlineColor: const WidgetStatePropertyAll(Colors.transparent), ), + segmentedButtonTheme: SegmentedButtonThemeData( + style: SegmentedButton.styleFrom( + selectedBackgroundColor: c.surface, + backgroundColor: c.fill, + side: BorderSide.none, + ), + ), + listTileTheme: ListTileThemeData( + iconColor: c.labelSecondary, + titleTextStyle: text.bodyLarge, + subtitleTextStyle: text.bodySmall?.copyWith(color: c.labelSecondary), + ), + progressIndicatorTheme: ProgressIndicatorThemeData(color: c.brandText), + ); + } + + /// The site's type scale (DESIGN.md › Typography): titles in Poppins, + /// the rest in the body font. + static TextTheme _textTheme(TextTheme base, RefetchColors c) { + TextStyle title( + double size, + FontWeight weight, + double height, [ + double tracking = 0, + ]) => TextStyle( + fontFamily: display, + fontSize: size, + fontWeight: weight, + height: height, + letterSpacing: tracking, + color: c.label, + ); + TextStyle body( + double size, + FontWeight weight, + double height, [ + Color? color, + ]) => TextStyle( + // Set explicitly: these styles replace the theme's defaults, so they + // would otherwise lose ThemeData.fontFamily and fall back to Roboto. + fontFamily: _body, + fontSize: size, + fontWeight: weight, + height: height, + letterSpacing: 0, + color: color ?? c.label, + ); + + return base.copyWith( + displaySmall: title(34, FontWeight.w700, 1.2, -0.4), // large-title + headlineMedium: title(28, FontWeight.w700, 1.2, -0.3), // title-1 + headlineSmall: title(22, FontWeight.w700, 1.25, -0.2), // title-2 + titleLarge: title(20, FontWeight.w600, 1.3), // title-3 + titleMedium: body(17, FontWeight.w600, 1.3), // headline + titleSmall: body(15, FontWeight.w600, 1.3), + bodyLarge: body(17, FontWeight.w400, 1.45), // body + bodyMedium: body(15, FontWeight.w400, 1.45), // subhead + bodySmall: body(13, FontWeight.w400, 1.35, c.labelSecondary), // footnote + labelLarge: body(15, FontWeight.w600, 1.2), + labelMedium: body(13, FontWeight.w600, 1.2), + labelSmall: body(12, FontWeight.w500, 1.2, c.labelTertiary), // caption-1 ); } } diff --git a/lib/core/widgets/empty_state.dart b/lib/core/widgets/empty_state.dart new file mode 100644 index 0000000..de2963d --- /dev/null +++ b/lib/core/widgets/empty_state.dart @@ -0,0 +1,74 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_theme.dart'; + +/// The refetch.io empty-state pattern: an icon, a one-line title, one +/// sentence, and at most one action. +class EmptyState extends StatelessWidget { + const EmptyState({ + super.key, + required this.icon, + required this.title, + this.message, + this.action, + this.detail, + }); + + final IconData icon; + final String title; + final String? message; + + /// A small technical line under the message (debug builds only, by caller). + final String? detail; + final Widget? action; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final c = context.colors; + return Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 56, + height: 56, + decoration: BoxDecoration( + color: c.brandTint, + shape: BoxShape.circle, + ), + child: Icon(icon, size: 26, color: c.brandText), + ), + const SizedBox(height: 16), + Text( + title, + textAlign: TextAlign.center, + style: theme.textTheme.titleMedium, + ), + if (message != null) ...[ + const SizedBox(height: 6), + Text( + message!, + textAlign: TextAlign.center, + style: theme.textTheme.bodyMedium?.copyWith( + color: c.labelSecondary, + ), + ), + ], + if (detail != null) ...[ + const SizedBox(height: 6), + Text( + detail!, + textAlign: TextAlign.center, + style: theme.textTheme.labelSmall, + ), + ], + if (action != null) ...[const SizedBox(height: 20), action!], + ], + ), + ), + ); + } +} diff --git a/lib/core/widgets/refetch_logo.dart b/lib/core/widgets/refetch_logo.dart new file mode 100644 index 0000000..6f7eb41 --- /dev/null +++ b/lib/core/widgets/refetch_logo.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_svg/flutter_svg.dart'; + +import '../theme/app_theme.dart'; + +/// The Refetch logo from refetch.io: the purple mark (identical in every +/// theme) plus the wordmark in `--logo-wordmark` (near-black in light mode, +/// white in dark mode). +class RefetchLogo extends StatelessWidget { + const RefetchLogo({super.key, this.height = 22, this.markOnly = false}); + + final double height; + + /// Just the round mark, for tight spots and empty states. + final bool markOnly; + + @override + Widget build(BuildContext context) { + if (markOnly) { + return SvgPicture.asset( + 'assets/brand/logo-mark.svg', + height: height, + semanticsLabel: 'Refetch', + ); + } + return SvgPicture.asset( + 'assets/brand/logo-wordmark.svg', + height: height, + semanticsLabel: 'Refetch', + theme: SvgTheme(currentColor: context.colors.logoWordmark), + ); + } +} diff --git a/lib/features/auth/presentation/auth_controller.dart b/lib/features/auth/presentation/auth_controller.dart index 62edcf2..64daa43 100644 --- a/lib/features/auth/presentation/auth_controller.dart +++ b/lib/features/auth/presentation/auth_controller.dart @@ -1,5 +1,12 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../core/analytics/analytics_providers.dart'; +import '../../../core/analytics/analytics_service.dart'; +import '../../../core/network/api_client.dart'; +import '../../../core/network/error_message.dart'; import '../data/auth_repository.dart'; import '../domain/app_user.dart'; @@ -18,6 +25,7 @@ class AuthController extends AsyncNotifier { state = await AsyncValue.guard( () => ref.read(authRepositoryProvider).signIn(email, password), ); + _afterAuth(AnalyticsEvents.signedIn); } Future signUp(String name, String email, String password) async { @@ -25,16 +33,46 @@ class AuthController extends AsyncNotifier { state = await AsyncValue.guard( () => ref.read(authRepositoryProvider).signUp(name, email, password), ); + _afterAuth(AnalyticsEvents.signedUp); } Future signOut() async { await ref.read(authRepositoryProvider).signOut(); state = const AsyncValue.data(null); + ref.read(analyticsProvider).track(AnalyticsEvents.signedOut); + } + + void _afterAuth(String event) { + final analytics = ref.read(analyticsProvider); + if (state.hasError) { + analytics.track( + AnalyticsEvents.signInFailed, + props: { + 'method': 'email', + 'flow': event, + 'reason': errorKind(state.error), + }, + ); + return; + } + analytics.track(event, props: {'method': 'email'}); + // Create or rename the person's refetch.io profile, as the website does + // on sign-in. Best effort: the app works without it. + unawaited( + ref + .read(apiClientProvider) + .post('/api/app/session') + .then((_) {}) + .catchError( + (Object error) => debugPrint('Profile sync failed: $error'), + ), + ); } } -final authControllerProvider = - AsyncNotifierProvider(AuthController.new); +final authControllerProvider = AsyncNotifierProvider( + AuthController.new, +); /// Convenience: the signed-in user, or `null` while loading / signed out. final currentUserProvider = Provider((ref) { diff --git a/lib/features/auth/presentation/sign_in_screen.dart b/lib/features/auth/presentation/sign_in_screen.dart index d2e1386..d9b4cb8 100644 --- a/lib/features/auth/presentation/sign_in_screen.dart +++ b/lib/features/auth/presentation/sign_in_screen.dart @@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import '../../../core/network/error_message.dart'; +import '../../../core/widgets/refetch_logo.dart'; import 'auth_controller.dart'; /// Email + password sign-in. @@ -58,7 +59,7 @@ class _SignInScreenState extends ConsumerState { }); return Scaffold( - appBar: AppBar(title: const Text('Sign in')), + appBar: AppBar(), body: Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 420), @@ -69,13 +70,30 @@ class _SignInScreenState extends ConsumerState { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + const Center(child: RefetchLogo(height: 56, markOnly: true)), + const SizedBox(height: 16), + Text( + 'Welcome back', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineMedium, + ), + const SizedBox(height: 6), + Text( + 'Sign in to vote, comment and share stories.', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 28), TextFormField( controller: _email, keyboardType: TextInputType.emailAddress, autofillHints: const [AutofillHints.email], decoration: const InputDecoration(labelText: 'Email'), - validator: (v) => - (v == null || !v.contains('@')) ? 'Enter a valid email' : null, + validator: (v) => (v == null || !v.contains('@')) + ? 'Enter a valid email' + : null, ), const SizedBox(height: 16), TextFormField( diff --git a/lib/features/auth/presentation/sign_up_screen.dart b/lib/features/auth/presentation/sign_up_screen.dart index 40b6dba..b76b6f4 100644 --- a/lib/features/auth/presentation/sign_up_screen.dart +++ b/lib/features/auth/presentation/sign_up_screen.dart @@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import '../../../core/network/error_message.dart'; +import '../../../core/widgets/refetch_logo.dart'; import 'auth_controller.dart'; /// Email + password sign-up. @@ -56,7 +57,7 @@ class _SignUpScreenState extends ConsumerState { }); return Scaffold( - appBar: AppBar(title: const Text('Create account')), + appBar: AppBar(), body: Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 420), @@ -67,12 +68,29 @@ class _SignUpScreenState extends ConsumerState { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + const Center(child: RefetchLogo(height: 56, markOnly: true)), + const SizedBox(height: 16), + Text( + 'Join Refetch', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineMedium, + ), + const SizedBox(height: 6), + Text( + 'The front page for builders. Free and open source.', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 28), TextFormField( controller: _name, textCapitalization: TextCapitalization.words, decoration: const InputDecoration(labelText: 'Name'), - validator: (v) => - (v == null || v.trim().isEmpty) ? 'Enter your name' : null, + validator: (v) => (v == null || v.trim().isEmpty) + ? 'Enter your name' + : null, ), const SizedBox(height: 16), TextFormField( @@ -80,8 +98,9 @@ class _SignUpScreenState extends ConsumerState { keyboardType: TextInputType.emailAddress, autofillHints: const [AutofillHints.email], decoration: const InputDecoration(labelText: 'Email'), - validator: (v) => - (v == null || !v.contains('@')) ? 'Enter a valid email' : null, + validator: (v) => (v == null || !v.contains('@')) + ? 'Enter a valid email' + : null, ), const SizedBox(height: 16), TextFormField( @@ -93,8 +112,9 @@ class _SignUpScreenState extends ConsumerState { helperText: 'At least 8 characters', ), onFieldSubmitted: (_) => _submit(), - validator: (v) => - (v == null || v.length < 8) ? 'At least 8 characters' : null, + validator: (v) => (v == null || v.length < 8) + ? 'At least 8 characters' + : null, ), const SizedBox(height: 24), FilledButton( diff --git a/lib/features/feed/data/feed_repository.dart b/lib/features/feed/data/feed_repository.dart index 2db3b81..b5c38f4 100644 --- a/lib/features/feed/data/feed_repository.dart +++ b/lib/features/feed/data/feed_repository.dart @@ -1,6 +1,8 @@ +import 'package:appwrite/appwrite.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../../../core/network/api_client.dart'; +import '../../../core/appwrite/appwrite_providers.dart'; +import '../../../core/config/app_config.dart'; import '../domain/post.dart'; /// The four feed views, matching the web app's tabs. @@ -18,42 +20,93 @@ enum FeedTab { /// Whether this tab requires an authenticated user. bool get requiresAuth => this == FeedTab.mines; - /// `sortType` query value for `/api/posts` (null for the auth-gated Mines tab, - /// which uses a dedicated endpoint). - String? get sortType => switch (this) { - FeedTab.top => 'score', + /// Name used in analytics events. + String get analyticsName => switch (this) { + FeedTab.top => 'top', FeedTab.latest => 'new', FeedTab.show => 'show', - FeedTab.mines => null, + FeedTab.mines => 'mines', }; } -/// Reads paginated feed pages from the refetch.io REST API. +/// Quality gates the web applies to the front page (`posts.server.ts`). +const _maxSpamScore = 70; +const _minRelevancyScore = 30; +const _frontPageWindow = Duration(hours: 24); + +/// The TablesDB queries for one feed page, mirroring the web's `listFeed` +/// and `listUserPosts`. Pure so it can be tested. +List feedQueries( + FeedTab tab, { + required int limit, + required int offset, + String? userId, + DateTime? now, +}) { + final page = [ + Query.limit(limit), + Query.offset(offset), + Query.select(Post.listFields), + ]; + + if (tab == FeedTab.mines) { + return [ + Query.equal('userId', userId ?? ''), + Query.orderDesc(r'$createdAt'), + ...page, + ]; + } + + final since = (now ?? DateTime.now()).toUtc().subtract(_frontPageWindow); + return [ + Query.greaterThan(r'$createdAt', since.toIso8601String()), + Query.lessThan('spamScore', _maxSpamScore), + Query.greaterThan('relevancyScore', _minRelevancyScore), + Query.equal('enhanced', true), + if (tab == FeedTab.show) Query.equal('type', 'show'), + if (tab == FeedTab.latest) + Query.orderDesc(r'$createdAt') + else ...[ + Query.orderDesc('score'), + Query.orderDesc(r'$createdAt'), + ], + ...page, + ]; +} + +/// Reads feed pages straight from the Appwrite posts table (public-read). class FeedRepository { - FeedRepository(this._api); + FeedRepository(this._tables); - final ApiClient _api; + final TablesDB _tables; Future> fetch( FeedTab tab, { required int limit, required int offset, + String? userId, }) async { - final query = {'limit': '$limit', 'offset': '$offset'}; - - if (tab == FeedTab.mines) { - final data = await _api.get('/api/mines', query: query, auth: true); - return Post.listFromResponse(data); - } + if (tab == FeedTab.mines && userId == null) return const []; + final result = await _tables.listRows( + databaseId: AppConfig.databaseId, + tableId: AppConfig.postsTableId, + queries: feedQueries(tab, limit: limit, offset: offset, userId: userId), + total: false, + ); + return [for (final row in result.rows) Post.fromRow(row.data)]; + } - final data = await _api.get( - '/api/posts', - query: {'sortType': tab.sortType!, ...query}, + /// One story with its summary columns, for the thread screen. + Future get(String postId) async { + final row = await _tables.getRow( + databaseId: AppConfig.databaseId, + tableId: AppConfig.postsTableId, + rowId: postId, ); - return Post.listFromResponse(data); + return Post.fromRow(row.data); } } final feedRepositoryProvider = Provider((ref) { - return FeedRepository(ref.watch(apiClientProvider)); + return FeedRepository(ref.watch(tablesDbProvider)); }); diff --git a/lib/features/feed/domain/post.dart b/lib/features/feed/domain/post.dart index 07d3f61..b6e73ca 100644 --- a/lib/features/feed/domain/post.dart +++ b/lib/features/feed/domain/post.dart @@ -1,7 +1,8 @@ -import 'dart:convert'; +import '../../../core/config/app_config.dart'; +import '../../../core/format/time_ago.dart' as format; -/// A feed item (a submitted link or "show" post) as returned by the refetch.io -/// `/api/posts`, `/api/mines`, and `/api/posts/{id}` endpoints. +/// A story (a submitted link or "show" post), read from the Appwrite posts +/// table. Mirrors `toPost`/`toPostDetail` in the web repo's `db.server.ts`. class Post { const Post({ required this.id, @@ -10,7 +11,7 @@ class Post { required this.count, required this.author, required this.countComments, - this.timeAgo, + this.createdAt, this.description, this.tldr, this.userId, @@ -22,13 +23,13 @@ class Post { final String id; final String title; + + /// Host of [link] without `www.`, or empty for a post without a link. final String domain; final int count; final String author; final int countComments; - - /// Pre-formatted "x hours ago" string from the API (field `daysAgo`). - final String? timeAgo; + final DateTime? createdAt; final String? description; final String? tldr; final String? userId; @@ -38,44 +39,96 @@ class Post { final String? type; final int? readingTime; - /// `'up'`, `'down'`, or `null`. Only populated on auth-aware endpoints. + /// `'up'`, `'down'`, or `null`; filled in from `/api/app/votes`. final String? currentVote; bool get isShow => type == 'show'; - factory Post.fromJson(Map json) { + /// "3h ago", or null when the row carried no creation time. + String? get timeAgo => createdAt == null ? null : format.timeAgo(createdAt!); + + /// The thread on refetch.io, for sharing. + String get threadUrl => '${AppConfig.apiBaseUrl}/threads/$id'; + + /// Columns the feed selects (the web's `POST_LIST_FIELDS`). + static const listFields = [ + r'$id', + r'$createdAt', + 'title', + 'description', + 'userId', + 'userName', + 'count', + 'countComments', + 'link', + 'type', + 'readingTime', + ]; + + /// Builds a post from a TablesDB row's data (which includes `$id` and + /// `$createdAt`). + factory Post.fromRow(Map row, {String? currentVote}) { + final rawLink = row['link']; + final link = + rawLink is String && + RegExp(r'^https?://', caseSensitive: false).hasMatch(rawLink) + ? rawLink + : null; + final userName = row['userName']; + final tldr = row['tldr']; + final readingTime = row['readingTime']; + final description = row['description']; return Post( - id: json['id'] as String, - title: (json['title'] ?? '') as String, - domain: (json['domain'] ?? '') as String, - count: _asInt(json['count']), - author: (json['author'] ?? 'anonymous') as String, - countComments: _asInt(json['countComments']), - timeAgo: json['daysAgo'] as String?, - description: json['description'] as String?, - tldr: json['tldr'] as String?, - userId: json['userId'] as String?, - link: json['link'] as String?, - type: json['type'] as String?, - readingTime: json['readingTime'] == null - ? null - : _asInt(json['readingTime']), - currentVote: json['currentVote'] as String?, + id: '${row[r'$id']}', + title: '${row['title'] ?? ''}', + domain: hostOf(link), + count: _asInt(row['count']), + author: userName is String && userName.isNotEmpty + ? userName + : 'Anonymous', + countComments: _asInt(row['countComments']), + createdAt: DateTime.tryParse('${row[r'$createdAt'] ?? ''}'), + description: description is String && description.trim().isNotEmpty + ? description.trim() + : null, + tldr: tldr is String && tldr.trim().isNotEmpty ? tldr.trim() : null, + userId: row['userId'] is String ? row['userId'] as String : null, + link: link, + type: row['type'] == 'show' ? 'show' : 'link', + readingTime: readingTime is num && readingTime > 0 + ? readingTime.toInt() + : null, + currentVote: currentVote, ); } - static int _asInt(dynamic value) => - value is num ? value.toInt() : int.tryParse('$value') ?? 0; + Post withVote(String? vote) => Post( + id: id, + title: title, + domain: domain, + count: count, + author: author, + countComments: countComments, + createdAt: createdAt, + description: description, + tldr: tldr, + userId: userId, + link: link, + type: type, + readingTime: readingTime, + currentVote: vote, + ); - /// Parses a `{ "posts": [...] }` envelope (or a bare list) into [Post]s. - static List listFromResponse(dynamic data) { - final list = data is Map ? data['posts'] : data; - if (list is! List) return const []; - return list - .map((e) => Post.fromJson(e as Map)) - .toList(growable: false); + /// `https://www.example.com/a` → `example.com`. + static String hostOf(String? url) { + if (url == null) return ''; + final host = Uri.tryParse(url)?.host ?? ''; + return host.startsWith('www.') ? host.substring(4) : host; } + static int _asInt(dynamic value) => + value is num ? value.toInt() : int.tryParse('$value') ?? 0; + @override - String toString() => 'Post(${jsonEncode({'id': id, 'title': title})})'; + String toString() => 'Post($id, $title)'; } diff --git a/lib/features/feed/presentation/feed_list.dart b/lib/features/feed/presentation/feed_list.dart index 88f73a1..b4171c3 100644 --- a/lib/features/feed/presentation/feed_list.dart +++ b/lib/features/feed/presentation/feed_list.dart @@ -2,11 +2,17 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import '../../../core/analytics/analytics_providers.dart'; +import '../../../core/analytics/analytics_service.dart'; import '../../../core/config/app_config.dart'; import '../../../core/network/error_message.dart'; +import '../../../core/theme/app_theme.dart'; +import '../../../core/widgets/empty_state.dart'; import '../../auth/presentation/auth_controller.dart'; import '../../vote/data/vote_repository.dart'; +import '../../vote/domain/vote_state.dart'; import '../../vote/presentation/vote_controller.dart'; import '../data/feed_repository.dart'; import '../domain/post.dart'; @@ -75,6 +81,17 @@ class _FeedListState extends ConsumerState widget.tab, limit: AppConfig.feedPageSize, offset: _offset, + userId: ref.read(currentUserProvider)?.id, + ); + ref + .read(analyticsProvider) + .track( + AnalyticsEvents.feedLoaded, + props: { + 'tab': widget.tab.analyticsName, + 'page': _offset ~/ AppConfig.feedPageSize + 1, + 'count': page.length, + }, ); if (!mounted) return; setState(() { @@ -89,6 +106,16 @@ class _FeedListState extends ConsumerState // Also logged so a failure is recoverable from device logs when someone // reports it, not only from what happens to be on screen. debugPrint('Feed load failed (${widget.tab.name}): $error'); + ref + .read(analyticsProvider) + .track( + AnalyticsEvents.feedLoadFailed, + props: { + 'tab': widget.tab.analyticsName, + 'page': _offset ~/ AppConfig.feedPageSize + 1, + 'reason': errorKind(error), + }, + ); if (!mounted) return; setState(() { _error = error; @@ -108,7 +135,11 @@ class _FeedListState extends ConsumerState ]; final votes = await ref.read(voteRepositoryProvider).batch(resources); if (!mounted) return; - ref.read(voteControllerProvider.notifier).prime(votes); + ref.read(voteControllerProvider.notifier).prime({ + for (final p in page) + if (votes[p.id] != null) + p.id: VoteState(count: p.count, currentVote: votes[p.id]), + }); } catch (_) { // Vote priming is best-effort; arrows fall back to default state. } @@ -130,7 +161,15 @@ class _FeedListState extends ConsumerState super.build(context); if (widget.tab.requiresAuth && ref.watch(currentUserProvider) == null) { - return _SignInPrompt(onSignIn: () => context.push('/signin')); + return EmptyState( + icon: LucideIcons.lock, + title: 'Your stories live here', + message: 'Sign in to see the stories you have shared.', + action: FilledButton( + onPressed: () => context.push('/signin'), + child: const Text('Sign in'), + ), + ); } if (!_initialLoadDone && _loading) { @@ -144,26 +183,73 @@ class _FeedListState extends ConsumerState if (_posts.isEmpty) { return RefreshIndicator( onRefresh: _refresh, - child: ListView( - children: const [ - SizedBox(height: 200), - Center(child: Text('Nothing here yet.')), - ], + child: LayoutBuilder( + builder: (context, constraints) => SingleChildScrollView( + physics: const AlwaysScrollableScrollPhysics(), + child: SizedBox( + height: constraints.maxHeight, + child: widget.tab == FeedTab.mines + ? EmptyState( + icon: LucideIcons.squarePen, + title: 'Nothing shared yet', + message: 'Stories you submit will show up here.', + action: FilledButton( + onPressed: () => context.push('/submit'), + child: const Text('Submit a story'), + ), + ) + : const EmptyState( + icon: LucideIcons.newspaper, + title: 'No stories right now', + message: 'Pull down to check again in a bit.', + ), + ), + ), ), ); } + final ranked = widget.tab == FeedTab.top || widget.tab == FeedTab.show; + final c = context.colors; return RefreshIndicator( onRefresh: _refresh, - child: ListView.separated( + child: ListView.builder( controller: _scrollController, + padding: const EdgeInsets.fromLTRB(12, 8, 12, 24), itemCount: _posts.length + 1, - separatorBuilder: (_, _) => const Divider(height: 1), itemBuilder: (context, index) { if (index >= _posts.length) { return _FooterLoader(loading: _loading, hasMore: _hasMore); } - return PostCard(post: _posts[index]); + // One rounded card for the whole list, with hairlines between rows + // (refetch.io's inset grouped list). + final first = index == 0; + final last = index == _posts.length - 1; + const r = Radius.circular(AppTheme.cardRadius); + return Container( + decoration: BoxDecoration( + color: c.surface, + borderRadius: BorderRadius.vertical( + top: first ? r : Radius.zero, + bottom: last ? r : Radius.zero, + ), + ), + clipBehavior: Clip.antiAlias, + child: Column( + children: [ + PostCard( + post: _posts[index], + rank: ranked ? index + 1 : null, + source: 'feed_${widget.tab.analyticsName}', + ), + if (!last) + Padding( + padding: EdgeInsets.only(left: ranked ? 70 : 46), + child: const Divider(height: 0.5), + ), + ], + ), + ); }, ), ); @@ -186,11 +272,11 @@ class _FooterLoader extends StatelessWidget { } if (!hasMore) { return Padding( - padding: const EdgeInsets.all(16), + padding: const EdgeInsets.all(20), child: Center( child: Text( - "You've reached the end.", - style: Theme.of(context).textTheme.bodySmall, + "You're all caught up.", + style: Theme.of(context).textTheme.labelSmall, ), ), ); @@ -199,28 +285,6 @@ class _FooterLoader extends StatelessWidget { } } -class _SignInPrompt extends StatelessWidget { - const _SignInPrompt({required this.onSignIn}); - - final VoidCallback onSignIn; - - @override - Widget build(BuildContext context) { - return Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.lock_outline, size: 48), - const SizedBox(height: 12), - const Text('Sign in to see your posts.'), - const SizedBox(height: 12), - FilledButton(onPressed: onSignIn, child: const Text('Sign in')), - ], - ), - ); - } -} - class _ErrorState extends StatelessWidget { const _ErrorState({required this.error, required this.onRetry}); @@ -229,40 +293,20 @@ class _ErrorState extends StatelessWidget { @override Widget build(BuildContext context) { - final theme = Theme.of(context); - // Debug builds only: the friendly message already separates "offline" from - // "server broke" from a real API message, so users gain nothing from an - // exception class name — and release notes of it read as an unfinished app. - final detail = kDebugMode ? detailForError(error) : null; - - return Center( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 32), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.error_outline, size: 48), - const SizedBox(height: 12), - Text( - messageForError(error, fallback: 'Could not load the feed.'), - textAlign: TextAlign.center, - ), - if (detail != null) ...[ - const SizedBox(height: 6), - // Shown so someone reporting a problem can quote something more - // specific than "it didn't load". - Text( - detail, - textAlign: TextAlign.center, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], - const SizedBox(height: 12), - OutlinedButton(onPressed: onRetry, child: const Text('Retry')), - ], - ), + final kind = errorKind(error); + return EmptyState( + icon: kind == 'network' ? LucideIcons.wifiOff : LucideIcons.circleAlert, + title: kind == 'network' ? "You're offline" : "Couldn't load stories", + message: messageForError( + error, + fallback: 'Something went wrong. Please try again.', + ), + // Debug builds only: the friendly message already separates "offline" + // from "server broke"; users gain nothing from an exception name. + detail: kDebugMode ? detailForError(error) : null, + action: OutlinedButton( + onPressed: onRetry, + child: const Text('Try again'), ), ); } diff --git a/lib/features/feed/presentation/feed_screen.dart b/lib/features/feed/presentation/feed_screen.dart index 8642195..dd95879 100644 --- a/lib/features/feed/presentation/feed_screen.dart +++ b/lib/features/feed/presentation/feed_screen.dart @@ -1,52 +1,48 @@ import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; -import '../../auth/presentation/auth_controller.dart'; +import '../../../core/widgets/refetch_logo.dart'; import '../data/feed_repository.dart'; import 'feed_list.dart'; -/// Home screen: the four feed tabs (Top / New / Show / Mines) plus actions for -/// submitting and the account. -class FeedScreen extends ConsumerWidget { +/// Home screen: the Refetch wordmark, the four feed tabs (Top / New / Show / +/// Mines), and actions for submitting and the account. +class FeedScreen extends StatelessWidget { const FeedScreen({super.key}); @override - Widget build(BuildContext context, WidgetRef ref) { - final user = ref.watch(currentUserProvider); - + Widget build(BuildContext context) { return DefaultTabController( length: FeedTab.values.length, child: Scaffold( appBar: AppBar( - title: const Text( - 'Refetch', - style: TextStyle(fontWeight: FontWeight.w800), - ), + titleSpacing: 16, + title: const RefetchLogo(height: 24), actions: [ IconButton( - tooltip: 'Submit', - icon: const Icon(Icons.add_circle_outline), + tooltip: 'Submit a story', + icon: const Icon(LucideIcons.squarePen, size: 22), onPressed: () => context.push('/submit'), ), + // Account works signed out too: it offers sign-in and holds the + // analytics switch, which signed-out people need as well. IconButton( - tooltip: user == null ? 'Sign in' : 'Account', - icon: Icon(user == null ? Icons.login : Icons.account_circle), - onPressed: () => context.push(user == null ? '/signin' : '/profile'), + tooltip: 'Account', + icon: const Icon(LucideIcons.circleUserRound, size: 22), + onPressed: () => context.push('/profile'), ), + const SizedBox(width: 4), ], bottom: TabBar( isScrollable: true, tabAlignment: TabAlignment.start, - tabs: [ - for (final tab in FeedTab.values) Tab(text: tab.label), - ], + padding: const EdgeInsets.symmetric(horizontal: 4), + tabs: [for (final tab in FeedTab.values) Tab(text: tab.label)], ), ), body: TabBarView( - children: [ - for (final tab in FeedTab.values) FeedList(tab: tab), - ], + children: [for (final tab in FeedTab.values) FeedList(tab: tab)], ), ), ); diff --git a/lib/features/feed/presentation/post_card.dart b/lib/features/feed/presentation/post_card.dart index 04ee2e9..645da81 100644 --- a/lib/features/feed/presentation/post_card.dart +++ b/lib/features/feed/presentation/post_card.dart @@ -1,102 +1,155 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; import 'package:url_launcher/url_launcher.dart'; +import '../../../core/analytics/analytics_providers.dart'; +import '../../../core/analytics/analytics_service.dart'; +import '../../../core/share/share_story.dart'; +import '../../../core/theme/app_theme.dart'; import '../../../core/widgets/site_favicon.dart'; import '../../vote/presentation/vote_buttons.dart'; import '../domain/post.dart'; -/// A single feed row: vote control, title, source/meta line, and comment count. +/// One story row in a feed list (refetch.io `PostRow`): optional rank, vote +/// control, favicon, title, and a meta line with comments and share. Tapping +/// opens the thread, whose "Read article" opens the link. class PostCard extends ConsumerWidget { - const PostCard({super.key, required this.post}); + const PostCard({ + super.key, + required this.post, + this.rank, + this.source = 'feed', + }); final Post post; + /// 1-based position where order means something (Top, Show). + final int? rank; + + /// Where the row is shown, for analytics (`feed_top`, `feed_new`, …). + final String source; + @override Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); - final scheme = theme.colorScheme; + final c = context.colors; return InkWell( - onTap: () => context.push('/thread/${post.id}'), + onTap: () { + ref + .read(analyticsProvider) + .track( + AnalyticsEvents.storyOpened, + props: {'post_id': post.id, 'source': source}, + ); + context.push('/thread/${post.id}'); + }, child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + padding: const EdgeInsets.fromLTRB(8, 10, 4, 10), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ + if (rank != null) + SizedBox( + width: 24, + child: Padding( + padding: const EdgeInsets.only(top: 12), + child: Text( + '$rank', + textAlign: TextAlign.center, + style: theme.textTheme.labelMedium?.copyWith( + fontFeatures: const [FontFeature.tabularFigures()], + color: rank! <= 3 ? c.brandText : c.labelQuaternary, + ), + ), + ), + ), VoteButtons( resourceId: post.id, resourceType: 'post', fallbackCount: post.count, fallbackVote: post.currentVote, + compact: true, + ), + const SizedBox(width: 8), + Padding( + padding: const EdgeInsets.only(top: 4), + child: SiteFavicon(domain: post.link ?? post.domain, size: 24), ), - const SizedBox(width: 10), - SiteFavicon(domain: post.link ?? post.domain), const SizedBox(width: 10), Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - post.title, - style: theme.textTheme.titleSmall?.copyWith( - fontWeight: FontWeight.w600, - height: 1.25, + child: Padding( + padding: const EdgeInsets.only(top: 2), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + post.title, + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.w500, + height: 1.3, + ), ), - ), - const SizedBox(height: 6), - _MetaLine(post: post), - ], + const SizedBox(height: 6), + _MetaLine(post: post, source: source), + ], + ), ), ), - if (post.link != null) ...[ - const SizedBox(width: 4), - IconButton( - tooltip: 'Open link', - visualDensity: VisualDensity.compact, - icon: Icon(Icons.open_in_new, size: 18, color: scheme.onSurfaceVariant), - onPressed: () => _openLink(context, post.link!), - ), - ], + const SizedBox(width: 12), ], ), ), ); } +} - Future _openLink(BuildContext context, String url) async { - final uri = Uri.tryParse(url); - final messenger = ScaffoldMessenger.of(context); - if (uri == null || !await launchUrl(uri, mode: LaunchMode.externalApplication)) { - messenger.showSnackBar( - const SnackBar(content: Text('Could not open the link.')), +/// Opens the story's article in the browser and records it. +Future openArticle( + BuildContext context, + WidgetRef ref, + Post post, { + required String source, +}) async { + final uri = post.link == null ? null : Uri.tryParse(post.link!); + final messenger = ScaffoldMessenger.of(context); + ref + .read(analyticsProvider) + .track( + AnalyticsEvents.articleOpened, + props: {'post_id': post.id, 'source': source, 'domain': post.domain}, ); - } + if (uri == null || + !await launchUrl(uri, mode: LaunchMode.externalApplication)) { + messenger.showSnackBar( + const SnackBar(content: Text('Could not open the link.')), + ); } } -class _MetaLine extends StatelessWidget { - const _MetaLine({required this.post}); +class _MetaLine extends ConsumerWidget { + const _MetaLine({required this.post, required this.source}); final Post post; + final String source; @override - Widget build(BuildContext context) { - final style = Theme.of(context).textTheme.bodySmall?.copyWith( - color: Theme.of(context).colorScheme.onSurfaceVariant, - ); + Widget build(BuildContext context, WidgetRef ref) { + final c = context.colors; + final style = Theme.of( + context, + ).textTheme.bodySmall?.copyWith(color: c.labelTertiary); final parts = [ if (post.domain.isNotEmpty) post.domain, if (post.timeAgo != null) post.timeAgo!, - if (post.readingTime != null && post.readingTime! > 0) - '${post.readingTime} min read', ]; return Row( children: [ - Expanded( + Flexible( child: Text( parts.join(' · '), maxLines: 1, @@ -104,10 +157,30 @@ class _MetaLine extends StatelessWidget { style: style, ), ), - const SizedBox(width: 8), - Icon(Icons.mode_comment_outlined, size: 14, color: style?.color), + const SizedBox(width: 10), + Icon(LucideIcons.messageCircle, size: 13, color: c.labelTertiary), const SizedBox(width: 4), - Text('${post.countComments}', style: style), + Text( + '${post.countComments}', + style: style?.copyWith( + fontFeatures: const [FontFeature.tabularFigures()], + ), + ), + const SizedBox(width: 4), + Builder( + builder: (buttonContext) => IconButton( + tooltip: 'Share', + visualDensity: VisualDensity.compact, + style: const ButtonStyle( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + padding: EdgeInsets.zero, + constraints: const BoxConstraints.tightFor(width: 36, height: 24), + icon: Icon(LucideIcons.share, size: 15, color: c.labelTertiary), + onPressed: () => + shareStory(buttonContext, ref, post, source: source), + ), + ), ], ); } diff --git a/lib/features/profile/presentation/profile_screen.dart b/lib/features/profile/presentation/profile_screen.dart index 12e37ff..d176427 100644 --- a/lib/features/profile/presentation/profile_screen.dart +++ b/lib/features/profile/presentation/profile_screen.dart @@ -1,9 +1,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; import '../../auth/presentation/auth_controller.dart'; +import '../../../core/widgets/empty_state.dart'; import '../../settings/presentation/notification_settings.dart'; +import '../../settings/presentation/privacy_settings.dart'; /// Account screen: shows the signed-in user and a sign-out action, or a /// sign-in prompt when signed out. @@ -19,17 +22,19 @@ class ProfileScreen extends ConsumerWidget { appBar: AppBar(title: const Text('Account')), body: Center( child: user == null - ? Column( - mainAxisSize: MainAxisSize.min, + ? ListView( + shrinkWrap: true, children: [ - const Icon(Icons.account_circle_outlined, size: 64), - const SizedBox(height: 12), - const Text('You are not signed in.'), - const SizedBox(height: 12), - FilledButton( - onPressed: () => context.push('/signin'), - child: const Text('Sign in'), + EmptyState( + icon: LucideIcons.userRound, + title: 'You are not signed in', + message: 'Sign in to vote, comment and get replies.', + action: FilledButton( + onPressed: () => context.push('/signin'), + child: const Text('Sign in'), + ), ), + const PrivacySettings(), ], ) : ListView( @@ -64,12 +69,14 @@ class ProfileScreen extends ConsumerWidget { const Divider(height: 1), const NotificationSettings(), const Divider(height: 1), + const PrivacySettings(), + const Divider(height: 1), const SizedBox(height: 24), Center( child: OutlinedButton.icon( onPressed: () => ref.read(authControllerProvider.notifier).signOut(), - icon: const Icon(Icons.logout), + icon: const Icon(LucideIcons.logOut, size: 18), label: const Text('Sign out'), ), ), diff --git a/lib/features/settings/presentation/notification_settings.dart b/lib/features/settings/presentation/notification_settings.dart index 7da1dab..777d7f7 100644 --- a/lib/features/settings/presentation/notification_settings.dart +++ b/lib/features/settings/presentation/notification_settings.dart @@ -1,7 +1,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; import 'package:permission_handler/permission_handler.dart'; +import '../../../core/analytics/analytics_providers.dart'; +import '../../../core/analytics/analytics_service.dart'; import '../../../core/network/error_message.dart'; import '../../../core/push/push_providers.dart'; import '../../../core/push/push_topic.dart'; @@ -43,8 +46,9 @@ class _NotificationSettingsState extends ConsumerState { } Future _grantPermission() async { - final granted = - await ref.read(pushNotificationServiceProvider).requestPermission(); + final granted = await ref + .read(pushNotificationServiceProvider) + .requestPermission(); if (!mounted) return; if (!granted) { // Likely permanently denied — send the user to system settings. @@ -61,6 +65,12 @@ class _NotificationSettingsState extends ConsumerState { try { if (value && !_permissionGranted) await _grantPermission(); await ref.read(topicSubscriptionsProvider).setEnabled(topic, value); + ref + .read(analyticsProvider) + .track( + AnalyticsEvents.settingChanged, + props: {'setting': 'push_${topic.topicId}', 'value': value}, + ); messenger ..hideCurrentSnackBar() ..showSnackBar( @@ -112,7 +122,7 @@ class _NotificationSettingsState extends ConsumerState { ), if (!_permissionGranted) ListTile( - leading: const Icon(Icons.notifications_off_outlined), + leading: const Icon(LucideIcons.bellOff), title: const Text('Allow notifications'), subtitle: const Text('Required to receive push notifications'), trailing: FilledButton( diff --git a/lib/features/settings/presentation/privacy_settings.dart b/lib/features/settings/presentation/privacy_settings.dart new file mode 100644 index 0000000..174f262 --- /dev/null +++ b/lib/features/settings/presentation/privacy_settings.dart @@ -0,0 +1,37 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/analytics/analytics_providers.dart'; + +/// The analytics switch in Account. Anonymous usage analytics are on by +/// default (as on refetch.io) and stop the moment this is turned off. +class PrivacySettings extends ConsumerWidget { + const PrivacySettings({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final consent = ref.watch(analyticsConsentProvider); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 4), + child: Text('Privacy', style: Theme.of(context).textTheme.titleSmall), + ), + SwitchListTile( + title: const Text('Share anonymous usage data'), + subtitle: const Text( + 'Which screens and features get used, so we know what to improve. ' + 'Never your name, email or what you write.', + ), + value: consent.value ?? false, + onChanged: consent.isLoading + ? null + : (value) => ref + .read(analyticsConsentProvider.notifier) + .setEnabled(value), + ), + ], + ); + } +} diff --git a/lib/features/submit/data/submit_repository.dart b/lib/features/submit/data/submit_repository.dart index 8312ce1..22baa6c 100644 --- a/lib/features/submit/data/submit_repository.dart +++ b/lib/features/submit/data/submit_repository.dart @@ -2,28 +2,30 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../core/network/api_client.dart'; -/// Submits new posts (links or "show" posts) via the refetch.io REST API. +/// Submits stories through the app API (`/api/app/submit`). As on refetch.io, +/// a story is a link; an optional note becomes the first comment. class SubmitRepository { SubmitRepository(this._api); final ApiClient _api; - Future submit({ + /// Returns the new story's id. + Future submit({ required String title, - required String type, - String? url, - String? description, + required String url, + String? comment, }) async { - await _api.post( - '/api/submit', - body: { - 'title': title, - 'type': type, - if (url != null && url.isNotEmpty) 'url': url, - if (description != null && description.isNotEmpty) - 'description': description, - }, - ); + final data = + await _api.post( + '/api/app/submit', + body: { + 'title': title, + 'url': url, + if (comment != null && comment.isNotEmpty) 'comment': comment, + }, + ) + as Map; + return '${data['id']}'; } } diff --git a/lib/features/submit/presentation/submit_screen.dart b/lib/features/submit/presentation/submit_screen.dart index d355eb4..ebf9316 100644 --- a/lib/features/submit/presentation/submit_screen.dart +++ b/lib/features/submit/presentation/submit_screen.dart @@ -1,12 +1,18 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import '../../../core/analytics/analytics_providers.dart'; +import '../../../core/analytics/analytics_service.dart'; +import '../../../core/network/api_exception.dart'; import '../../../core/network/error_message.dart'; +import '../../../core/widgets/empty_state.dart'; import '../../auth/presentation/auth_controller.dart'; import '../data/submit_repository.dart'; -/// Submit a new post — either a link or a "show" (text) post. +/// Share a story, as on refetch.io: a link and a title, plus an optional note +/// that becomes the first comment of the discussion. class SubmitScreen extends ConsumerStatefulWidget { const SubmitScreen({super.key}); @@ -18,16 +24,15 @@ class _SubmitScreenState extends ConsumerState { final _formKey = GlobalKey(); final _title = TextEditingController(); final _url = TextEditingController(); - final _description = TextEditingController(); + final _note = TextEditingController(); - String _type = 'link'; bool _submitting = false; @override void dispose() { _title.dispose(); _url.dispose(); - _description.dispose(); + _note.dispose(); super.dispose(); } @@ -36,24 +41,34 @@ class _SubmitScreenState extends ConsumerState { setState(() => _submitting = true); final messenger = ScaffoldMessenger.of(context); final router = GoRouter.of(context); + final analytics = ref.read(analyticsProvider); try { - await ref + final id = await ref .read(submitRepositoryProvider) .submit( title: _title.text.trim(), - type: _type, - url: _type == 'link' ? _url.text.trim() : null, - description: _description.text.trim(), + url: _url.text.trim(), + comment: _note.text.trim(), ); + analytics.track( + AnalyticsEvents.storySubmitted, + props: {'has_note': _note.text.trim().isNotEmpty}, + ); messenger.showSnackBar( - const SnackBar(content: Text('Submitted! It will appear once processed.')), + const SnackBar( + content: Text( + 'Shared. It reaches the front page once it has been reviewed.', + ), + ), ); - if (mounted) router.pop(); + if (mounted) router.pushReplacement('/thread/$id'); + } on ApiException catch (error) { + messenger.showSnackBar(SnackBar(content: Text(error.message))); } catch (error) { messenger.showSnackBar( SnackBar( content: Text( - messageForError(error, fallback: 'Could not submit your post.'), + messageForError(error, fallback: 'Could not share your story.'), ), ), ); @@ -65,79 +80,96 @@ class _SubmitScreenState extends ConsumerState { @override Widget build(BuildContext context) { final user = ref.watch(currentUserProvider); + final theme = Theme.of(context); return Scaffold( - appBar: AppBar(title: const Text('Submit')), + appBar: AppBar(), body: user == null - ? _SignInRequired(onSignIn: () => context.push('/signin')) + ? EmptyState( + icon: LucideIcons.squarePen, + title: 'Share a story', + message: 'Sign in to share links with the community.', + action: FilledButton( + onPressed: () => context.push('/signin'), + child: const Text('Sign in'), + ), + ) : Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 480), child: SingleChildScrollView( - padding: const EdgeInsets.all(24), + padding: const EdgeInsets.fromLTRB(20, 4, 20, 24), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - SegmentedButton( - segments: const [ - ButtonSegment(value: 'link', label: Text('Link')), - ButtonSegment(value: 'show', label: Text('Show')), - ], - selected: {_type}, - onSelectionChanged: (s) => - setState(() => _type = s.first), + Text( + 'Share a story', + style: theme.textTheme.headlineMedium, + ), + const SizedBox(height: 6), + Text( + 'Links to articles, launches and projects worth a builder’s time.', + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), ), - const SizedBox(height: 20), + const SizedBox(height: 24), + TextFormField( + controller: _url, + keyboardType: TextInputType.url, + autocorrect: false, + decoration: const InputDecoration( + labelText: 'Link', + hintText: 'https://', + ), + validator: (v) { + final value = v?.trim() ?? ''; + final uri = Uri.tryParse(value); + final ok = + uri != null && + (uri.scheme == 'http' || + uri.scheme == 'https') && + uri.host.isNotEmpty; + return ok ? null : 'Enter a valid http(s) link'; + }, + ), + const SizedBox(height: 16), TextFormField( controller: _title, + maxLength: 300, decoration: const InputDecoration(labelText: 'Title'), validator: (v) => (v == null || v.trim().isEmpty) - ? 'Enter a title' + ? 'Add a title' : null, ), - const SizedBox(height: 16), - if (_type == 'link') - TextFormField( - controller: _url, - keyboardType: TextInputType.url, - decoration: const InputDecoration(labelText: 'URL'), - validator: (v) { - if (_type != 'link') return null; - final value = v?.trim() ?? ''; - final uri = Uri.tryParse(value); - if (value.isEmpty || uri == null || !uri.isAbsolute) { - return 'Enter a valid URL'; - } - return null; - }, - ), - if (_type == 'show') - TextFormField( - controller: _description, - minLines: 4, - maxLines: 8, - decoration: const InputDecoration( - labelText: 'Description', - ), - validator: (v) { - if (_type != 'show') return null; - return (v == null || v.trim().isEmpty) - ? 'Describe what you are showing' - : null; - }, + const SizedBox(height: 8), + TextFormField( + controller: _note, + minLines: 3, + maxLines: 6, + maxLength: 2000, + decoration: const InputDecoration( + labelText: 'Note (optional)', + hintText: + 'Why is it worth reading? This starts the discussion.', + alignLabelWithHint: true, ), - const SizedBox(height: 24), + ), + const SizedBox(height: 16), FilledButton( onPressed: _submitting ? null : _submit, child: _submitting ? const SizedBox( height: 20, width: 20, - child: CircularProgressIndicator(strokeWidth: 2), + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), ) - : const Text('Submit'), + : const Text('Share'), ), ], ), @@ -148,25 +180,3 @@ class _SubmitScreenState extends ConsumerState { ); } } - -class _SignInRequired extends StatelessWidget { - const _SignInRequired({required this.onSignIn}); - - final VoidCallback onSignIn; - - @override - Widget build(BuildContext context) { - return Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.lock_outline, size: 48), - const SizedBox(height: 12), - const Text('Sign in to submit a post.'), - const SizedBox(height: 12), - FilledButton(onPressed: onSignIn, child: const Text('Sign in')), - ], - ), - ); - } -} diff --git a/lib/features/thread/data/thread_repository.dart b/lib/features/thread/data/thread_repository.dart index 35bf166..ba15a1b 100644 --- a/lib/features/thread/data/thread_repository.dart +++ b/lib/features/thread/data/thread_repository.dart @@ -1,7 +1,12 @@ +import 'package:appwrite/appwrite.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../core/appwrite/appwrite_providers.dart'; +import '../../../core/config/app_config.dart'; import '../../../core/network/api_client.dart'; +import '../../feed/data/feed_repository.dart'; import '../../feed/domain/post.dart'; +import '../../vote/data/vote_repository.dart'; import '../domain/comment.dart'; /// A post together with its (nested) comment tree. @@ -10,50 +15,83 @@ class ThreadData { final Post post; final List comments; + + /// Every comment, replies included. + int get commentCount => Comment.flatten(comments).length; } -/// Reads a single thread and performs comment mutations against refetch.io. +/// The most comments a thread loads (the web's `MAX_THREAD_COMMENTS`). +const maxThreadComments = 500; + +/// Reads a thread from Appwrite (posts and comments are public-read) and +/// writes comments through the app API. class ThreadRepository { - ThreadRepository(this._api); + ThreadRepository(this._tables, this._feed, this._api, this._votes); + final TablesDB _tables; + final FeedRepository _feed; final ApiClient _api; + final VoteRepository _votes; - /// Loads the post header and its nested comments concurrently. - Future load(String postId) async { - final results = await Future.wait([ - _api.get('/api/posts/$postId'), - _api.get('/api/comments', query: {'postId': postId}), - ]); + /// Loads the story and its comments; when [signedIn], also the viewer's + /// votes on them (best effort). + Future load(String postId, {bool signedIn = false}) async { + var (post, list) = await ( + _feed.get(postId), + _tables.listRows( + databaseId: AppConfig.databaseId, + tableId: AppConfig.commentsTableId, + queries: [ + Query.equal('postId', postId), + Query.orderDesc(r'$createdAt'), + Query.limit(maxThreadComments), + Query.select(Comment.fields), + ], + total: false, + ), + ).wait; + final flat = [for (final row in list.rows) Comment.fromRow(row.data)]; - final postEnvelope = results[0] as Map; - final post = Post.fromJson(postEnvelope['post'] as Map); - final comments = Comment.listFromResponse(results[1]); + var votes = const {}; + if (signedIn) { + try { + votes = await _votes.batch([ + (id: post.id, type: 'post'), + for (final c in flat) (id: c.id, type: 'comment'), + ]); + } catch (_) { + // Arrows fall back to "not voted". + } + post = post.withVote(votes[post.id]); + } - return ThreadData(post: post, comments: comments); + return ThreadData( + post: post, + comments: Comment.buildTree(flat, votes: votes), + ); } Future addComment({ required String postId, required String text, - required String userName, String? replyId, }) async { await _api.post( - '/api/comments', - body: { - 'postId': postId, - 'text': text, - 'userName': userName, - 'replyId': ?replyId, - }, + '/api/app/comments', + body: {'postId': postId, 'content': text, 'replyId': ?replyId}, ); } Future deleteComment(String commentId) async { - await _api.delete('/api/comments/$commentId'); + await _api.delete('/api/app/comments/$commentId'); } } final threadRepositoryProvider = Provider((ref) { - return ThreadRepository(ref.watch(apiClientProvider)); + return ThreadRepository( + ref.watch(tablesDbProvider), + ref.watch(feedRepositoryProvider), + ref.watch(apiClientProvider), + ref.watch(voteRepositoryProvider), + ); }); diff --git a/lib/features/thread/domain/comment.dart b/lib/features/thread/domain/comment.dart index f3fabf1..407752b 100644 --- a/lib/features/thread/domain/comment.dart +++ b/lib/features/thread/domain/comment.dart @@ -1,52 +1,121 @@ -/// A comment on a post. The refetch.io `/api/comments` endpoint returns these -/// already nested via the `replies` field. +import '../../../core/format/time_ago.dart' as format; + +/// A comment on a story, read from the Appwrite comments table. Rows are flat +/// (`replyId` points at the parent); [Comment.buildTree] nests them the way the +/// web's `buildCommentTree` does. class Comment { const Comment({ required this.id, required this.author, required this.text, - required this.timeAgo, required this.count, required this.replies, required this.depth, + this.createdAt, this.userId, this.parentId, + this.currentVote, }); final String id; final String author; final String text; - final String timeAgo; final int count; final List replies; final int depth; + final DateTime? createdAt; final String? userId; final String? parentId; - factory Comment.fromJson(Map json) { - final rawReplies = json['replies']; + /// `'up'`, `'down'`, or `null`; filled in from `/api/app/votes`. + final String? currentVote; + + String get timeAgo => createdAt == null ? '' : format.timeAgo(createdAt!); + + /// Columns the thread selects (the web's `COMMENT_FIELDS`, minus the + /// optional ones older databases lack). + static const fields = [ + r'$id', + r'$createdAt', + 'postId', + 'userId', + 'userName', + 'content', + 'replyId', + 'count', + ]; + + factory Comment.fromRow(Map row) { + final userName = row['userName']; + final replyId = row['replyId']; + final count = row['count']; return Comment( - id: json['id'] as String, - author: (json['author'] ?? 'anonymous') as String, - text: (json['text'] ?? '') as String, - timeAgo: (json['timeAgo'] ?? '') as String, - count: json['count'] is num ? (json['count'] as num).toInt() : 0, - userId: json['userId'] as String?, - parentId: json['parentId'] as String?, - depth: json['depth'] is num ? (json['depth'] as num).toInt() : 0, - replies: rawReplies is List - ? rawReplies - .map((e) => Comment.fromJson(e as Map)) - .toList(growable: false) - : const [], + id: '${row[r'$id']}', + author: userName is String && userName.isNotEmpty + ? userName + : 'Anonymous', + text: '${row['content'] ?? ''}', + count: count is num ? count.toInt() : 0, + createdAt: DateTime.tryParse('${row[r'$createdAt'] ?? ''}'), + userId: row['userId'] is String ? row['userId'] as String : null, + parentId: replyId is String && replyId.isNotEmpty ? replyId : null, + depth: 0, + replies: const [], ); } - static List listFromResponse(dynamic data) { - final list = data is Map ? data['comments'] : data; - if (list is! List) return const []; - return list - .map((e) => Comment.fromJson(e as Map)) - .toList(growable: false); + /// Nests flat comments into a reply tree. Top-level comments are oldest + /// first, as are replies; a reply whose parent is gone becomes top-level. + /// [votes] maps comment id → the viewer's vote. + static List buildTree( + List flat, { + Map votes = const {}, + }) { + final byParent = >{}; + final ids = {for (final c in flat) c.id}; + for (final comment in flat) { + final parent = comment.parentId; + final key = parent != null && parent != comment.id && ids.contains(parent) + ? parent + : null; + byParent.putIfAbsent(key, () => []).add(comment); + } + + int oldest(Comment a, Comment b) { + final at = a.createdAt, bt = b.createdAt; + if (at == null || bt == null) return 0; + return at.compareTo(bt); + } + + final visited = {}; + List build(String? parent, int depth) { + final children = [...?byParent[parent]]..sort(oldest); + return [ + for (final c in children) + if (visited.add(c.id)) + Comment( + id: c.id, + author: c.author, + text: c.text, + count: c.count, + createdAt: c.createdAt, + userId: c.userId, + parentId: c.parentId, + currentVote: votes[c.id], + depth: depth, + replies: build(c.id, depth + 1), + ), + ]; + } + + return build(null, 0); + } + + /// Every comment in [tree], depth first. + static Iterable flatten(List tree) sync* { + for (final c in tree) { + yield c; + yield* flatten(c.replies); + } } } diff --git a/lib/features/thread/presentation/comment_tile.dart b/lib/features/thread/presentation/comment_tile.dart index 6bfddf1..ddaa93d 100644 --- a/lib/features/thread/presentation/comment_tile.dart +++ b/lib/features/thread/presentation/comment_tile.dart @@ -1,4 +1,7 @@ import 'package:flutter/material.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; + +import '../../../core/theme/app_theme.dart'; import '../../vote/presentation/vote_buttons.dart'; import '../domain/comment.dart'; @@ -22,7 +25,6 @@ class CommentTile extends StatelessWidget { @override Widget build(BuildContext context) { final theme = Theme.of(context); - final scheme = theme.colorScheme; final indent = _indentPerLevel * (depth.clamp(0, _maxIndentLevels)); return Padding( @@ -35,7 +37,10 @@ class CommentTile extends StatelessWidget { decoration: BoxDecoration( border: depth > 0 ? Border( - left: BorderSide(color: scheme.outlineVariant, width: 2), + left: BorderSide( + color: context.colors.separator, + width: 2, + ), ) : null, ), @@ -46,6 +51,7 @@ class CommentTile extends StatelessWidget { resourceId: comment.id, resourceType: 'comment', fallbackCount: comment.count, + fallbackVote: comment.currentVote, compact: true, ), const SizedBox(width: 8), @@ -57,16 +63,12 @@ class CommentTile extends StatelessWidget { children: [ Text( comment.author, - style: theme.textTheme.labelMedium?.copyWith( - fontWeight: FontWeight.w600, - ), + style: theme.textTheme.labelMedium, ), const SizedBox(width: 8), Text( comment.timeAgo, - style: theme.textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), + style: theme.textTheme.labelSmall, ), ], ), @@ -79,7 +81,7 @@ class CommentTile extends StatelessWidget { minimumSize: const Size(0, 32), visualDensity: VisualDensity.compact, ), - icon: const Icon(Icons.reply, size: 16), + icon: const Icon(LucideIcons.reply, size: 15), label: const Text('Reply'), ), ], @@ -89,11 +91,7 @@ class CommentTile extends StatelessWidget { ), ), for (final reply in comment.replies) - CommentTile( - comment: reply, - onReply: onReply, - depth: depth + 1, - ), + CommentTile(comment: reply, onReply: onReply, depth: depth + 1), ], ), ); diff --git a/lib/features/thread/presentation/thread_controller.dart b/lib/features/thread/presentation/thread_controller.dart index 92c98fc..fa8f7c1 100644 --- a/lib/features/thread/presentation/thread_controller.dart +++ b/lib/features/thread/presentation/thread_controller.dart @@ -1,13 +1,16 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../auth/presentation/auth_controller.dart'; import '../data/thread_repository.dart'; -/// Loads a single thread (post + nested comments) by post id. +/// Loads a single thread (post + nested comments) by post id, with the +/// viewer's votes when signed in. /// /// Invalidate `threadProvider(postId)` after a comment mutation to refresh. final threadProvider = FutureProvider.family(( ref, postId, ) async { - return ref.read(threadRepositoryProvider).load(postId); + final signedIn = ref.watch(currentUserProvider) != null; + return ref.read(threadRepositoryProvider).load(postId, signedIn: signedIn); }); diff --git a/lib/features/thread/presentation/thread_screen.dart b/lib/features/thread/presentation/thread_screen.dart index 3e067d5..7ae15c3 100644 --- a/lib/features/thread/presentation/thread_screen.dart +++ b/lib/features/thread/presentation/thread_screen.dart @@ -1,20 +1,27 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; -import 'package:url_launcher/url_launcher.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import '../../../core/analytics/analytics_providers.dart'; +import '../../../core/analytics/analytics_service.dart'; import '../../../core/network/error_message.dart'; +import '../../../core/share/share_story.dart'; +import '../../../core/theme/app_theme.dart'; +import '../../../core/widgets/empty_state.dart'; import '../../../core/widgets/site_favicon.dart'; import '../../auth/domain/app_user.dart'; import '../../auth/presentation/auth_controller.dart'; import '../../feed/domain/post.dart'; +import '../../feed/presentation/post_card.dart' show openArticle; import '../../vote/presentation/vote_buttons.dart'; import '../data/thread_repository.dart'; import '../domain/comment.dart'; import 'comment_tile.dart'; import 'thread_controller.dart'; -/// Post detail with its nested comment thread and a comment composer. +/// A story with its comment thread and a comment composer. class ThreadScreen extends ConsumerWidget { const ThreadScreen({super.key, required this.postId}); @@ -25,30 +32,70 @@ class ThreadScreen extends ConsumerWidget { final async = ref.watch(threadProvider(postId)); final user = ref.watch(currentUserProvider); + ref.listen(threadProvider(postId), (previous, next) { + if (next.hasError && !next.isLoading) { + ref + .read(analyticsProvider) + .track( + AnalyticsEvents.threadLoadFailed, + props: {'post_id': postId, 'reason': errorKind(next.error)}, + ); + } + }); + return Scaffold( - appBar: AppBar(title: const Text('Thread')), + appBar: AppBar( + actions: [ + if (async.value case final thread?) + Builder( + builder: (buttonContext) => IconButton( + tooltip: 'Share', + icon: const Icon(LucideIcons.share, size: 22), + onPressed: () => shareStory( + buttonContext, + ref, + thread.post, + source: 'thread', + ), + ), + ), + const SizedBox(width: 4), + ], + ), floatingActionButton: async.hasValue ? FloatingActionButton.extended( onPressed: () => _composeComment(context, ref, user: user), - icon: const Icon(Icons.add_comment_outlined), + icon: const Icon(LucideIcons.messageCircle, size: 20), label: const Text('Comment'), ) : null, body: async.when( loading: () => const Center(child: CircularProgressIndicator()), - error: (error, _) => _ThreadError( - message: messageForError(error, fallback: 'Failed to load thread.'), - onRetry: () => ref.invalidate(threadProvider(postId)), + error: (error, _) => EmptyState( + icon: errorKind(error) == 'network' + ? LucideIcons.wifiOff + : LucideIcons.circleAlert, + title: "Couldn't load this story", + message: messageForError( + error, + fallback: 'Something went wrong. Please try again.', + ), + detail: kDebugMode ? detailForError(error) : null, + action: OutlinedButton( + onPressed: () => ref.invalidate(threadProvider(postId)), + child: const Text('Try again'), + ), ), data: (thread) => RefreshIndicator( onRefresh: () async => ref.invalidate(threadProvider(postId)), child: ListView( - padding: const EdgeInsets.only(bottom: 96), + padding: const EdgeInsets.fromLTRB(12, 4, 12, 96), children: [ - _PostHeader(post: thread.post), - const Divider(height: 1), + Card(child: _PostHeader(post: thread.post)), + const SizedBox(height: 20), _CommentsSection( comments: thread.comments, + total: thread.commentCount, onReply: (parent) => _composeComment(context, ref, user: user, parent: parent), ), @@ -73,9 +120,8 @@ class ThreadScreen extends ConsumerWidget { final text = await showModalBottomSheet( context: context, isScrollControlled: true, - builder: (context) => _CommentComposer( - replyingTo: parent?.author, - ), + showDragHandle: true, + builder: (context) => _CommentComposer(replyingTo: parent?.author), ); if (text == null || text.trim().isEmpty || !context.mounted) return; @@ -83,11 +129,12 @@ class ThreadScreen extends ConsumerWidget { try { await ref .read(threadRepositoryProvider) - .addComment( - postId: postId, - text: text.trim(), - userName: user.displayName, - replyId: parent?.id, + .addComment(postId: postId, text: text.trim(), replyId: parent?.id); + ref + .read(analyticsProvider) + .track( + AnalyticsEvents.commentPosted, + props: {'post_id': postId, 'is_reply': parent != null}, ); ref.invalidate(threadProvider(postId)); } catch (error) { @@ -102,18 +149,24 @@ class ThreadScreen extends ConsumerWidget { } } -class _PostHeader extends StatelessWidget { +class _PostHeader extends ConsumerWidget { const _PostHeader({required this.post}); final Post post; @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); - final scheme = theme.colorScheme; + final c = context.colors; + + final meta = [ + 'by ${post.author}', + if (post.timeAgo != null) post.timeAgo!, + if (post.readingTime != null) '${post.readingTime} min read', + ].join(' · '); return Padding( - padding: const EdgeInsets.all(16), + padding: const EdgeInsets.fromLTRB(12, 16, 16, 16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -126,100 +179,133 @@ class _PostHeader extends StatelessWidget { fallbackCount: post.count, fallbackVote: post.currentVote, ), - const SizedBox(width: 12), - SiteFavicon(domain: post.link ?? post.domain, size: 32), - const SizedBox(width: 12), + const SizedBox(width: 10), Expanded( - child: Text( - post.title, - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w700, - ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (post.domain.isNotEmpty) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + children: [ + SiteFavicon( + domain: post.link ?? post.domain, + size: 18, + ), + const SizedBox(width: 6), + Flexible( + child: Text( + post.domain, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.labelMedium?.copyWith( + color: c.brandText, + ), + ), + ), + ], + ), + ), + Text(post.title, style: theme.textTheme.headlineSmall), + const SizedBox(height: 8), + Text(meta, style: theme.textTheme.bodySmall), + ], ), ), ], ), - const SizedBox(height: 12), - Text( - 'by ${post.author}' - '${post.timeAgo != null ? ' · ${post.timeAgo}' : ''}' - '${post.domain.isNotEmpty ? ' · ${post.domain}' : ''}', - style: theme.textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - if (post.tldr != null && post.tldr!.isNotEmpty) ...[ - const SizedBox(height: 12), + if (post.tldr != null) ...[ + const SizedBox(height: 16), Container( - padding: const EdgeInsets.all(12), + width: double.infinity, + padding: const EdgeInsets.all(14), decoration: BoxDecoration( - color: scheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(8), + color: c.brandTint, + borderRadius: BorderRadius.circular(AppTheme.controlRadius), ), - child: Text( - post.tldr!, - style: theme.textTheme.bodyMedium, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // DESIGN.md: label AI-generated content in words. + Text( + 'Summary, generated by AI', + style: theme.textTheme.labelMedium?.copyWith( + color: c.brandText, + ), + ), + const SizedBox(height: 6), + Text(post.tldr!, style: theme.textTheme.bodyMedium), + ], ), ), ], - if (post.description != null && post.description!.isNotEmpty) ...[ - const SizedBox(height: 12), + if (post.description != null && post.tldr == null) ...[ + const SizedBox(height: 16), Text(post.description!, style: theme.textTheme.bodyMedium), ], if (post.link != null) ...[ - const SizedBox(height: 12), - OutlinedButton.icon( - onPressed: () => _openLink(context, post.link!), - icon: const Icon(Icons.open_in_new, size: 18), - label: const Text('Open link'), + const SizedBox(height: 16), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: () => + openArticle(context, ref, post, source: 'thread'), + icon: const Icon(LucideIcons.externalLink, size: 18), + label: const Text('Read article'), + ), ), ], ], ), ); } - - Future _openLink(BuildContext context, String url) async { - final uri = Uri.tryParse(url); - final messenger = ScaffoldMessenger.of(context); - if (uri == null || - !await launchUrl(uri, mode: LaunchMode.externalApplication)) { - messenger.showSnackBar( - const SnackBar(content: Text('Could not open the link.')), - ); - } - } } class _CommentsSection extends StatelessWidget { - const _CommentsSection({required this.comments, required this.onReply}); + const _CommentsSection({ + required this.comments, + required this.total, + required this.onReply, + }); final List comments; + final int total; final void Function(Comment parent) onReply; @override Widget build(BuildContext context) { if (comments.isEmpty) { return const Padding( - padding: EdgeInsets.all(32), - child: Center(child: Text('No comments yet. Be the first!')), + padding: EdgeInsets.only(top: 24), + child: EmptyState( + icon: LucideIcons.messagesSquare, + title: 'No comments yet', + message: 'Start the conversation.', + ), ); } return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + padding: const EdgeInsets.fromLTRB(8, 0, 8, 8), child: Text( - '${comments.length} ${comments.length == 1 ? 'comment' : 'comments'}', - style: Theme.of(context).textTheme.titleSmall, + '$total ${total == 1 ? 'comment' : 'comments'}', + style: Theme.of(context).textTheme.titleLarge, ), ), - for (final comment in comments) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 8), - child: CommentTile(comment: comment, onReply: onReply), + Card( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final comment in comments) + CommentTile(comment: comment, onReply: onReply), + ], + ), ), + ), ], ); } @@ -247,7 +333,7 @@ class _CommentComposerState extends State<_CommentComposer> { Widget build(BuildContext context) { final viewInsets = MediaQuery.of(context).viewInsets.bottom; return Padding( - padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + viewInsets), + padding: EdgeInsets.fromLTRB(16, 0, 16, 16 + viewInsets), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, @@ -256,7 +342,7 @@ class _CommentComposerState extends State<_CommentComposer> { widget.replyingTo == null ? 'Add a comment' : 'Reply to ${widget.replyingTo}', - style: Theme.of(context).textTheme.titleMedium, + style: Theme.of(context).textTheme.titleLarge, ), const SizedBox(height: 12), TextField( @@ -264,9 +350,7 @@ class _CommentComposerState extends State<_CommentComposer> { autofocus: true, minLines: 3, maxLines: 6, - decoration: const InputDecoration( - hintText: 'Share your thoughts…', - ), + decoration: const InputDecoration(hintText: 'What do you think?'), ), const SizedBox(height: 12), FilledButton( @@ -278,26 +362,3 @@ class _CommentComposerState extends State<_CommentComposer> { ); } } - -class _ThreadError extends StatelessWidget { - const _ThreadError({required this.message, required this.onRetry}); - - final String message; - final VoidCallback onRetry; - - @override - Widget build(BuildContext context) { - return Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.error_outline, size: 48), - const SizedBox(height: 12), - Text(message), - const SizedBox(height: 12), - OutlinedButton(onPressed: onRetry, child: const Text('Retry')), - ], - ), - ); - } -} diff --git a/lib/features/vote/data/vote_repository.dart b/lib/features/vote/data/vote_repository.dart index 1f622cc..2b2b188 100644 --- a/lib/features/vote/data/vote_repository.dart +++ b/lib/features/vote/data/vote_repository.dart @@ -6,14 +6,16 @@ import '../domain/vote_state.dart'; /// A resource to look up a vote for: a post or a comment. typedef VoteResource = ({String id, String type}); -/// Casts votes and reads vote state via the refetch.io REST API. +/// Casts votes and reads the signed-in person's votes through the app API +/// (`/api/app/vote`, `/api/app/votes`). Votes are private, so they can't be +/// read from Appwrite directly. class VoteRepository { VoteRepository(this._api); final ApiClient _api; - /// Casts (or toggles off) a vote. The server returns the resulting score and - /// the user's resulting vote direction (`null` if the vote was removed). + /// Casts, flips or removes a vote ([voteType] again removes it). The server + /// answers the resulting score and vote. Future vote({ required String resourceId, required String resourceType, @@ -21,45 +23,48 @@ class VoteRepository { }) async { final data = await _api.post( - '/api/vote', + '/api/app/vote', body: { - 'resourceId': resourceId, 'resourceType': resourceType, - 'voteType': voteType, + 'resourceId': resourceId, + 'direction': voteType, }, ) as Map; return VoteState( - count: data['newScore'] is num ? (data['newScore'] as num).toInt() : 0, - currentVote: data['voteType'] as String?, + count: data['count'] is num ? (data['count'] as num).toInt() : 0, + currentVote: data['vote'] as String?, ); } - /// Fetches the user's vote state for many resources at once. - Future> batch(List resources) async { + /// The signed-in person's votes on many resources at once: id → `'up'` or + /// `'down'`. Resources without a vote are left out. + Future> batch(List resources) async { if (resources.isEmpty) return const {}; final data = await _api.post( - '/api/vote/batch', + '/api/app/votes', body: { - 'resources': resources - .map((r) => {'id': r.id, 'type': r.type}) - .toList(), + 'posts': [ + for (final r in resources) + if (r.type == 'post') r.id, + ], + 'comments': [ + for (final r in resources) + if (r.type == 'comment') r.id, + ], }, ) as Map; - final voteMap = data['voteMap']; - if (voteMap is! Map) return const {}; - - return voteMap.map( - (key, value) => MapEntry( - key as String, - VoteState.fromJson(value as Map), - ), - ); + return { + for (final group in ['posts', 'comments']) + if (data[group] is Map) + for (final entry in (data[group] as Map).entries) + if (entry.value is String) '${entry.key}': entry.value as String, + }; } } diff --git a/lib/features/vote/presentation/vote_buttons.dart b/lib/features/vote/presentation/vote_buttons.dart index 8317d72..efa2907 100644 --- a/lib/features/vote/presentation/vote_buttons.dart +++ b/lib/features/vote/presentation/vote_buttons.dart @@ -1,8 +1,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import '../../../core/analytics/analytics_providers.dart'; +import '../../../core/analytics/analytics_service.dart'; import '../../../core/network/error_message.dart'; +import '../../../core/theme/app_theme.dart'; import '../../auth/presentation/auth_controller.dart'; import '../domain/vote_state.dart'; import 'vote_controller.dart'; @@ -32,19 +36,23 @@ class VoteButtons extends ConsumerWidget { final votes = ref.watch(voteControllerProvider); final fallback = VoteState(count: fallbackCount, currentVote: fallbackVote); final state = votes[resourceId] ?? fallback; - final scheme = Theme.of(context).colorScheme; - final size = compact ? 18.0 : 22.0; - - Color colorFor(bool active) => - active ? scheme.primary : scheme.onSurfaceVariant; + final c = context.colors; + final size = compact ? 16.0 : 20.0; + final countColor = state.isUp + ? c.up + : state.isDown + ? c.down + : c.labelSecondary; return Column( mainAxisSize: MainAxisSize.min, children: [ _VoteIcon( - icon: Icons.keyboard_arrow_up_rounded, + icon: LucideIcons.arrowUp, + tooltip: state.isUp ? 'Remove upvote' : 'Upvote', size: size, - color: colorFor(state.isUp), + color: state.isUp ? c.up : c.labelTertiary, + tint: state.isUp ? c.upTint : null, onTap: () => _vote(context, ref, 'up', fallback), ), Text( @@ -52,17 +60,16 @@ class VoteButtons extends ConsumerWidget { style: TextStyle( fontSize: compact ? 12 : 13, fontWeight: FontWeight.w600, - color: state.isUp - ? scheme.primary - : state.isDown - ? scheme.error - : scheme.onSurface, + fontFeatures: const [FontFeature.tabularFigures()], + color: countColor, ), ), _VoteIcon( - icon: Icons.keyboard_arrow_down_rounded, + icon: LucideIcons.arrowDown, + tooltip: state.isDown ? 'Remove downvote' : 'Downvote', size: size, - color: state.isDown ? scheme.error : scheme.onSurfaceVariant, + color: state.isDown ? c.down : c.labelTertiary, + tint: state.isDown ? c.downTint : null, onTap: () => _vote(context, ref, 'down', fallback), ), ], @@ -82,6 +89,7 @@ class VoteButtons extends ConsumerWidget { } final messenger = ScaffoldMessenger.of(context); + final analytics = ref.read(analyticsProvider); try { await ref .read(voteControllerProvider.notifier) @@ -91,6 +99,10 @@ class VoteButtons extends ConsumerWidget { voteType: direction, fallback: fallback, ); + analytics.track( + AnalyticsEvents.voteCast, + props: {'resource_type': resourceType, 'direction': direction}, + ); } catch (error) { messenger.showSnackBar( SnackBar( @@ -106,22 +118,38 @@ class VoteButtons extends ConsumerWidget { class _VoteIcon extends StatelessWidget { const _VoteIcon({ required this.icon, + required this.tooltip, required this.size, required this.color, required this.onTap, + this.tint, }); final IconData icon; + final String tooltip; final double size; final Color color; + final Color? tint; final VoidCallback onTap; @override Widget build(BuildContext context) { - return InkResponse( - onTap: onTap, - radius: size, - child: Icon(icon, size: size + 6, color: color), + final box = size + 14; + return Tooltip( + message: tooltip, + child: Material( + color: tint ?? Colors.transparent, + shape: const CircleBorder(), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: onTap, + child: SizedBox( + width: box, + height: box, + child: Icon(icon, size: size, color: color), + ), + ), + ), ); } } diff --git a/lib/main.dart b/lib/main.dart index ac2e613..395dc58 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,3 +1,5 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -5,5 +7,21 @@ import 'app.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); + _registerFontLicenses(); runApp(const ProviderScope(child: RefetchApp())); } + +/// Inter and Poppins ship under the SIL Open Font License, which asks for the +/// licence to travel with the fonts; it shows in the app's licence page. +void _registerFontLicenses() { + LicenseRegistry.addLicense(() async* { + for (final (family, file) in [ + ('Inter', 'assets/fonts/Inter-OFL.txt'), + ('Poppins', 'assets/fonts/Poppins-OFL.txt'), + ]) { + yield LicenseEntryWithLineBreaks([ + family, + ], await rootBundle.loadString(file)); + } + }); +} diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index 3044364..b7573d3 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -11,6 +11,7 @@ import flutter_local_notifications import flutter_web_auth_2 import package_info_plus import push +import share_plus import shared_preferences_foundation import url_launcher_macos import window_to_front @@ -22,6 +23,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FlutterWebAuth2Plugin.register(with: registry.registrar(forPlugin: "FlutterWebAuth2Plugin")) FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) PushPlugin.register(with: registry.registrar(forPlugin: "PushPlugin")) + SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) WindowToFrontPlugin.register(with: registry.registrar(forPlugin: "WindowToFrontPlugin")) diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json index a2ec33f..96d3fee 100644 --- a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -1,68 +1,68 @@ { - "images" : [ - { - "size" : "16x16", - "idiom" : "mac", - "filename" : "app_icon_16.png", - "scale" : "1x" + "info": { + "version": 1, + "author": "xcode" }, - { - "size" : "16x16", - "idiom" : "mac", - "filename" : "app_icon_32.png", - "scale" : "2x" - }, - { - "size" : "32x32", - "idiom" : "mac", - "filename" : "app_icon_32.png", - "scale" : "1x" - }, - { - "size" : "32x32", - "idiom" : "mac", - "filename" : "app_icon_64.png", - "scale" : "2x" - }, - { - "size" : "128x128", - "idiom" : "mac", - "filename" : "app_icon_128.png", - "scale" : "1x" - }, - { - "size" : "128x128", - "idiom" : "mac", - "filename" : "app_icon_256.png", - "scale" : "2x" - }, - { - "size" : "256x256", - "idiom" : "mac", - "filename" : "app_icon_256.png", - "scale" : "1x" - }, - { - "size" : "256x256", - "idiom" : "mac", - "filename" : "app_icon_512.png", - "scale" : "2x" - }, - { - "size" : "512x512", - "idiom" : "mac", - "filename" : "app_icon_512.png", - "scale" : "1x" - }, - { - "size" : "512x512", - "idiom" : "mac", - "filename" : "app_icon_1024.png", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} + "images": [ + { + "size": "16x16", + "idiom": "mac", + "filename": "app_icon_16.png", + "scale": "1x" + }, + { + "size": "16x16", + "idiom": "mac", + "filename": "app_icon_32.png", + "scale": "2x" + }, + { + "size": "32x32", + "idiom": "mac", + "filename": "app_icon_32.png", + "scale": "1x" + }, + { + "size": "32x32", + "idiom": "mac", + "filename": "app_icon_64.png", + "scale": "2x" + }, + { + "size": "128x128", + "idiom": "mac", + "filename": "app_icon_128.png", + "scale": "1x" + }, + { + "size": "128x128", + "idiom": "mac", + "filename": "app_icon_256.png", + "scale": "2x" + }, + { + "size": "256x256", + "idiom": "mac", + "filename": "app_icon_256.png", + "scale": "1x" + }, + { + "size": "256x256", + "idiom": "mac", + "filename": "app_icon_512.png", + "scale": "2x" + }, + { + "size": "512x512", + "idiom": "mac", + "filename": "app_icon_512.png", + "scale": "1x" + }, + { + "size": "512x512", + "idiom": "mac", + "filename": "app_icon_1024.png", + "scale": "2x" + } + ] +} \ No newline at end of file diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png index 3f0b1c1..16ee7d2 100644 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png index 088ba0f..f3d890a 100644 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png index e22125b..3b12c69 100644 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png index ef9ba25..6cc40ce 100644 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png index 66173fc..3e05bad 100644 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png index 47bbd3b..c6139f0 100644 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png index 42aa454..b4e7ac4 100644 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/pubspec.lock b/pubspec.lock index 5db62f0..60bd527 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -17,14 +17,22 @@ packages: url: "https://pub.dev" source: hosted version: "12.1.0" + ansicolor: + dependency: transitive + description: + name: ansicolor + sha256: "50e982d500bc863e1d703448afdbf9e5a72eb48840a4f766fa361ffd6877055f" + url: "https://pub.dev" + source: hosted + version: "2.0.3" appwrite: dependency: "direct main" description: name: appwrite - sha256: "954e24c094252cc13d2d74fe7e684b0f88de5611e1b110c10217bee889ce2496" + sha256: "7a8090677b56f30acc4510ebe87aff53dcf6fc33938a74c17e54fc7f3f1bc7ed" url: "https://pub.dev" source: hosted - version: "24.2.0" + version: "28.3.0" archive: dependency: transitive description: @@ -65,6 +73,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + charcode: + dependency: transitive + description: + name: charcode + sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a + url: "https://pub.dev" + source: hosted + version: "1.4.0" checked_yaml: dependency: transitive description: @@ -137,6 +153,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.15.0" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6 + url: "https://pub.dev" + source: hosted + version: "0.3.5+5" crypto: dependency: transitive description: @@ -145,6 +169,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.7" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" dbus: dependency: transitive description: @@ -157,26 +189,34 @@ packages: dependency: transitive description: name: desktop_webview_window - sha256: "57cf20d81689d5cbb1adfd0017e96b669398a669d927906073b0e42fc64111c0" + sha256: "20c3ac0f0404f72a0ce76f6f729f4dc656c04747f42e0a38d9553855b1d6012e" url: "https://pub.dev" source: hosted - version: "0.2.3" + version: "0.3.2" device_info_plus: dependency: transitive description: name: device_info_plus - sha256: b4fed1b2835da9d670d7bed7db79ae2a94b0f5ad6312268158a9b5479abbacdd + sha256: ade1c36f8355d6284c98e4a47992ea263887ed3d1acb281e37635dd45f04c4aa url: "https://pub.dev" source: hosted - version: "12.4.0" + version: "13.3.0" device_info_plus_platform_interface: dependency: transitive description: name: device_info_plus_platform_interface - sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f + sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46" url: "https://pub.dev" source: hosted - version: "7.0.3" + version: "8.1.0" + event_bus: + dependency: transitive + description: + name: event_bus + sha256: "1a55e97923769c286d295240048fc180e7b0768902c3c2e869fe059aafa15304" + url: "https://pub.dev" + source: hosted + version: "2.0.1" fake_async: dependency: transitive description: @@ -193,6 +233,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" file: dependency: transitive description: @@ -201,11 +249,56 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.1" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" flutter: dependency: "direct main" description: flutter source: sdk version: "0.0.0" + flutter_background_service: + dependency: transitive + description: + name: flutter_background_service + sha256: "70a1c185b1fa1a44f8f14ecd6c86f6e50366e3562f00b2fa5a54df39b3324d3d" + url: "https://pub.dev" + source: hosted + version: "5.1.0" + flutter_background_service_android: + dependency: transitive + description: + name: flutter_background_service_android + sha256: ca0793d4cd19f1e194a130918401a3d0b1076c81236f7273458ae96987944a87 + url: "https://pub.dev" + source: hosted + version: "6.3.1" + flutter_background_service_ios: + dependency: transitive + description: + name: flutter_background_service_ios + sha256: "6037ffd45c4d019dab0975c7feb1d31012dd697e25edc05505a4a9b0c7dc9fba" + url: "https://pub.dev" + source: hosted + version: "5.0.3" + flutter_background_service_platform_interface: + dependency: transitive + description: + name: flutter_background_service_platform_interface + sha256: ca74aa95789a8304f4d3f57f07ba404faa86bed6e415f83e8edea6ad8b904a41 + url: "https://pub.dev" + source: hosted + version: "5.1.2" + flutter_driver: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" flutter_launcher_icons: dependency: "direct dev" description: @@ -226,34 +319,50 @@ packages: dependency: "direct main" description: name: flutter_local_notifications - sha256: "0d9035862236fe38250fe1644d7ed3b8254e34a21b2c837c9f539fbb3bba5ef1" + sha256: "357be7ff996dc272e2037c69c1bdd5d1bd21172219d55f8bd2e11aeea602e6d3" url: "https://pub.dev" source: hosted - version: "21.0.0" + version: "22.3.1" flutter_local_notifications_linux: dependency: transitive description: name: flutter_local_notifications_linux - sha256: e0f25e243c6c44c825bbbc6b2b2e76f7d9222362adcfe9fd780bf01923c840bd + sha256: "3b89a4bf095fa5f8a99beeabf982c5bd506c3ad25e7b9e61da945e994dc5b615" url: "https://pub.dev" source: hosted - version: "8.0.0" + version: "8.0.2" flutter_local_notifications_platform_interface: dependency: transitive description: name: flutter_local_notifications_platform_interface - sha256: e7db3d5b49c2b7ecc68deba4aaaa67a348f92ee0fef34c8e4b4459dbef0d7307 + sha256: "43c3761d916c9bd3d5c7ebbc44d82f4990329840c0c5d62ad5260cc1b5d399bd" + url: "https://pub.dev" + source: hosted + version: "12.2.0" + flutter_local_notifications_web: + dependency: transitive + description: + name: flutter_local_notifications_web + sha256: "516afaf97a2d1e67a036c6617321b00d205d72f7a67b6eccf936cd565f985878" url: "https://pub.dev" source: hosted - version: "11.0.0" + version: "1.0.0" flutter_local_notifications_windows: dependency: transitive description: name: flutter_local_notifications_windows - sha256: "3a2654ba104fbb52c618ebed9def24ef270228470718c43b3a6afcd5c81bef0c" + sha256: "6f43bdd03b171b7a90f22647506fea33e2bb12294b7c7c7a3d690e960a382945" url: "https://pub.dev" source: hosted - version: "3.0.0" + version: "3.1.1" + flutter_native_splash: + dependency: "direct dev" + description: + name: flutter_native_splash + sha256: "9db4b80b044e9af17cc4b1272137fc7ace0054d879ef8210a76adc34aaf4cdff" + url: "https://pub.dev" + source: hosted + version: "2.4.8" flutter_riverpod: dependency: "direct main" description: @@ -262,6 +371,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.3.1" + flutter_svg: + dependency: "direct main" + description: + name: flutter_svg + sha256: "100c19dcc4ff60083e95a44a6f44f3a1bb887d353c5d86f6a9b688aa3cb46236" + url: "https://pub.dev" + source: hosted + version: "2.3.2" flutter_test: dependency: "direct dev" description: flutter @@ -271,10 +388,10 @@ packages: dependency: transitive description: name: flutter_web_auth_2 - sha256: d354998934ddc338e69b999b2abaeb33c6fd09999d3a5f92ead1a6b49b49712e + sha256: a7655829251ee63aae64a748f8512f36670d8eba4657b0055cdf5ef304a9d164 url: "https://pub.dev" source: hosted - version: "5.0.2" + version: "5.1.0" flutter_web_auth_2_platform_interface: dependency: transitive description: @@ -296,6 +413,11 @@ packages: url: "https://pub.dev" source: hosted version: "4.0.0" + fuchsia_remote_debug_protocol: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" glob: dependency: transitive description: @@ -320,6 +442,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.0" + html: + dependency: transitive + description: + name: html + sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" + url: "https://pub.dev" + source: hosted + version: "0.15.7" http: dependency: "direct main" description: @@ -352,6 +482,11 @@ packages: url: "https://pub.dev" source: hosted version: "4.9.2" + integration_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" io: dependency: transitive description: @@ -424,14 +559,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.3.0" + lucide_icons_flutter: + dependency: "direct main" + description: + name: lucide_icons_flutter + sha256: "96719b024196fd2fdb395f490e7e91bd6d2474f43f62800eb62920868e777ac5" + url: "https://pub.dev" + source: hosted + version: "4.0.2" matcher: dependency: transitive description: name: matcher - sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.19" + version: "0.12.20" material_color_utilities: dependency: transitive description: @@ -444,10 +587,10 @@ packages: dependency: transitive description: name: meta - sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "1.18.0" + version: "1.19.0" mime: dependency: transitive description: @@ -464,6 +607,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.5" + mqtt5_client: + dependency: transitive + description: + name: mqtt5_client + sha256: a716e6bddc4715cd585ac7147383080dffafb6b7d55f370dc596b38c85e8c557 + url: "https://pub.dev" + source: hosted + version: "4.17.1" node_preamble: dependency: transitive description: @@ -492,18 +643,18 @@ packages: dependency: transitive description: name: package_info_plus - sha256: "468c26b4254ab01979fa5e4a98cb343ea3631b9acee6f21028997419a80e1a20" + sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908" url: "https://pub.dev" source: hosted - version: "9.0.1" + version: "10.2.2" package_info_plus_platform_interface: dependency: transitive description: name: package_info_plus_platform_interface - sha256: "202a487f08836a592a6bd4f901ac69b3a8f146af552bbd14407b6b41e1c3f086" + sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4 url: "https://pub.dev" source: hosted - version: "3.2.1" + version: "4.1.0" path: dependency: transitive description: @@ -512,14 +663,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.9.1" + path_parsing: + dependency: transitive + description: + name: path_parsing + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" + url: "https://pub.dev" + source: hosted + version: "1.1.0" path_provider: dependency: transitive description: name: path_provider - sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 url: "https://pub.dev" source: hosted - version: "2.1.5" + version: "2.1.6" path_provider_android: dependency: transitive description: @@ -648,6 +807,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.5.2" + process: + dependency: transitive + description: + name: process + sha256: "4242ba3508d37e01808bdf71ad1d5bb93a8d671bf2e7450e6b1b353fb0808891" + url: "https://pub.dev" + source: hosted + version: "5.0.6" pub_semver: dependency: transitive description: @@ -680,6 +847,22 @@ packages: url: "https://pub.dev" source: hosted version: "3.2.1" + share_plus: + dependency: "direct main" + description: + name: share_plus + sha256: db40767f130189d53f3ae8a6393c217ff4a492da1baff718a9873679c0c00224 + url: "https://pub.dev" + source: hosted + version: "13.3.1" + share_plus_platform_interface: + dependency: transitive + description: + name: share_plus_platform_interface + sha256: "365ef7379fc22507256adda3385152942ffce08935452bc972c2e52a0bebae41" + url: "https://pub.dev" + source: hosted + version: "7.2.0" shared_preferences: dependency: "direct main" description: @@ -829,6 +1012,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + sync_http: + dependency: transitive + description: + name: sync_http + sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961" + url: "https://pub.dev" + source: hosted + version: "0.3.1" term_glyph: dependency: transitive description: @@ -841,26 +1032,26 @@ packages: dependency: transitive description: name: test - sha256: "8d9ceddbab833f180fbefed08afa76d7c03513dfdba87ffcec2718b02bbcbf20" + sha256: ca578dc12bb8b2f40b67b7d3bd2fac4f31c01a6ff7130a14e2597b919934507f url: "https://pub.dev" source: hosted - version: "1.31.0" + version: "1.31.1" test_api: dependency: transitive description: name: test_api - sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" url: "https://pub.dev" source: hosted - version: "0.7.11" + version: "0.7.12" test_core: dependency: transitive description: name: test_core - sha256: "1991d4cfe85d5043241acac92962c3977c8d2f2add1ee73130c7b286417d1d34" + sha256: d2e98ec12998368dc59ddd47ab709f2cd55acd6b66dc7db764455a44082f4bc5 url: "https://pub.dev" source: hosted - version: "0.6.17" + version: "0.6.18" timezone: dependency: transitive description: @@ -877,6 +1068,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + universal_html: + dependency: transitive + description: + name: universal_html + sha256: c0bcae5c733c60f26c7dfc88b10b0fd27cbcc45cb7492311cdaa6067e21c9cd4 + url: "https://pub.dev" + source: hosted + version: "2.3.0" universal_io: dependency: transitive description: @@ -949,14 +1148,46 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.5" + uuid: + dependency: transitive + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.dev" + source: hosted + version: "4.6.0" + vector_graphics: + dependency: transitive + description: + name: vector_graphics + sha256: "82885f6ac633044e7a4e4d8d745724a67aa0dc50af5d8a81ec29379f63c29035" + url: "https://pub.dev" + source: hosted + version: "1.2.6" + vector_graphics_codec: + dependency: transitive + description: + name: vector_graphics_codec + sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146" + url: "https://pub.dev" + source: hosted + version: "1.1.13" + vector_graphics_compiler: + dependency: transitive + description: + name: vector_graphics_compiler + sha256: "4c9d2e7121eea8b4f160e6e435900a0ae7214cfc97c2d6cf84c25532b789b50d" + url: "https://pub.dev" + source: hosted + version: "1.3.4" vector_math: dependency: transitive description: name: vector_math - sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.4.4" vm_service: dependency: transitive description: @@ -997,6 +1228,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.3" + webdriver: + dependency: transitive + description: + name: webdriver + sha256: "28b82ec894fed45dd71c23ba62d1af973ed97dd59a4f5790a4d38b0b13e5657e" + url: "https://pub.dev" + source: hosted + version: "3.2.0" webkit_inspection_protocol: dependency: transitive description: @@ -1009,18 +1248,18 @@ packages: dependency: transitive description: name: win32 - sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d url: "https://pub.dev" source: hosted - version: "5.15.0" + version: "6.4.0" win32_registry: dependency: transitive description: name: win32_registry - sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae" + sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904" url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "3.0.3" window_to_front: dependency: transitive description: @@ -1055,4 +1294,4 @@ packages: version: "3.1.3" sdks: dart: ">=3.12.0 <4.0.0" - flutter: ">=3.38.4" + flutter: ">=3.41.0" diff --git a/pubspec.yaml b/pubspec.yaml index 24cbbdf..40d40e6 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,40 +1,71 @@ name: refetch -description: "A new Flutter project." +description: "Refetch: the front page for builders. Open-source alternative to YC-controlled HN." publish_to: 'none' -version: 0.1.0+5 +version: 0.2.0+6 environment: sdk: ^3.12.0 dependencies: - appwrite: ^24.2.0 + appwrite: ^28.3.0 flutter: sdk: flutter - flutter_local_notifications: ^21.0.0 + flutter_local_notifications: ^22.3.1 flutter_riverpod: ^3.3.1 + flutter_svg: ^2.3.2 go_router: ^17.2.3 http: ^1.6.0 + lucide_icons_flutter: ^4.0.2 permission_handler: ^12.0.2 push: ^3.3.3 + share_plus: ^13.3.1 shared_preferences: ^2.5.5 url_launcher: ^6.3.2 dev_dependencies: flutter_test: sdk: flutter + # Drives the store-screenshot capture (integration_test/screenshot_test.dart). + integration_test: + sdk: flutter flutter_launcher_icons: ^0.14.4 flutter_lints: ^6.0.0 mocktail: ^1.0.5 + flutter_native_splash: ^2.4.8 flutter: uses-material-design: true + assets: + - assets/brand/logo-mark.svg + - assets/brand/logo-wordmark.svg + - assets/fonts/Inter-OFL.txt + - assets/fonts/Poppins-OFL.txt + fonts: + # Body text on Android, Windows and Linux (refetch.io --font-sans; Apple + # platforms use the system font there, as the site does). + - family: Inter + fonts: + - asset: assets/fonts/Inter-Regular.ttf + - asset: assets/fonts/Inter-Medium.ttf + weight: 500 + - asset: assets/fonts/Inter-SemiBold.ttf + weight: 600 + - asset: assets/fonts/Inter-Bold.ttf + weight: 700 + # Titles (refetch.io --font-display, the wordmark's typeface). + - family: Poppins + fonts: + - asset: assets/fonts/Poppins-SemiBold.ttf + weight: 600 + - asset: assets/fonts/Poppins-Bold.ttf + weight: 700 flutter_launcher_icons: image_path: "assets/icon/icon.png" android: true - adaptive_icon_background: "#5A00FF" + adaptive_icon_background: "#FFFFFF" adaptive_icon_foreground: "assets/icon/icon_foreground.png" - adaptive_icon_monochrome: "assets/icon/icon_foreground.png" + adaptive_icon_monochrome: "assets/icon/icon_monochrome.png" ios: true remove_alpha_ios: true macos: @@ -47,5 +78,19 @@ flutter_launcher_icons: web: generate: true image_path: "assets/icon/icon.png" - background_color: "#5A00FF" - theme_color: "#5A00FF" + background_color: "#F5F5F7" + theme_color: "#4E1CB3" + +# Launch screen: the logo mark on the app background (refetch.io --bg). +# Regenerate with `dart run flutter_native_splash:create`. +flutter_native_splash: + color: "#F5F5F7" + image: assets/brand/splash_mark.png + color_dark: "#0E0D13" + image_dark: assets/brand/splash_mark.png + android_12: + color: "#F5F5F7" + image: assets/brand/splash_mark.png + color_dark: "#0E0D13" + image_dark: assets/brand/splash_mark.png + web: false diff --git a/screenshots/README.md b/screenshots/README.md new file mode 100644 index 0000000..92f4861 --- /dev/null +++ b/screenshots/README.md @@ -0,0 +1,44 @@ +# Store screenshots + +Every store listing image is built by a GitHub workflow and arrives as a pull +request (ported from momo-pasal). The copy and styling live in +`headlines.json`. + +| Step | What runs | +|---|---| +| Capture | `integration_test/screenshot_test.dart` with `flutter drive`, on a CI emulator or simulator. It reads the live feed from Appwrite; analytics is compiled out. | +| Job | `tool/screenshot_job.dart` turns `headlines.json` into a moksha job | +| Render | [moksha](https://github.com/lohanidamodar/moksha): device frame, Refetch purple background, Poppins headline, Inter subhead, at the exact store size, checked against store rules (no alpha, Play's 2:1 limit, Apple sizes) | +| Review | the workflow opens a PR; the diff is the review | + +## The workflows + +Manual only (Actions › Screenshots (Android) / Screenshots (iOS)): + +| Family | Captured on | Output | Goes to | +|---|---|---|---| +| Android phone | `pixel_6` emulator, API 34 | 1080x1920 | `android/fastlane/metadata/android//images/phoneScreenshots/` | +| iPhone 6.9" | iPhone 17 Pro Max simulator | 1320x2868 | `ios/fastlane/screenshots/framed//iphone_*.png` | +| iPad 13" | iPad Pro 13" simulator | 2064x2752 | `ios/fastlane/screenshots/framed//ipad_*.png` | + +Those are the folders the fastlane `upload_screenshots` / `upload_listing` +lanes read, so a merged PR is in the release path. + +## Changing the copy or the screens + +Edit `headlines.json`; scene ids match the names the test captures +(`top`, `thread`, `new`, `account`). Add a screen in the test and a scene here. + +## Locally + +```sh +flutter drive --driver=test_driver/integration_test.dart \ + --target=integration_test/screenshot_test.dart \ + --dart-define=ANALYTICS_PROPERTY_ID= -d +dart run tool/screenshot_job.dart --asset-type android-phone-screenshot \ + --size-id android-phone --out build/job.json +# in a moksha checkout (clone it on Linux/WSL: a Windows checkout's CRLF +# line endings break its scripts) +npm ci && npm run render -- --job /build/job.json \ + --images /build/screenshots --out /build/rendered +``` diff --git a/screenshots/headlines.json b/screenshots/headlines.json new file mode 100644 index 0000000..d05a901 --- /dev/null +++ b/screenshots/headlines.json @@ -0,0 +1,48 @@ +{ + "_comment": [ + "Store screenshot copy and styling, in one place because every store reads", + "it. tool/screenshot_job.dart turns this into a moksha job; moksha renders", + "the finished images and checks them against each store's upload rules.", + "", + "Scene ids match the capture names integration_test/screenshot_test.dart", + "writes. Add a screen there and add it here.", + "", + "Background is the Refetch purple (#4E1CB3, docs/BRANDING.md); text is", + "white. Headlines use Poppins (the wordmark's face), subheads Inter, as on", + "refetch.io. These are store copy, not UI strings: write the benefit." + ], + + "background": { "type": "solid", "id": "custom", "color": "#4E1CB3" }, + + "layouts": ["hero-center", "tilt-right", "float-up", "tilt-left"], + + "fonts": { + "headline": "Poppins", + "subhead": "Inter" + }, + + "textColor": "#FFFFFF", + + "scenes": [ + { + "id": "top", + "headline": { "en-US": "The front page for builders" }, + "subhead": { "en-US": "Today's best tech stories, ranked in the open" } + }, + { + "id": "thread", + "headline": { "en-US": "Read the room" }, + "subhead": { "en-US": "A quick summary, then the discussion" } + }, + { + "id": "new", + "headline": { "en-US": "Fresh from the source" }, + "subhead": { "en-US": "New stories from trusted tech sites, all day" } + }, + { + "id": "account", + "headline": { "en-US": "Your data, your call" }, + "subhead": { "en-US": "Anonymous usage stats, off with one switch" } + } + ] +} diff --git a/test/analytics_test.dart b/test/analytics_test.dart new file mode 100644 index 0000000..acc2772 --- /dev/null +++ b/test/analytics_test.dart @@ -0,0 +1,257 @@ +import 'package:appwrite/appwrite.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:refetch/core/analytics/analytics_providers.dart'; +import 'package:refetch/core/analytics/analytics_service.dart'; +import 'package:refetch/core/analytics/appwrite_analytics.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _FakeClient extends Fake implements Client {} + +/// The SDK's Analytics service with the network call replaced by a recorder, +/// so these tests run the real `Tracking` helper end to end. +class _RecordingAnalytics extends Analytics { + _RecordingAnalytics() : super(_FakeClient()); + + final List> events = []; + + @override + Future createEvent({ + required String propertyId, + required String name, + required String url, + String? domain, + String? referrer, + int? screenWidth, + String? sessionHash, + int? scrollDepth, + int? engagementTime, + List? props, + String? userId, + String? ip, + String? userAgent, + bool? interactive, + }) async { + events.add({ + 'propertyId': propertyId, + 'name': name, + 'url': url, + 'props': props, + 'userId': userId, + 'interactive': interactive, + }); + } +} + +/// Records calls made through the [AnalyticsService] interface. +class _SpyService implements AnalyticsService { + final List calls = []; + + @override + void start() => calls.add('start'); + + @override + void stop() => calls.add('stop'); + + @override + void screenView(String screen, {Map? props}) => + calls.add('screen:$screen'); + + @override + void track(String name, {Map? props}) => + calls.add('track:$name${props == null ? '' : ' $props'}'); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('AppwriteAnalyticsService (via the SDK Tracking helper)', () { + late _RecordingAnalytics analytics; + late AppwriteAnalyticsService service; + + setUp(() { + analytics = _RecordingAnalytics(); + service = AppwriteAnalyticsService(Tracking(analytics, 'prop-123')); + }); + + tearDown(() => service.stop()); + + test('track sends the name, flattened props and no user id', () async { + service.track( + 'story_shared', + props: {'post_id': 'p1', 'source': 'feed', 'skip': null}, + ); + await Future.delayed(Duration.zero); + + final event = analytics.events.single; + expect(event['propertyId'], 'prop-123'); + expect(event['name'], 'story_shared'); + expect(event['props'], ['post_id', 'p1', 'source', 'feed']); + expect(event['userId'], isNull); + expect(event['url'], startsWith('app://')); + }); + + test( + 'screenView becomes screen_view with the screen as the URL path', + () async { + service.screenView('thread'); + await Future.delayed(Duration.zero); + + final event = analytics.events.single; + expect(event['name'], 'screen_view'); + expect(event['url'], endsWith('/thread')); + expect(event['props'], containsAllInOrder(['screen', 'thread'])); + }, + ); + + test( + 'start reports backgrounding as non-interactive; stop ends it', + () async { + final binding = TestWidgetsFlutterBinding.instance; + service.start(); + binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + await Future.delayed(Duration.zero); + expect(analytics.events.map((e) => e['name']), ['app_backgrounded']); + expect(analytics.events.single['interactive'], isFalse); + + service.stop(); + binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await Future.delayed(Duration.zero); + expect(analytics.events, hasLength(1), reason: 'nothing after stop'); + }, + ); + }); + + group('ConsentedAnalytics', () { + test('forwards only while enabled', () { + final spy = _SpyService(); + final analytics = ConsentedAnalytics(spy, enabled: false); + + analytics.track('a'); + analytics.screenView('feed'); + expect(spy.calls, isEmpty); + + analytics.enabled = true; + analytics.track('b'); + expect(spy.calls, ['track:b']); + }); + + test('holds events until consent is known, then sends them', () { + final spy = _SpyService(); + final analytics = ConsentedAnalytics(spy, enabled: null)..start(); + analytics.screenView('feed'); + expect(spy.calls, isEmpty, reason: 'nothing leaves before we know'); + + analytics.enabled = true; + expect(spy.calls, ['start', 'screen:feed']); + }); + + test('held events are dropped when consent turns out to be off', () { + final spy = _SpyService(); + final analytics = ConsentedAnalytics(spy, enabled: null)..start(); + analytics.screenView('feed'); + analytics.enabled = false; + analytics.enabled = true; + expect(spy.calls, ['start'], reason: 'the held view was dropped'); + }); + + test('the hold is bounded', () { + final spy = _SpyService(); + final analytics = ConsentedAnalytics(spy, enabled: null); + for (var i = 0; i < 50; i++) { + analytics.track('e$i'); + } + analytics.enabled = true; + expect(spy.calls, hasLength(ConsentedAnalytics.maxPending)); + }); + + test('turning it off stops automatic events', () { + final spy = _SpyService(); + final analytics = ConsentedAnalytics(spy)..start(); + analytics.enabled = false; + expect(spy.calls, ['start', 'stop']); + }); + }); + + test('cleanProps drops nulls and caps the pair count', () { + final many = {for (var i = 0; i < 40; i++) 'k$i': i}; + expect(cleanProps(many), hasLength(15)); + expect(cleanProps({'a': null, 'b': 1}), {'b': 1}); + expect(cleanProps(null), isEmpty); + }); + + group('AnalyticsRouteObserver', () { + test('sends named page routes and ignores unnamed ones', () { + final spy = _SpyService(); + final observer = AnalyticsRouteObserver(spy); + final feed = MaterialPageRoute( + settings: const RouteSettings(name: 'feed'), + builder: (_) => const SizedBox(), + ); + final thread = MaterialPageRoute( + settings: const RouteSettings(name: 'thread'), + builder: (_) => const SizedBox(), + ); + final anonymous = MaterialPageRoute( + builder: (_) => const SizedBox(), + ); + + observer.didPush(feed, null); + observer.didPush(thread, feed); + observer.didPop(thread, feed); + observer.didPush(anonymous, feed); + + expect(spy.calls, ['screen:feed', 'screen:thread', 'screen:feed']); + }); + }); + + group('analytics consent', () { + ProviderContainer containerWith(_SpyService spy) { + final container = ProviderContainer( + overrides: [analyticsBackendProvider.overrideWithValue(spy)], + ); + addTearDown(container.dispose); + return container; + } + + test('is on by default', () async { + SharedPreferences.setMockInitialValues({}); + final spy = _SpyService(); + final container = containerWith(spy); + + expect(await container.read(analyticsConsentProvider.future), isTrue); + container.read(analyticsProvider).track('x'); + expect(spy.calls, ['track:x']); + }); + + test('a saved opt-out is honoured before anything is sent', () async { + SharedPreferences.setMockInitialValues({'analytics.enabled': false}); + final spy = _SpyService(); + final container = containerWith(spy); + final analytics = container.read(analyticsProvider)..start(); + + analytics.track('early'); + expect(await container.read(analyticsConsentProvider.future), isFalse); + analytics.track('later'); + expect(spy.calls, isEmpty); + }); + + test('opting out persists, sends nothing; opting in is recorded', () async { + SharedPreferences.setMockInitialValues({}); + final spy = _SpyService(); + final container = containerWith(spy); + await container.read(analyticsConsentProvider.future); + + await container.read(analyticsConsentProvider.notifier).setEnabled(false); + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getBool('analytics.enabled'), isFalse); + container.read(analyticsProvider).track('dropped'); + expect(spy.calls, isEmpty); + + await container.read(analyticsConsentProvider.notifier).setEnabled(true); + expect(spy.calls.single, startsWith('track:setting_changed')); + expect(prefs.getBool('analytics.enabled'), isTrue); + }); + }); +} diff --git a/test/api_client_test.dart b/test/api_client_test.dart index 1be04ce..d7d8e97 100644 --- a/test/api_client_test.dart +++ b/test/api_client_test.dart @@ -28,7 +28,9 @@ void main() { jwtService: jwt, httpClient: httpClient, ); - when(() => account.createJWT()).thenAnswer((_) async => models.Jwt(jwt: 't')); + when( + () => account.createJWT(), + ).thenAnswer((_) async => models.Jwt(jwt: 't')); }); test('clears the JWT and retries once on 401, then succeeds', () async { @@ -55,40 +57,87 @@ void main() { verify(() => account.createJWT()).called(2); }); - test('throws ApiException with the server message on non-401 errors', () async { - when( + test( + 'throws ApiException with the server message on non-401 errors', + () async { + when( + () => httpClient.post( + any(), + headers: any(named: 'headers'), + body: any(named: 'body'), + encoding: any(named: 'encoding'), + ), + ).thenAnswer((_) async => http.Response('{"message":"nope"}', 400)); + + await expectLater( + api.post('/api/vote', body: const {}), + throwsA( + isA() + .having((e) => e.statusCode, 'statusCode', 400) + .having((e) => e.message, 'message', 'nope'), + ), + ); + }, + ); + + test('unauthenticated request without a session fails fast', () async { + when(() => account.createJWT()).thenThrow(AppwriteException('no session')); + + await expectLater( + api.post('/api/vote', body: const {}), + throwsA(isA().having((e) => e.statusCode, 'code', 401)), + ); + verifyNever( () => httpClient.post( any(), headers: any(named: 'headers'), body: any(named: 'body'), encoding: any(named: 'encoding'), ), - ).thenAnswer((_) async => http.Response('{"message":"nope"}', 400)); + ); + }); - await expectLater( - api.post('/api/vote', body: const {}), - throwsA( - isA() - .having((e) => e.statusCode, 'statusCode', 400) - .having((e) => e.message, 'message', 'nope'), + test('unwraps the app API data envelope', () async { + when( + () => httpClient.post( + any(), + headers: any(named: 'headers'), + body: any(named: 'body'), + encoding: any(named: 'encoding'), ), + ).thenAnswer( + (_) async => http.Response('{"data":{"vote":"up","count":4}}', 200), ); - }); - test('unauthenticated request without a session fails fast', () async { - when(() => account.createJWT()).thenThrow(AppwriteException('no session')); + expect(await api.post('/api/app/vote'), {'vote': 'up', 'count': 4}); + }); - await expectLater( - api.post('/api/vote', body: const {}), - throwsA(isA().having((e) => e.statusCode, 'code', 401)), - ); - verifyNever( + test('reads the app API error field', () async { + when( () => httpClient.post( any(), headers: any(named: 'headers'), body: any(named: 'body'), encoding: any(named: 'encoding'), ), + ).thenAnswer( + (_) async => http.Response( + '{"error":"This story has already been shared.","code":"duplicate"}', + 409, + ), + ); + + await expectLater( + api.post('/api/app/submit'), + throwsA( + isA() + .having((e) => e.statusCode, 'statusCode', 409) + .having( + (e) => e.message, + 'message', + 'This story has already been shared.', + ), + ), ); }); } diff --git a/test/comment_test.dart b/test/comment_test.dart index 21d3f34..ab9465d 100644 --- a/test/comment_test.dart +++ b/test/comment_test.dart @@ -1,44 +1,68 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:refetch/features/thread/domain/comment.dart'; -void main() { - test('Comment.fromJson parses nested replies recursively', () { - final comment = Comment.fromJson({ - 'id': 'root', - 'author': 'alice', - 'text': 'top level', - 'timeAgo': '1 hour ago', - 'count': 3, - 'depth': 0, - 'replies': [ - { - 'id': 'child', - 'author': 'bob', - 'text': 'a reply', - 'timeAgo': '30 minutes ago', - 'count': 1, - 'depth': 1, - 'parentId': 'root', - 'replies': const [], - }, - ], +Comment _row(String id, {String? reply, required int minute, int count = 0}) => + Comment.fromRow({ + r'$id': id, + r'$createdAt': DateTime.utc(2026, 11, 8, 8, minute).toIso8601String(), + 'userName': 'user-$id', + 'content': 'text $id', + 'replyId': reply ?? '', + 'count': count, }); - expect(comment.id, 'root'); - expect(comment.count, 3); - expect(comment.replies, hasLength(1)); - expect(comment.replies.first.id, 'child'); - expect(comment.replies.first.parentId, 'root'); - expect(comment.replies.first.replies, isEmpty); +void main() { + test('Comment.fromRow maps a comments-table row', () { + final c = _row('a', minute: 5, count: 3); + expect(c.id, 'a'); + expect(c.author, 'user-a'); + expect(c.text, 'text a'); + expect(c.count, 3); + expect(c.parentId, isNull, reason: 'an empty replyId means top level'); + expect(c.createdAt, DateTime.utc(2026, 11, 8, 8, 5)); }); - test('Comment.listFromResponse reads the {comments: [...]} envelope', () { - final comments = Comment.listFromResponse({ - 'comments': [ - {'id': '1', 'replies': const []}, - ], + test('missing name falls back to Anonymous', () { + expect(Comment.fromRow({r'$id': 'x'}).author, 'Anonymous'); + }); + + group('buildTree', () { + test('nests replies under parents, oldest first, with depth', () { + // Rows arrive newest first, as the thread query orders them. + final flat = [ + _row('r2', reply: 'root1', minute: 4), + _row('root2', minute: 3), + _row('r1', reply: 'root1', minute: 2), + _row('rr', reply: 'r1', minute: 6), + _row('root1', minute: 1), + ]; + + final tree = Comment.buildTree(flat, votes: {'rr': 'up'}); + + expect(tree.map((c) => c.id), ['root1', 'root2']); + final root1 = tree.first; + expect(root1.depth, 0); + expect(root1.replies.map((c) => c.id), ['r1', 'r2']); + expect(root1.replies.first.depth, 1); + final rr = root1.replies.first.replies.single; + expect(rr.id, 'rr'); + expect(rr.depth, 2); + expect(rr.currentVote, 'up'); + expect(Comment.flatten(tree).length, 5); + }); + + test('promotes replies whose parent is gone, as the web does', () { + final tree = Comment.buildTree([ + _row('orphan', reply: 'deleted', minute: 2), + _row('root', minute: 1), + ]); + expect(tree.map((c) => c.id), ['root', 'orphan']); + }); + + test('a self-referencing reply cannot loop', () { + final tree = Comment.buildTree([_row('self', reply: 'self', minute: 1)]); + expect(tree.single.id, 'self'); + expect(tree.single.replies, isEmpty); }); - expect(comments, hasLength(1)); - expect(comments.first.author, 'anonymous'); }); } diff --git a/test/error_message_test.dart b/test/error_message_test.dart index 7b061c3..a5e1a1c 100644 --- a/test/error_message_test.dart +++ b/test/error_message_test.dart @@ -28,15 +28,15 @@ void main() { }); test('uses fallback for unknown errors', () { - expect( - messageForError(Exception('x'), fallback: 'Nope'), - 'Nope', - ); + expect(messageForError(Exception('x'), fallback: 'Nope'), 'Nope'); expect(messageForError(null, fallback: 'Nope'), 'Nope'); }); test('uses fallback when ApiException message is blank', () { - expect(messageForError(const ApiException(400, ' '), fallback: 'Oops'), 'Oops'); + expect( + messageForError(const ApiException(400, ' '), fallback: 'Oops'), + 'Oops', + ); }); test('a blank 5xx body still explains itself rather than falling back', () { @@ -77,4 +77,40 @@ void main() { expect(messageForError(error), 'That URL was already submitted.'); expect(detailForError(error), 'HTTP 422'); }); + + group('Appwrite read failures', () { + final offline = AppwriteException( + 'ClientException with SocketException: Failed host lookup: ' + "'fra.cloud.appwrite.io' (OS Error: No address associated with hostname, errno = 7), " + 'uri=https://fra.cloud.appwrite.io/v1/tablesdb/x', + ); + + test('a transport failure reads as offline, not as socket text', () { + expect( + messageForError(offline), + "Can't reach Refetch. Check your connection and try again.", + ); + expect(errorKind(offline), 'network'); + expect( + detailForError(offline), + startsWith('SocketException: Failed host lookup'), + ); + }); + + test('5xx reads as a server problem; 4xx keeps the message', () { + final server = AppwriteException('Server Error', 503, 'general_unknown'); + final missing = AppwriteException('Row not found', 404, 'row_not_found'); + expect(errorKind(server), 'server'); + expect(messageForError(server), startsWith('Refetch is having trouble')); + expect(errorKind(missing), 'client'); + expect(messageForError(missing), 'Row not found'); + expect(detailForError(missing), 'Appwrite 404 row_not_found'); + }); + + test('a code-less SDK error that is not transport keeps its message', () { + final local = AppwriteException('Missing required parameter: "rowId"'); + expect(errorKind(local), 'client'); + expect(messageForError(local), 'Missing required parameter: "rowId"'); + }); + }); } diff --git a/test/feed_queries_test.dart b/test/feed_queries_test.dart new file mode 100644 index 0000000..f37a218 --- /dev/null +++ b/test/feed_queries_test.dart @@ -0,0 +1,76 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:refetch/features/feed/data/feed_repository.dart'; + +/// Decodes the query strings so the test reads as data, not JSON. +List> _decode(List queries) => [ + for (final q in queries) jsonDecode(q) as Map, +]; + +Map? _find( + List> qs, + String method, [ + String? attribute, +]) { + for (final q in qs) { + if (q['method'] == method && + (attribute == null || q['attribute'] == attribute)) { + return q; + } + } + return null; +} + +void main() { + final now = DateTime.utc(2026, 11, 8, 12); + + test('Top mirrors the web front page: last 24h, quality gates, by score', () { + final qs = _decode( + feedQueries(FeedTab.top, limit: 25, offset: 50, now: now), + ); + + expect(_find(qs, 'greaterThan', r'$createdAt')!['values'], [ + '2026-11-07T12:00:00.000Z', + ]); + expect(_find(qs, 'lessThan', 'spamScore')!['values'], [70]); + expect(_find(qs, 'greaterThan', 'relevancyScore')!['values'], [30]); + expect(_find(qs, 'equal', 'enhanced')!['values'], [true]); + expect( + qs.where((q) => q['method'] == 'orderDesc').map((q) => q['attribute']), + ['score', r'$createdAt'], + ); + expect(_find(qs, 'limit')!['values'], [25]); + expect(_find(qs, 'offset')!['values'], [50]); + expect(_find(qs, 'equal', 'type'), isNull); + }); + + test('New orders by time only', () { + final qs = _decode( + feedQueries(FeedTab.latest, limit: 25, offset: 0, now: now), + ); + expect( + qs.where((q) => q['method'] == 'orderDesc').map((q) => q['attribute']), + [r'$createdAt'], + ); + }); + + test('Show filters to show posts', () { + final qs = _decode( + feedQueries(FeedTab.show, limit: 25, offset: 0, now: now), + ); + expect(_find(qs, 'equal', 'type')!['values'], ['show']); + }); + + test( + 'Mines lists the signed-in person\'s stories, newest first, ungated', + () { + final qs = _decode( + feedQueries(FeedTab.mines, limit: 25, offset: 0, userId: 'u1'), + ); + expect(_find(qs, 'equal', 'userId')!['values'], ['u1']); + expect(_find(qs, 'lessThan', 'spamScore'), isNull); + expect(_find(qs, 'orderDesc')!['attribute'], r'$createdAt'); + }, + ); +} diff --git a/test/post_test.dart b/test/post_test.dart index 99e4bff..9a61c66 100644 --- a/test/post_test.dart +++ b/test/post_test.dart @@ -2,64 +2,80 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:refetch/features/feed/domain/post.dart'; void main() { - group('Post.fromJson', () { - test('parses a full feed item', () { - final post = Post.fromJson({ - 'id': 'abc', + group('Post.fromRow', () { + test('maps a posts-table row', () { + final post = Post.fromRow({ + r'$id': 'abc', + r'$createdAt': '2026-11-08T08:00:00.000+00:00', 'title': 'Hello', - 'domain': 'example.com', + 'description': ' A note ', + 'userId': 'u1', + 'userName': 'jane', 'count': 42, - 'author': 'jane', 'countComments': 7, - 'daysAgo': '2 hours ago', - 'link': 'https://example.com/x', + 'link': 'https://www.example.com/x', 'type': 'link', 'readingTime': 5, - 'currentVote': 'up', - }); + 'tldr': 'Short summary', + }, currentVote: 'up'); expect(post.id, 'abc'); expect(post.title, 'Hello'); + expect(post.domain, 'example.com'); expect(post.count, 42); expect(post.countComments, 7); - expect(post.timeAgo, '2 hours ago'); + expect(post.author, 'jane'); + expect(post.description, 'A note'); + expect(post.tldr, 'Short summary'); expect(post.readingTime, 5); expect(post.currentVote, 'up'); + expect(post.createdAt, DateTime.utc(2026, 11, 8, 8)); expect(post.isShow, isFalse); + expect(post.threadUrl, 'https://refetch.io/threads/abc'); }); - test('applies sensible defaults for missing fields', () { - final post = Post.fromJson({'id': 'only-id'}); + test('applies the web defaults to a sparse row', () { + final post = Post.fromRow({r'$id': 'only-id'}); expect(post.title, ''); expect(post.count, 0); expect(post.countComments, 0); - expect(post.author, 'anonymous'); + expect(post.author, 'Anonymous'); + expect(post.domain, ''); + expect(post.link, isNull); expect(post.readingTime, isNull); - expect(post.currentVote, isNull); - }); - - test('coerces numeric strings/doubles to int', () { - final post = Post.fromJson({'id': 'x', 'count': 3.0, 'countComments': 2}); - expect(post.count, 3); - expect(post.countComments, 2); + expect(post.description, isNull); + expect(post.timeAgo, isNull); + expect(post.type, 'link'); }); - }); - group('Post.listFromResponse', () { - test('reads the {posts: [...]} envelope', () { - final posts = Post.listFromResponse({ - 'posts': [ - {'id': '1', 'title': 'a'}, - {'id': '2', 'title': 'b'}, - ], + test('drops non-http links and empty summaries, keeps show posts', () { + final post = Post.fromRow({ + r'$id': 'x', + 'link': 'javascript:alert(1)', + 'tldr': ' ', + 'readingTime': 0, + 'type': 'show', }); - expect(posts, hasLength(2)); - expect(posts.first.id, '1'); + expect(post.link, isNull); + expect(post.domain, ''); + expect(post.tldr, isNull); + expect(post.readingTime, isNull); + expect(post.isShow, isTrue); }); - test('returns empty for unexpected shapes', () { - expect(Post.listFromResponse(null), isEmpty); - expect(Post.listFromResponse({'nope': true}), isEmpty); + test('withVote replaces only the vote', () { + final post = Post.fromRow({r'$id': 'a', 'count': 3}, currentVote: 'up'); + final cleared = post.withVote(null); + expect(cleared.currentVote, isNull); + expect(cleared.count, 3); + expect(cleared.id, 'a'); }); }); + + test('hostOf strips www and tolerates junk', () { + expect(Post.hostOf('https://www.theverge.com/a'), 'theverge.com'); + expect(Post.hostOf('https://news.ycombinator.com'), 'news.ycombinator.com'); + expect(Post.hostOf(null), ''); + expect(Post.hostOf('not a url'), ''); + }); } diff --git a/test/time_ago_test.dart b/test/time_ago_test.dart new file mode 100644 index 0000000..afcb23e --- /dev/null +++ b/test/time_ago_test.dart @@ -0,0 +1,25 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:refetch/core/format/time_ago.dart'; + +void main() { + final now = DateTime(2026, 11, 8, 12); + + test('reads like refetch.io', () { + expect( + timeAgo(now.subtract(const Duration(seconds: 20)), now: now), + 'just now', + ); + expect( + timeAgo(now.subtract(const Duration(minutes: 5)), now: now), + '5m ago', + ); + expect(timeAgo(now.subtract(const Duration(hours: 3)), now: now), '3h ago'); + expect(timeAgo(now.subtract(const Duration(days: 2)), now: now), '2d ago'); + expect(timeAgo(DateTime(2026, 8, 3), now: now), 'Aug 3'); + expect(timeAgo(DateTime(2025, 8, 3), now: now), 'Aug 3, 2025'); + }); + + test('a clock running behind does not show a negative age', () { + expect(timeAgo(now.add(const Duration(minutes: 2)), now: now), 'just now'); + }); +} diff --git a/test/vote_controller_test.dart b/test/vote_controller_test.dart index 173fcf8..4f32065 100644 --- a/test/vote_controller_test.dart +++ b/test/vote_controller_test.dart @@ -23,7 +23,7 @@ class _FakeVoteRepository implements VoteRepository { } @override - Future> batch(List resources) async => + Future> batch(List resources) async => const {}; } diff --git a/test/vote_repository_test.dart b/test/vote_repository_test.dart new file mode 100644 index 0000000..0a34658 --- /dev/null +++ b/test/vote_repository_test.dart @@ -0,0 +1,68 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:refetch/core/network/api_client.dart'; +import 'package:refetch/features/vote/data/vote_repository.dart'; + +class _MockApi extends Mock implements ApiClient {} + +void main() { + late _MockApi api; + late VoteRepository repo; + + setUp(() { + api = _MockApi(); + repo = VoteRepository(api); + }); + + test('vote sends direction and reads the new vote and score', () async { + when( + () => api.post('/api/app/vote', body: any(named: 'body')), + ).thenAnswer((_) async => {'vote': null, 'count': 9}); + + final state = await repo.vote( + resourceId: 'p1', + resourceType: 'post', + voteType: 'up', + ); + + expect(state.count, 9); + expect(state.currentVote, isNull); + final body = verify( + () => api.post('/api/app/vote', body: captureAny(named: 'body')), + ).captured.single; + expect(body, { + 'resourceType': 'post', + 'resourceId': 'p1', + 'direction': 'up', + }); + }); + + test('batch splits posts and comments and merges the answer', () async { + when(() => api.post('/api/app/votes', body: any(named: 'body'))).thenAnswer( + (_) async => { + 'posts': {'p1': 'up'}, + 'comments': {'c1': 'down'}, + }, + ); + + final votes = await repo.batch([ + (id: 'p1', type: 'post'), + (id: 'p2', type: 'post'), + (id: 'c1', type: 'comment'), + ]); + + expect(votes, {'p1': 'up', 'c1': 'down'}); + final body = verify( + () => api.post('/api/app/votes', body: captureAny(named: 'body')), + ).captured.single; + expect(body, { + 'posts': ['p1', 'p2'], + 'comments': ['c1'], + }); + }); + + test('batch with nothing to look up makes no request', () async { + expect(await repo.batch(const []), isEmpty); + verifyNever(() => api.post(any(), body: any(named: 'body'))); + }); +} diff --git a/test_driver/integration_test.dart b/test_driver/integration_test.dart new file mode 100644 index 0000000..e5368e3 --- /dev/null +++ b/test_driver/integration_test.dart @@ -0,0 +1,28 @@ +import 'dart:io'; + +import 'package:integration_test/integration_test_driver_extended.dart'; + +/// Driver for the store-screenshot integration test. +/// +/// Writes each captured screenshot to `build/screenshots/`, where the +/// Screenshots workflow captions them and the fastlane `upload_screenshots` +/// lane uploads the result. +/// +/// ```sh +/// flutter drive \ +/// --driver=test_driver/integration_test.dart \ +/// --target=integration_test/screenshot_test.dart \ +/// -d +/// ``` +Future main() async { + await integrationDriver( + onScreenshot: + (String name, List bytes, [Map? args]) async { + final file = await File( + 'build/screenshots/$name.png', + ).create(recursive: true); + file.writeAsBytesSync(bytes); + return true; + }, + ); +} diff --git a/tool/render_brand_assets.py b/tool/render_brand_assets.py new file mode 100644 index 0000000..1cf5409 --- /dev/null +++ b/tool/render_brand_assets.py @@ -0,0 +1,117 @@ +"""Render the app icon and splash sources from the Refetch logo mark. + +The mark comes from refetch.io (see docs/BRANDING.md): a #4E1CB3 disc with +white arrows. Per the web DESIGN.md it is never placed on a purple +background, so the icon is the purple mark on white, like the site's +maskable-512.png and apple-touch-icon.png. + + pip install resvg_py pillow + python tool/render_brand_assets.py + dart run flutter_launcher_icons + dart run flutter_native_splash:create + +Writes the SVG sources next to the PNGs so the art stays editable. +""" + +from pathlib import Path + +import resvg_py + +ROOT = Path(__file__).resolve().parent.parent +ICON = ROOT / "assets" / "icon" +BRAND = ROOT / "assets" / "brand" +PLAY = ROOT / "android" / "fastlane" / "metadata" / "android" / "en-US" / "images" +FONTS = ROOT / "assets" / "fonts" + +PURPLE = "#4E1CB3" +VIEW = (10.9, 2.1, 198.8) # x, y, size of the mark's own viewBox + +# The disc with the arrows cut out, from the site's logo SVG. +DISC = ( + "M110.3,2.2C55.4,2.2,10.9,46.6,10.9,101.5s44.5,99.4,99.4,99.4,99.4-44.5," + "99.4-99.4S165.1,2.2,110.3,2.2ZM90.3,124.4l-36.3.6c-.6,0-1.1-.5-1.1-1.1v-36.6" + "c0-.9,1.1-1.4,1.8-.8l11.9,11.9,36.4-36.4c1.1-1.1,2.8-1.1,3.9,0l8.1,8.1c1.1,1.1," + "1.1,2.8,0,3.9l-36.4,36.4,12.3,12.2c.7.7.2,1.8-.7,1.8h0ZM166.5,117.4l-12.8-10.9" + "-36.6,36.2c-1.1,1.1-2.8,1.1-3.9,0l-8.1-8.2c-1.1-1.1-1.1-2.8,0-3.9l36.6-36.2" + "-11.2-13.1c-.7-.7-.2-1.8.7-1.8l35.6.5c.6,0,1.1.5,1.1,1.1l.5,35.7c0,.9-1.1," + "1.4-1.8.7h0Z" +) + + +def mark(scale: float, size: int = 1024, arrows: str | None = "#FFFFFF", fill: str = PURPLE) -> str: + """The mark centred on a size x size canvas, its disc `scale` of the width.""" + x, y, s = VIEW + d = size * scale + k = d / s + off = (size - d) / 2 + back = f'' if arrows else "" + return ( + f'' + f'{back}' + ) + + +def svg(body: str, size: int = 1024, background: str | None = None) -> str: + bg = f'' if background else "" + return ( + f'{bg}{body}\n' + ) + + +def write(path: Path, source: str, size: int = 1024) -> None: + path.with_suffix(".svg").write_text(source, encoding="utf-8") + png = resvg_py.svg_to_bytes(svg_string=source, width=size, height=size) + path.with_suffix(".png").write_bytes(bytes(png)) + print("wrote", path.with_suffix(".png").relative_to(ROOT)) + + +def feature_graphic() -> None: + """Play feature graphic (1024x500): the full logo and the site's tagline + on the light canvas (#F5F5F7), never on purple (DESIGN.md).""" + logo = (BRAND / "logo-wordmark.svg").read_text(encoding="utf-8") + logo = logo.replace('fill="currentColor"', 'fill="#1D1D1F"') + inner = logo[logo.index(">") + 1 : logo.rindex("")] + # Logo viewBox is 913 x 203; draw it 520 wide, centred. + k = 520 / 913 + x = (1024 - 520) / 2 + source = ( + '' + '' + f'{inner}' + 'The front page for builders' + "\n" + ) + png = resvg_py.svg_to_bytes( + svg_string=source, + width=1024, + height=500, + skip_system_fonts=True, + font_files=[str(FONTS / "Inter-Medium.ttf")], + ) + (PLAY / "featureGraphic.png").write_bytes(bytes(png)) + print("wrote", (PLAY / "featureGraphic.png").relative_to(ROOT)) + + +def main() -> None: + # Launcher icon (iOS, macOS, Windows, web, legacy Android): white tile, + # the disc at 62% like the site's touch icon. + write(ICON / "icon", svg(mark(0.62), background="#FFFFFF")) + # Android adaptive foreground: the visible circle is 72/108 of the canvas, + # so 58% keeps the disc clear of every launcher mask. + write(ICON / "icon_foreground", svg(mark(0.58))) + # Android 13 themed icon: one colour, arrows cut out (alpha only). + write(ICON / "icon_monochrome", svg(mark(0.58, arrows=None, fill="#000000"))) + # Splash: the mark alone on a transparent canvas; the splash background + # colour comes from the theme (#F5F5F7 light, #0E0D13 dark). + write(BRAND / "splash_mark", svg(mark(0.5)), size=768) + # Play listing icon (512, no alpha) and feature graphic. + png = resvg_py.svg_to_bytes(svg_string=svg(mark(0.62), background="#FFFFFF"), width=512, height=512) + (PLAY / "icon.png").write_bytes(bytes(png)) + print("wrote", (PLAY / "icon.png").relative_to(ROOT)) + feature_graphic() + + +if __name__ == "__main__": + main() diff --git a/tool/screenshot_job.dart b/tool/screenshot_job.dart new file mode 100644 index 0000000..d964ff9 --- /dev/null +++ b/tool/screenshot_job.dart @@ -0,0 +1,150 @@ +// Builds a moksha job file from screenshots/headlines.json. +// +// dart run tool/screenshot_job.dart \ +// --asset-type android-phone-screenshot \ +// --size-id android-phone \ +// --locale en-US \ +// --captures build/screenshots \ +// --out job.json +// +// Adapted from momo-pasal's tool of the same name. Kept in Dart, separate from +// the workflow, so the mapping from our copy to moksha's config is readable and +// can be run by hand. `npm run render -- --schema` in a moksha checkout lists +// every valid asset type, size, layout and background. + +import 'dart:convert'; +import 'dart:io'; + +void main(List args) { + final assetType = _option(args, '--asset-type'); + final locale = _option(args, '--locale') ?? 'en-US'; + final captureDir = _option(args, '--captures') ?? 'build/screenshots'; + final outPath = _option(args, '--out') ?? 'job.json'; + final sizeId = _option(args, '--size-id'); + + if (assetType == null) { + stderr.writeln( + 'usage: --asset-type [--locale en-US] [--size-id ] ' + '[--captures ] [--out ]', + ); + exit(64); + } + + final configFile = File('screenshots/headlines.json'); + if (!configFile.existsSync()) { + stderr.writeln('missing ${configFile.path}'); + exit(1); + } + final config = + jsonDecode(configFile.readAsStringSync()) as Map; + + final dir = Directory(captureDir); + final captures = dir.existsSync() + ? (dir + .listSync() + .whereType() + .where((f) => f.path.endsWith('.png')) + .toList() + ..sort((a, b) => a.path.compareTo(b.path))) + : []; + + if (captures.isEmpty) { + stderr.writeln('no PNGs in $captureDir; capture before building a job'); + exit(1); + } + + final scenes = [ + for (final scene in (config['scenes'] as List? ?? const [])) + scene as Map, + ]; + final layouts = [ + for (final layout in (config['layouts'] as List? ?? const [])) + layout as String, + ]; + final fonts = (config['fonts'] as Map?) ?? const {}; + final headlineFont = '${fonts['headline'] ?? 'Inter'}'; + final subheadFont = '${fonts['subhead'] ?? 'Inter'}'; + final textColor = config['textColor'] as String?; + + final assets = >[]; + + for (var i = 0; i < captures.length; i++) { + final name = captures[i].uri.pathSegments.last; + final id = _sceneId(name); + final scene = scenes.cast?>().firstWhere( + (s) => s?['id'] == id, + orElse: () => null, + ); + + if (scene == null) { + stderr.writeln('no scene "$id" in headlines.json; skipping $name'); + continue; + } + + final headline = _text(scene['headline'], locale); + final subhead = _text(scene['subhead'], locale); + + assets.add({ + 'assetType': assetType, + 'sizeId': ?sizeId, + // Cycled rather than fixed: a listing where every tile has the same + // composition reads as a contact sheet. + if (layouts.isNotEmpty) 'layout': layouts[i % layouts.length], + if (config['background'] != null) 'background': config['background'], + 'textOverlays': [ + if (headline.isNotEmpty) + { + 'text': headline, + 'anchor': 'top-center', + 'fontSize': 0.058, + 'font': headlineFont, + 'weight': 700, + 'color': ?textColor, + }, + if (subhead.isNotEmpty) + { + 'text': subhead, + 'anchor': 'top-center', + 'offsetY': 0.075, + 'fontSize': 0.034, + 'font': subheadFont, + 'weight': 500, + 'color': ?textColor, + }, + ], + 'screenshot': name, + 'filename': name, + }); + } + + if (assets.isEmpty) { + stderr.writeln('every capture was skipped; nothing to render'); + exit(1); + } + + File(outPath).writeAsStringSync( + const JsonEncoder.withIndent(' ').convert({'assets': assets}), + ); + stdout.writeln( + '${assets.length} asset(s) -> $outPath ($assetType, $locale)', + ); +} + +/// `01_top.png` -> `top`. The numeric prefix is capture order, which is also +/// the order the store shows them in. +String _sceneId(String fileName) { + final withoutExtension = fileName.replaceAll(RegExp(r'\.png$'), ''); + final underscore = withoutExtension.indexOf('_'); + return underscore == -1 + ? withoutExtension + : withoutExtension.substring(underscore + 1); +} + +String _text(Object? value, String locale) => + value is Map ? '${value[locale] ?? ''}' : ''; + +String? _option(List args, String name) { + final index = args.indexOf(name); + if (index == -1 || index + 1 >= args.length) return null; + return args[index + 1]; +} diff --git a/web/favicon.png b/web/favicon.png index e22125b..3b12c69 100644 Binary files a/web/favicon.png and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png index ddbadd3..1797f61 100644 Binary files a/web/icons/Icon-192.png and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png index 47bbd3b..c6139f0 100644 Binary files a/web/icons/Icon-512.png and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png index ddbadd3..1797f61 100644 Binary files a/web/icons/Icon-maskable-192.png and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png index 47bbd3b..c6139f0 100644 Binary files a/web/icons/Icon-maskable-512.png and b/web/icons/Icon-maskable-512.png differ diff --git a/web/manifest.json b/web/manifest.json index 76400c8..79ce985 100644 --- a/web/manifest.json +++ b/web/manifest.json @@ -3,8 +3,8 @@ "short_name": "Refetch", "start_url": ".", "display": "standalone", - "background_color": "#5A00FF", - "theme_color": "#5A00FF", + "background_color": "#F5F5F7", + "theme_color": "#4E1CB3", "description": "A new Flutter project.", "orientation": "portrait-primary", "prefer_related_applications": false, diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 7c971b5..33585e7 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -16,6 +17,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) { registry->GetRegistrarForPlugin("DesktopWebviewWindowPlugin")); PermissionHandlerWindowsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin")); + SharePlusWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi")); UrlLauncherWindowsRegisterWithRegistrar( registry->GetRegistrarForPlugin("UrlLauncherWindows")); WindowToFrontPluginRegisterWithRegistrar( diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index 240bb74..977aacf 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -5,6 +5,7 @@ list(APPEND FLUTTER_PLUGIN_LIST desktop_webview_window permission_handler_windows + share_plus url_launcher_windows window_to_front ) diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico index 16054bd..c2a0dfb 100644 Binary files a/windows/runner/resources/app_icon.ico and b/windows/runner/resources/app_icon.ico differ