diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index e5601ed..ae76b5a 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -6,10 +6,8 @@ body: - type: markdown attributes: value: | - Thanks for the report. If you can reproduce it in the - [live playground](https://simplifyjobs.github.io/flutter_border_beam/), - paste the share link — it carries the exact configuration and saves - everyone a round trip. + Thanks for the report. A minimal reproduction below saves everyone a + round trip. Security issues do **not** belong here — see [SECURITY.md](https://github.com/SimplifyJobs/flutter_border_beam/blob/main/SECURITY.md). @@ -28,11 +26,11 @@ body: label: Minimal reproduction description: >- The smallest widget tree that shows the problem — ideally one that - drops straight into a fresh `flutter create` app. A playground share - link works too. + drops straight into a fresh `flutter create` app. render: dart placeholder: | - BorderBeam.rotate( + BorderBeam( + effect: const BeamEffect.rotate(), colors: BeamColors.ocean, child: const SizedBox(width: 240, height: 120), ) @@ -54,11 +52,11 @@ body: required: true - type: input - id: variant + id: effect attributes: - label: Variant(s) and palette - description: Which `BeamVariant` and which `BeamColors` (or custom colors). - placeholder: "rotate + line; BeamColors.colorful" + label: Effect(s) and palette + description: Which `BeamEffect` and which `BeamColors` (or custom colors). + placeholder: "rotate; BeamColors.colorful" validations: required: true @@ -75,7 +73,7 @@ body: id: package-version attributes: label: flutter_border_beam version - placeholder: "0.1.0" + placeholder: "0.2.0" validations: required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 17ef9b4..fb49ce4 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -3,9 +3,9 @@ contact_links: - name: Question or idea url: https://github.com/SimplifyJobs/flutter_border_beam/discussions about: Ask how to do something, or float an idea before it becomes a proposal. - - name: Live playground + - name: Live demo url: https://simplifyjobs.github.io/flutter_border_beam/ - about: Try variants and palettes in the browser, then share the exact configuration. + about: See every effect and palette in the browser. - name: Security vulnerability url: https://github.com/SimplifyJobs/flutter_border_beam/security/advisories/new about: Report privately. Never in a public issue. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 4388223..6a293a5 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -1,16 +1,16 @@ name: Feature request -description: Propose a new variant, option, palette, or API. +description: Propose a new effect, option, palette, or API. title: "[feat]: " labels: [enhancement] body: - type: markdown attributes: value: | - This package is a port of the - [border-beam](https://github.com/Jakubantalik/border-beam) React - library. Features that exist upstream are the easiest sell — say so if - yours does, and link the source. Flutter-only additions are welcome - too; they just need to stay out of the parity tables. + Every effect is drawn by one fragment shader in a single draw call, + with no offscreen layers or blurs. Proposals that fit that model — new + light along the border, new motion, new palettes, new options — are + the easiest sell. Describe the look you want; how to render it is a + conversation for the issue. - type: textarea id: problem @@ -31,8 +31,8 @@ body: fine — the shape is what matters. render: dart placeholder: | - BorderBeam.rotate( - style: const BeamStyle(tailLength: 0.4), + BorderBeam( + effect: const BeamEffect.rotate(length: 0.4), child: ..., ) validations: @@ -68,7 +68,6 @@ body: attributes: label: Anything else description: >- - References, a link to the React implementation, screenshots or a - mockup of the effect. + References, screenshots, a video, or a mockup of the effect. validations: required: false diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index be1de89..5e9f3ee 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -11,7 +11,7 @@ the first thing a reviewer needs to know. @@ -32,24 +32,24 @@ What you actually ran, and what it said. Do not claim a check you skipped — -**saveLayer budget** — unchanged / changed: +**Frame budget** — still one draw, no `saveLayer` / clip / image or mask filter: ## Checklist -- [ ] No values in `lib/src/constants/` were tweaked (they are verbatim - transcriptions of the React source); Flutter-only additions live in a - clearly headed file +- [ ] `BeamOutline` and `color_math.dart` still mirror the shader (if either + side changed) - [ ] New public API has doc comments (`public_member_api_docs` is enforced) - [ ] Docs and comments describe current behavior — no change-history prose - [ ] `CHANGELOG.md` updated diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 41a5d27..ba5e0fb 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,7 +3,9 @@ version: 2 updates: - # GitHub Actions used by ci.yaml and release.yaml. + # GitHub Actions used by ci.yaml, release.yaml, and pages.yaml. They are + # pinned to commit SHAs with the release in a trailing comment; Dependabot + # bumps both together. - package-ecosystem: github-actions directory: / schedule: @@ -17,7 +19,7 @@ updates: patterns: - "*" - # Dart/Flutter dependencies for the package and the example gallery. + # Dart/Flutter dependencies for the package and the example app. - package-ecosystem: pub directories: - / diff --git a/.github/labels.yml b/.github/labels.yml index 7babf34..3f7b44b 100644 --- a/.github/labels.yml +++ b/.github/labels.yml @@ -14,7 +14,7 @@ - name: enhancement color: a2eeef - description: A new variant, option, palette, or API. + description: A new effect, option, palette, or API. - name: documentation color: 0075ca @@ -22,11 +22,11 @@ - name: rendering color: 8a63d2 - description: Painting, geometry, gradients, goldens — anything about the pixels. + description: The shader, geometry, colour, goldens — anything about the pixels. - name: performance color: fbca04 - description: Frame cost, saveLayer budget, repaint churn, memory. + description: Frame cost, the one-draw budget, repaint churn, memory. - name: good first issue color: 7057ff diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index dfc25fa..ac884f5 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -1,19 +1,26 @@ # CI for flutter_border_beam. # -# Two things about this workflow are deliberate and easy to get wrong: +# Three things about this workflow are deliberate and easy to get wrong: # -# 1. The Flutter version is PINNED to 3.44.2 rather than tracking `stable`. -# The golden files in `test/` were generated on Flutter 3.44.2 (Dart 3.12) -# on macOS, and rasterization of blurs and gradients shifts between -# Flutter releases. An unpinned `stable` would turn every Flutter release -# into a spurious golden diff. Regenerate the goldens (macOS, +# 1. The Flutter version is PINNED to 3.50.0 rather than tracking `stable`. +# The golden files in `test/golden/` were generated on Flutter 3.50.0 +# (Dart 3.14) on macOS, and shader compilation and rasterization shift +# between Flutter releases. An unpinned `stable` would turn every Flutter +# release into a spurious golden diff. Regenerate the goldens (macOS, # `flutter test --update-goldens --tags golden`) in the same commit that -# bumps this pin. -# 2. The `min-sdk` job builds and tests on Flutter 3.35.0 — the exact lower -# bound declared by `environment: flutter: ">=3.35.0"` in pubspec.yaml. +# bumps this pin, and move release.yaml's and pages.yaml's pins with it. +# 2. The `min-sdk` job builds and tests on Flutter 3.47.0 — the exact lower +# bound declared by `environment: flutter: ">=3.47.0"` in pubspec.yaml +# (the floor `material_ui` sets). Its job name carries no version, so a +# floor bump does not rename the required status check. # Without it that bound is an untested claim and consumers on the oldest # supported SDK find the breakage for us. It is a hard gate, not an # advisory one: no `continue-on-error`. +# 3. Every action is pinned to a full commit SHA, with the release it was cut +# from in a trailing comment. A tag can be moved; a SHA cannot, and +# release.yaml runs with a credential that can publish to pub.dev. +# Dependabot (.github/dependabot.yml) bumps the SHA and the comment +# together. # # Jobs are intentionally independent (no `needs:`) so they run in parallel. # `goldens` is the only macOS runner, and therefore the only expensive one. @@ -26,32 +33,38 @@ on: pull_request: workflow_dispatch: +# A new push to a PR supersedes the run in flight. Runs on `main` are never +# cancelled: every commit there gets a complete run, because release.yaml +# expects the tagged commit to have been green on `main` — goldens included. concurrency: group: ci-${{ github.ref }} - cancel-in-progress: true + cancel-in-progress: ${{ github.event_name == 'pull_request' }} permissions: contents: read env: # The pinned SDK. Keep in sync with the goldens and with release.yaml. - FLUTTER_VERSION: 3.44.2 + FLUTTER_VERSION: 3.50.0 # The declared lower bound from pubspec.yaml's `environment:` block. - FLUTTER_MIN_VERSION: 3.35.0 + FLUTTER_MIN_VERSION: 3.47.0 jobs: quality: name: Format, analyze, test, coverage runs-on: ubuntu-latest + timeout-minutes: 20 permissions: contents: read # Required so codecov/codecov-action can mint a GitHub OIDC token and # upload tokenlessly (the repo is public, so there is no CODECOV_TOKEN). id-token: write steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - - uses: subosito/flutter-action@v2 + - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 with: flutter-version: ${{ env.FLUTTER_VERSION }} channel: stable @@ -66,28 +79,36 @@ jobs: - name: Analyze run: flutter analyze --fatal-infos + # Validated before the tests run, from a tree that holds only the + # checkout: once `--coverage` and the Codecov upload have run, the tree + # also holds `coverage/` and the Codecov uploader binary, and the dry + # run would no longer be looking at the archive a release publishes. + # Exits non-zero on any validation warning. + - name: Validate the publishable archive + run: dart pub publish --dry-run + # Goldens are pinned to macOS rendering — the `goldens` job owns them. - name: Test with coverage run: flutter test --exclude-tags golden --coverage - name: Upload coverage to Codecov - uses: codecov/codecov-action@v7 + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: files: coverage/lcov.info use_oidc: true # Coverage reporting must never be the reason a PR goes red. fail_ci_if_error: false - - name: Validate the publishable archive - run: dart pub publish --dry-run - goldens: name: Goldens (macOS) runs-on: macos-latest + timeout-minutes: 30 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - - uses: subosito/flutter-action@v2 + - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 with: # Same pin as `quality`: the goldens encode this exact renderer. flutter-version: ${{ env.FLUTTER_VERSION }} @@ -102,7 +123,7 @@ jobs: - name: Upload golden failures if: failure() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: golden-failures path: test/**/failures/** @@ -110,12 +131,15 @@ jobs: if-no-files-found: ignore min-sdk: - name: Minimum supported Flutter (3.35.0) + name: Minimum supported Flutter runs-on: ubuntu-latest + timeout-minutes: 20 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - - uses: subosito/flutter-action@v2 + - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 with: flutter-version: ${{ env.FLUTTER_MIN_VERSION }} channel: stable @@ -136,15 +160,28 @@ jobs: pana: name: pub.dev score (pana) runs-on: ubuntu-latest + timeout-minutes: 20 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - - uses: subosito/flutter-action@v2 + - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 with: flutter-version: ${{ env.FLUTTER_VERSION }} channel: stable cache: true + # pana scores the pubspec's `screenshots:` by converting them with the + # libwebp tools (cwebp, dwebp, webpinfo), as pub.dev's analyzer does. + # The runner image does not ship them; without them every screenshot + # fails with "No such file or directory" and the example/screenshots + # check scores 0/10 here while scoring 10/10 on pub.dev. + - name: Install the WebP tools + run: | + sudo apt-get update -q + sudo apt-get install -y -q --no-install-recommends webp + - name: Install dependencies run: flutter pub get @@ -152,30 +189,33 @@ jobs: run: dart pub global activate pana # pana prints the full report to the log, then `--exit-code-threshold N` - # fails the job when MORE than N pub.dev points are lost. 20 is a floor, - # not a target: it leaves room for points only a published package can - # earn (downstream-usage and up-to-date-dependency signals) while still - # catching a real regression — a dropped example, a broken publish - # archive, undocumented public API, an unresolvable dependency. Ratchet - # it down as the package settles; the number should only get smaller. + # fails the job when MORE than N of the 160 pub.dev points are lost. On + # the pinned SDK the package earns all 160, so any lost check is a + # regression — a dropped example, a broken screenshot, a lint, an + # undocumented public API, an unresolvable dependency. If a new pana + # release takes points for something the package cannot fix, raise this + # with a comment saying which check and why rather than ignoring the job. - name: Run pana - run: dart pub global run pana --no-warning --exit-code-threshold 20 . + run: dart pub global run pana --no-warning --exit-code-threshold 0 . example: name: Example app runs-on: ubuntu-latest + timeout-minutes: 20 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - - uses: subosito/flutter-action@v2 + - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 with: flutter-version: ${{ env.FLUTTER_VERSION }} channel: stable cache: true - # The example consumes the package by path, so it is the canary for API - # breaks in the gallery, and the web build proves the package carries no - # imports that fail to compile for web. + # The example consumes the package by path, so analyzing it catches API + # breaks, and the web build proves the package carries no imports that + # fail to compile for web. - name: Install dependencies working-directory: example run: flutter pub get @@ -184,10 +224,6 @@ jobs: working-directory: example run: flutter analyze --fatal-infos - - name: Test - working-directory: example - run: flutter test - - name: Build web working-directory: example run: flutter build web --release diff --git a/.github/workflows/pages.yaml b/.github/workflows/pages.yaml index eba96d5..fb312f1 100644 --- a/.github/workflows/pages.yaml +++ b/.github/workflows/pages.yaml @@ -1,14 +1,12 @@ -# Deploy the example gallery to GitHub Pages. +# Deploy the example app to GitHub Pages. # -# The site is `example/` — the demo gallery and the interactive playground — -# built for web and served at +# The site is `example/` — the one-screen effect showcase — built for web and +# served at # # https://simplifyjobs.github.io/flutter_border_beam/ # -# That URL is not incidental: `example/lib/src/playground/share_codec.dart` -# hardcodes it as `playgroundSiteUrl` when it builds a share link, so the -# `--base-href` below must stay `/flutter_border_beam/` (the repo name) for -# shared links to resolve. +# The root README links to that URL. Pages serves a project site under the +# repo name, so the `--base-href` below must stay `/flutter_border_beam/`. # # ── ONE-TIME SETUP THE MAINTAINER MUST DO ──────────────────────────────────── # @@ -21,12 +19,9 @@ # ── WHY THE 404 COPY ───────────────────────────────────────────────────────── # # Pages serves static files and has no rewrite rule, so any path that is not a -# real file 404s. The playground puts its state in the URL and the gallery -# uses path-shaped routes (`/pulse`, …), so a deep link would land on the -# Pages 404 page instead of the app. Copying `index.html` to `404.html` makes -# the 404 response *be* the app: Flutter boots, reads the location, and routes -# to it. `#state` fragments survive the redirect for free (fragments are never -# sent to the server). +# real file 404s. A mistyped or stale deep link would land on the Pages 404 +# page instead of the app. Copying `index.html` to `404.html` makes the 404 +# response *be* the app: Flutter boots on any path under the site. # # The Flutter pin matches ci.yaml's FLUTTER_VERSION — the site should be built # by the same SDK the package is tested on. @@ -39,14 +34,13 @@ on: paths: - "example/**" - "lib/**" + - "shaders/**" - "pubspec.yaml" - ".github/workflows/pages.yaml" workflow_dispatch: -permissions: - contents: read - pages: write - id-token: write +# Least privilege: nothing by default; each job asks for what it uses. +permissions: {} # One deployment at a time. Queued rather than cancelled: a half-finished # deploy that loses its slot would leave the live site on an older build. @@ -56,16 +50,24 @@ concurrency: env: # Keep in sync with ci.yaml's FLUTTER_VERSION. - FLUTTER_VERSION: 3.44.2 + FLUTTER_VERSION: 3.50.0 jobs: build: name: Build the example for web runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + # configure-pages reads the repo's Pages settings to fail early when + # Pages is not set to deploy from GitHub Actions. + pages: read steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - - uses: subosito/flutter-action@v2 + - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 with: flutter-version: ${{ env.FLUTTER_VERSION }} channel: stable @@ -85,9 +87,9 @@ jobs: working-directory: example run: cp build/web/index.html build/web/404.html - - uses: actions/configure-pages@v6 + - uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0 - - uses: actions/upload-pages-artifact@v5 + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 with: path: example/build/web @@ -95,10 +97,16 @@ jobs: name: Deploy to GitHub Pages needs: build runs-on: ubuntu-latest + timeout-minutes: 10 + # The minimum deploy-pages documents: write the deployment, and mint the + # OIDC token that proves it came from this workflow. + permissions: + pages: write + id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - name: Deploy id: deployment - uses: actions/deploy-pages@v5 + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 2ffe0d9..5900f15 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -10,7 +10,8 @@ # "Today, you can only automate publishing of existing packages. To create # a new package, you must publish the first version using `dart pub # publish`." (https://dart.dev/tools/pub/automated-publishing). Until -# 0.1.0 is on pub.dev there is nothing to attach automated publishing to. +# the first version is on pub.dev there is nothing to attach automated +# publishing to. # 2. On pub.dev, open # https://pub.dev/packages/flutter_border_beam/admin # → "Automated publishing" → "Enable publishing from GitHub Actions", and @@ -64,25 +65,30 @@ permissions: env: # Must match ci.yaml's pin. - FLUTTER_VERSION: 3.44.2 + FLUTTER_VERSION: 3.50.0 jobs: publish: name: Publish to pub.dev runs-on: ubuntu-latest + timeout-minutes: 30 permissions: # Mints the pub.dev OIDC credential. id-token: write # Lets `gh release create` write the GitHub Release. contents: write steps: - - uses: actions/checkout@v7 + # Every action here is pinned to a commit SHA (see ci.yaml's header): + # this job holds a credential that can publish to pub.dev. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false # Order matters — see the header. This step configures the pub.dev # credential; the Flutter SDK installed next provides the toolchain. - - uses: dart-lang/setup-dart@v1 + - uses: dart-lang/setup-dart@2286a0c042b44434fe26d292bbce8d34f7ec662b # v1.8.2 - - uses: subosito/flutter-action@v2 + - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 with: flutter-version: ${{ env.FLUTTER_VERSION }} channel: stable diff --git a/.github/workflows/upstream_drift.yaml b/.github/workflows/upstream_drift.yaml deleted file mode 100644 index e432b94..0000000 --- a/.github/workflows/upstream_drift.yaml +++ /dev/null @@ -1,125 +0,0 @@ -# Upstream drift alarm for flutter_border_beam. -# -# Everything in `lib/src/constants/` is a hand transcription of the React -# border-beam library's `src/styles.ts`. `test/constants/spec_parity_test.dart` -# proves the transcription against a VENDORED copy of upstream's generated -# `spec/beam-spec.json` — which means the parity test can only ever be as -# current as that fixture. This job watches the live upstream and shouts when -# it moves. -# -# It is an ALARM, not a build gate: it never runs on push or pull_request, so -# it can fail without blocking anyone's merge. A failure means "go re-audit the -# constants", never "this PR is broken". -# -# Two independent signals, because they catch different things: -# -# 1. The spec JSON itself (minus its `generated` timestamp, which the -# extractor rewrites on every run whether or not a value changed). -# 2. The sha256 of `src/styles.ts`. The spec is generated FROM styles.ts, so a -# styles change that upstream has not regenerated the spec for would slip -# past signal 1 entirely. -# -# Markdown in the job summary uses `~~~` fences and escaped backticks so the -# shell literals stay free of unquoted backticks (shellcheck SC2016). - -name: Upstream drift - -on: - schedule: - # Mondays, 06:00 UTC. - - cron: '0 6 * * 1' - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: upstream-drift - cancel-in-progress: false - -env: - UPSTREAM_RAW: https://raw.githubusercontent.com/Jakubantalik/Libraries/main/packages/border-beam - -jobs: - compare-vendored-spec-with-upstream: - name: Compare vendored spec with upstream - runs-on: ubuntu-latest - steps: - - name: Check out flutter_border_beam - uses: actions/checkout@v7 - - - name: Fetch upstream spec and styles.ts - run: | - set -euo pipefail - mkdir -p "$RUNNER_TEMP/upstream" - curl -fsSL --retry 3 --retry-delay 5 --retry-all-errors \ - "$UPSTREAM_RAW/spec/beam-spec.json" \ - -o "$RUNNER_TEMP/upstream/beam-spec.json" - curl -fsSL --retry 3 --retry-delay 5 --retry-all-errors \ - "$UPSTREAM_RAW/src/styles.ts" \ - -o "$RUNNER_TEMP/upstream/styles.ts" - jq empty < "$RUNNER_TEMP/upstream/beam-spec.json" - - - name: Diff the spec (ignoring the generated timestamp) - id: spec - run: | - set -euo pipefail - jq -S 'del(.generated)' test/fixtures/beam-spec.json \ - > "$RUNNER_TEMP/ours.json" - jq -S 'del(.generated)' "$RUNNER_TEMP/upstream/beam-spec.json" \ - > "$RUNNER_TEMP/theirs.json" - if diff -u "$RUNNER_TEMP/ours.json" "$RUNNER_TEMP/theirs.json" \ - > "$RUNNER_TEMP/spec.diff"; then - echo "changed=false" >> "$GITHUB_OUTPUT" - echo "Vendored spec matches upstream." - else - echo "changed=true" >> "$GITHUB_OUTPUT" - { - echo "### Upstream \`beam-spec.json\` changed" - echo - echo '~~~diff' - head -c 60000 "$RUNNER_TEMP/spec.diff" - echo - echo '~~~' - } >> "$GITHUB_STEP_SUMMARY" - cat "$RUNNER_TEMP/spec.diff" - fi - - - name: Compare the styles.ts hash - id: styles - run: | - set -euo pipefail - recorded="$(grep '^styles_sha256=' test/fixtures/UPSTREAM | cut -d= -f2)" - current="$(sha256sum "$RUNNER_TEMP/upstream/styles.ts" | cut -d' ' -f1)" - echo "recorded: $recorded" - echo "current: $current" - if [ "$recorded" = "$current" ]; then - echo "changed=false" >> "$GITHUB_OUTPUT" - else - echo "changed=true" >> "$GITHUB_OUTPUT" - { - echo "### Upstream \`src/styles.ts\` changed" - echo - echo "recorded: \`$recorded\`" - echo - echo "current: \`$current\`" - } >> "$GITHUB_STEP_SUMMARY" - fi - - - name: Report - env: - SPEC_CHANGED: ${{ steps.spec.outputs.changed }} - STYLES_CHANGED: ${{ steps.styles.outputs.changed }} - run: | - set -euo pipefail - remedy="re-audit the constants against src/styles.ts, run tool/spec/refresh.sh, then flutter test test/constants/spec_parity_test.dart" - if [ "$SPEC_CHANGED" = 'true' ]; then - echo "::error title=Upstream spec drift::beam-spec.json changed upstream — $remedy" - fi - if [ "$STYLES_CHANGED" = 'true' ]; then - echo "::warning title=Upstream styles.ts drift::styles.ts changed upstream (the spec may not have been regenerated yet) — $remedy" - fi - if [ "$SPEC_CHANGED" = 'true' ] || [ "$STYLES_CHANGED" = 'true' ]; then - exit 1 - fi - echo "No upstream drift." diff --git a/.pubignore b/.pubignore index 054d3c1..eb3300c 100644 --- a/.pubignore +++ b/.pubignore @@ -1,13 +1,37 @@ # Repo-only files, excluded from the published pub package. +# +# A `.pubignore` REPLACES the `.gitignore` in its directory as far as pub is +# concerned — pub reads one or the other, never both — so everything the root +# `.gitignore` keeps out of git must be listed here again, or `dart pub +# publish` ships it (a stray `flutter_01.log`, a local `coverage/`). Hidden +# files and directories (`.dart_tool/`, `.github/`, `.demos/`, `.DS_Store`) +# are always left out by pub itself, and `example/.gitignore` still applies +# inside `example/`. +# # `screenshots/` stays in the archive — pub.dev renders the images the # pubspec's `screenshots:` section points at, so they must ship with the package. +# `shaders/` must stay in the archive too: `beam.frag` is declared under +# `flutter: shaders:` and compiled into every consuming app. Never ignore it. + +# ── Mirrors of the root .gitignore ────────────────────────────────────────── +*.class +*.log +*.pyc +*.swp +*.iml +*.ipr +*.iws +migrate_working_dir/ +**/doc/api/ +**/build/ +coverage/ + +# ── Repo-only sources and tooling ─────────────────────────────────────────── assets/ tool/ -# The vendored upstream spec is parity-test input only (123 KB of JSON). -test/fixtures/ CLAUDE.md -.demos/ -**/.dart_tool/ -**/build/ -# Golden reference images (6.9 MB) only matter to the repo's own CI, not to consumers. +# codecov.yml, plus the uploader binary and its checksums that +# codecov/codecov-action downloads into the working tree in CI. +/codecov* +# Golden reference images only matter to the repo's own CI, not to consumers. test/golden/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 52b220b..122a786 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,295 +3,284 @@ All notable changes to this package are documented here, following [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). -## Unreleased - -This release tracks upstream [border-beam](https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam) -**1.4.0**; the tables in `lib/src/constants/` are transcribed from that -version's `src/styles.ts`, whose spec still declares `1.3.0` as its visual -baseline. See [doc/parity.md](doc/parity.md) for the deviation list and how -the transcription is verified. +## 0.2.0 + +A new renderer and a new effect model. This is the first release since 0.1.0 +and includes everything developed in between, so it breaks the API: the +[migration table](#migrating-to-020) maps every removed name to its +replacement, where it has one. + +### Why the renderer changed + +0.1 reproduced the React [border-beam](https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam) +library's CSS layer stack on Flutter's canvas: per frame, several `saveLayer`s +(each an offscreen render target), Gaussian blurs through `ImageFilter` and +`MaskFilter` (each a separate pass), path clips, and freshly built gradients. +A beam left running on a card kept the GPU busy enough to heat a phone, and +the pulse variants ran at a capped ~30fps, as the original's pulse driver does. + +0.2.0 draws every effect with **one fragment shader in a single pass**: + +- one `drawRect` / `drawDRRect` per frame — no `saveLayer`, no clip, no + `ImageFilter` or `MaskFilter`, no offscreen target; +- the original design's layered light model: the shader evaluates its + layers per pixel — the hairline stroke and its head highlight, the + edge-faded inner glow with its inset shadow, the bloom, the line's spikes, + the pulse's breathing blobs — from the original palettes' blob tables, + checked against 0.1 side by side but not pixel-matched to it (see + Changed, below); +- every blur evaluated analytically instead (a blurred hairline is a gaussian + across the ring, a blurred colour blob an energy-preserving gaussian); +- fragment work limited to the band where light can land; +- per frame, the CPU fills a fixed block of uniforms in a `FragmentShader` + reused for the beam's lifetime — no path or gradient construction; +- every effect at the display's refresh rate, 120Hz included. + +With that, the package is no longer a port. It was originally ported from +border-beam and remains inspired by it, but 0.2.0 is an independent native +renderer: it does not track the original's source, and its constants are +design data rather than transcriptions. ### Added -#### API - -- `BorderBeam` has a public generic constructor taking a `BeamVariant`, so a - variant chosen at runtime needs no switch over the five named ones. -- `BorderBeam.overlay` paints a beam with no child of its own, sized by its - parent — drop it into a `Stack` under a `Positioned.fill` and it traces the - stack's bounds. -- `BorderBeamTheme` supplies `BorderBeamThemeData` defaults to the beams below - it, one slot per value object. `of` walks every enclosing scope, depends on - each, and merges them outside-in, so nested themes compose. -- `BeamThemeConfig` is public, with `copyWith`, value equality, and - `BeamThemeConfig.presetFor(variant, brightness)` to start from a preset. -- `BeamVariant.defaultHuePeriod` and `BeamVariant.defaultBloomHuePeriod` - expose the per-variant hue timings the config resolves against. -- `BorderBeam` and `BeamPainter` implement `debugFillProperties`. +#### Renderer -#### Palettes +- `shaders/beam.frag`, declared under `flutter: shaders:` and bundled with the + package; nothing to add to an app's pubspec. +- `BorderBeam.precache()` loads the shader ahead of the first beam — in `main` + for a ready first frame, and in tests before reading pixels. -- Seven Flutter-only presets: `aurora`, `neon`, `candy`, `ember`, `ice`, - `gold` (hue pinned, full opacity) and `holographic` (built for pairing with - a fast continuous hue drift). They live in `extra_palettes.dart`, separate - from the transcribed tables. -- `BeamColors.custom` takes a `base` palette to distribute over. -- `BeamColors.fromSeed` derives a glow-safe palette from one brand color in - four harmonies (`analogous`, `complementary`, `triadic`, `monochrome`), - lifting derived colors into a readable lightness/saturation band. -- `BeamColors.fromScheme` builds a palette from a Material `ColorScheme`'s - primary, secondary and tertiary roles, dropping near-duplicates. -- `BeamColors.lerp` blends two color choices per blob; `scaleAlpha` dims every - table entry without touching layer opacity. - -#### Shape - -- `BeamShape.all(radius)` is the const path to a uniform radius — it stores - the number instead of building a `BorderRadius`, so a theme or a widget can - hold one in a `const` expression. It compares equal to - `BeamShape.circular(radius)`. -- `BeamShape.edge` moves the line variant's beam to any `BeamEdge` (top, - right, bottom, left). -- `BeamShape.ringOffset` pushes the ring outward or pulls it inward from the - child's bounds. -- `BeamShape.contour` takes a `BeamContour` — an arbitrary closed path for the - beam to travel, replacing the rounded rectangle, with a true normal offset - for its inner ring. `BeamPathContour` wraps a `Path Function(Rect)` with an - explicit equality key. -- `BeamShape.segment` accepts a `BeamSegment` between two `BeamAnchor`s — a - raw perimeter fraction, a position along a `BeamEdge`, or a position through - a `BeamCorner` — and masks the unchanged full-ring animation to that - clockwise span. Presets cover each half and each edge with its adjacent - corner arcs; endpoint feathering is measured in perimeter pixels. -- `BeamShape.wrapCorners` places a segment-free line in border-path space so - its streak bends around the two corner arcs adjacent to its selected edge. - -#### Style - -- `BeamStyle.hueMode` picks the shape of the hue track: `BeamHueMode.pingPong` - swings across ±`hueRange`, `BeamHueMode.continuous` revolves a full 360°. - Traveling variants ping-pong and pulse variants revolve by default. -- `BeamStyle.tailLength` scales the traveling window about its head, and - `BeamStyle.glowSpread` scales how far the bloom and halo layers reach past - the ring. -- `BeamStyle.comet` re-aims the bloom into a halo trailing the rotate and - small beams' head outside the ring; `BeamStyle.sparkle` scatters - deterministic twinkles at that head, at a density of 0–1. -- `BeamStyle.segments` breaks the ring into that many evenly spaced dashes - through a feathered conic mask; null keeps it solid. -- `BeamStyle.innerSizeScale` scales pulse-inside's inner wash: below 1 it - pulls tighter to the border, above 1 it floods further in. The perimeter - ring and the bloom keep their own geometry. -- `BeamStyle.renderScale` (0.25–1) paints the beam at that fraction of the box - and magnifies it back, so a palette authored against a 350×140 card still - reads on a screen-width one. One canvas transform, no extra layer. -- `BeamStyle.pulseOutsideStock` is a ready-made style carrying the upstream - library's stock pulse-outside look — a tighter, dimmer halo — next to this - package's default, which bakes the tuning the original's demo page applies. - `BeamStyle.pulseOutsideTuning` (`BeamPulseOutsideTuning.demo` / `.stock`) - switches the glow geometry alone. - -#### Motion - -- `BeamTiming.cycleGap` rests the traveling beam between sweeps. -- `BeamTiming.direction` runs the beam forward, reversed, or alternating each - cycle (`BeamDirection`); reversed sweeps mirror the asymmetric stop tables - at runtime, so the soft tail still trails the head. -- `BeamTiming.phaseOffset` starts the timeline part way through a cycle. -- `BeamTiming.beamCount` sends several beams around the contour at once, - equally spaced — tiled into one sweep shader for rotate, one traveller per - band for line. -- `BeamTiming.huePeriod`, `bloomHuePeriod`, `breatheFactor`, `spikeFactor`, - and `spike2Factor` expose the timings that were fixed in the phase resolver. -- `BorderBeam.progress` drives the sweep from a value instead of the clock, - turning `rotate` into a progress ring and `line` into a progress bar, with - the clock still running underneath. -- `BorderBeam.follow` eases the sweep toward a normalized point in the box — - critically damped, ~150ms — and hands it back to the clock without a snap. -- `BorderBeam.strengthListenable` and `BorderBeam.speedListenable` drive layer - opacity and playback rate per frame without rebuilding. -- `BeamSync` runs every descendant beam off one shared clock: one ticker, one - timeline, identical phases, with `active` and `speed` on the group. - -#### Playback - -- `BeamPlayback.repeat` stops the beam after a set number of cycles - (`BeamRepeat.forever()`, `.once()`, `.count(n)`), fading out and firing - `onDeactivate` rather than cutting mid-sweep. -- `BeamPlayback.reducedMotion` chooses what happens under - `MediaQuery.disableAnimations`: `staticFrame` (the default), `hide` (no - painter, no ticks), `slow` (quarter speed), or `animate` to ignore the ask. -- `BeamPlayback.pauseWhenOffscreen` (default true) stops the clock while the - beam is more than 256px outside its nearest enclosing `Scrollable`, and - resumes it exactly where it left off — play state, fade, and callbacks - untouched. It does nothing when there is no enclosing scrollable. -- `BeamPlayback.fadeCurve` sets the easing both fade envelopes run on; - `BeamPlayback.cssEase` is the web's `cubic-bezier(0.25, 0.1, 0.25, 1)`. -- `BeamPlayback.debugFrozenAt` pins the beam to one instant of its timeline, - at full opacity, and never starts its clock — deterministic frames for - goldens, docs captures, and design reviews. -- `BorderBeamController.pulse()` and `flash()` are one-shot brightness accents - that ride the fade envelope without touching the timeline. - -#### Widgets - -- `BeamDecoration` paints a beam as a `Decoration`, for dropping into an - existing `Container` or `DecoratedBox` — `foregroundDecoration` for the - variants `BorderBeam` paints over its child, `decoration` for - `pulseOutside`. It takes `brightness` and a `BorderBeamThemeData` as - arguments, since a `BoxPainter` has no `BuildContext`. -- `BeamFocusRing` lights while the wrapped subtree, or a given `FocusNode`, - holds focus, honoring `FocusManager.highlightMode`. -- `BeamHover` lights on hover and steers the sweep to the cursor through - `BorderBeam.follow`, with a hold after exit. -- `BeamPress` lights while a finger is down, with a minimum duration, and - never takes a gesture from its child. +#### Effects -### Changed - -#### Naming & repository - -- The package is named `flutter_border_beam`; the barrel is - `package:flutter_border_beam/flutter_border_beam.dart`. The pub.dev name - `border_beam` belongs to an unrelated package. -- The canonical repository is , - which `repository`, `issue_tracker`, and `homepage` now point at. -- `LICENSE` leads with the canonical MIT header so GitHub detects it, with the - border-beam third-party notice preserved below. -- The pubspec gains a `screenshots:` section backed by PNGs shipped in - `screenshots/`; `assets/` stays pub-ignored. - -#### API - -- `BorderBeam` takes four value objects instead of a flat parameter list: - `BeamStyle` (colors, theme, filters, layer-opacity hooks, and a - `themeConfig` that replaces the whole variant×brightness preset), - `BeamShape` (per-corner radius, border width, superellipse, edge, ring - offset, contour), `BeamTiming` (cycle, rest, speed, direction, hue periods, - line track factors), and `BeamPlayback` (active, autoPlay, startAfter, - duration, repeat, reduced motion). Every field is nullable and means - *inherit*; `controller`, `onActivate`, and `onDeactivate` stay flat on the - widget. -- `colors`, `active`, and `borderRadius` remain on the widget as shorthands - for `style.colors`, `playback.active`, and a uniform `shape.radius`; a - non-null shorthand wins over the same field in its object. -- Field resolution is one order throughout: flat shorthand, then the value - object on the widget, then `BorderBeamTheme` (inner over outer), then the - variant preset. - -#### Shape - -- Shapes are per-corner: `BeamShape.radius` is a `BorderRadiusGeometry` - resolved against the ambient `Directionality`, clamped per corner the way - `RRect.scaleRadii` clamps. `BeamShape.circular(r)` and `BeamShape.stadium()` - cover the uniform and pill cases; a stadium rounds to half the shortest - side, so a square box comes out a circle. - -#### Motion - -- `BeamTiming.cycleGap` rests the traveling beam between sweeps: the sweep - still takes `cycle`, then the beam parks at the end of its travel while its - fade envelope eases out and back in over `min(0.25s, gap / 2)` at each end. - The pulse variants ignore it. Hue, breathe, and spike tracks keep running - through the gap. -- `BeamTiming.speed` sets the playback rate when no controller is attached, - and leaves the config-cache key entirely — a rate change no longer - re-resolves the config or rebuilds the phase resolver. +- `BeamEffect`, a sealed value type chosen with `effect:` on `BorderBeam`, + `BorderBeam.overlay`, `BeamDecoration`, `BeamFocusRing`, `BeamHover`, and + `BeamPress`, and as a default with `BorderBeamThemeData.effect`. Three + effects: + - `BeamEffect.rotate({length, count, comet})` — a beam laps the border. + - `BeamEffect.line({edge})` — a streak rides one edge with spikes of light. + - `BeamEffect.pulse()` — colour breathes inward from the border. +- `BeamEffect.values`, and per effect `travels`, `defaultCycle`, + `defaultCycleGap`, `defaultHueMode`, and `defaultHuePeriod`. #### Palettes -- `BeamColors`, `BeamPalette`, `BeamPresetData`, `BeamBlob`, and `LineBlob` - are value types that compare structurally, and `resolve()` memoizes by value - through a bounded LRU, so equal color choices share one `BeamPalette` and a - palette rebuilt inline in `build()` hits the widget's config cache instead - of re-deriving nine gradient tables. -- `BeamBlob` and `LineBlob` sizes are documented as the ellipse **radii** every - painter already treats them as. +- Palettes are rings of 1–8 colour stops: `BeamColors(colors, {stops})` places + colours evenly or at chosen perimeter positions, and `BeamColors.solid(color)` + is one colour all the way round. +- 15 presets beyond 0.1.0's four, 19 in all: `aurora`, `neon`, `candy`, + `ember`, `ice`, `gold`, `holographic`, and, new in this release, `lagoon`, + `dusk`, `forest`, `rose`, `cosmic`, `citrus`, `sky`, and `lavender`. + `BeamColors.presets` maps every name to its palette. +- `BeamColors.fromSeed` (four harmonies, every one kept within a readable + lightness band and above a saturation floor), `BeamColors.fromScheme`, + `BeamColors.lerp`, and `scaleAlpha`. + +#### API since 0.1.0 + +- Four value objects replace the flat parameter list: `BeamStyle` + (`colors`, `theme`, `strength`, `glow`, `hueShift`, `hueMode`, `hueBase`), + `BeamShape` (`radius`, `superellipse`, `borderWidth`, `ringOffset`, + `segment`, `dashes`; `.all`, `.circular`, `.stadium`), `BeamTiming` + (`cycle`, `cycleGap`, `speed`, `direction`, `phaseOffset`, `huePeriod`), and + `BeamPlayback` (`active`, `autoPlay`, `startAfter`, `duration`, `repeat`, + `reducedMotion`, `pauseWhenOffscreen`, `fadeCurve`, `debugFrozenAt`). Every + field is nullable and means *inherit*; `colors`, `active`, and + `borderRadius` stay on the widget as shorthands. +- `BorderBeamTheme` / `BorderBeamThemeData` supply defaults to a subtree; + nested themes merge field by field. +- `BorderBeam.overlay` paints a beam with no child, sized by its parent. +- `BeamSync` runs a subtree's beams off one clock; a member that changes its + `cycle` retimes only itself. +- `BorderBeam.progress`, `follow`, `strengthListenable`, and + `speedListenable` drive the beam without a controller. Releasing `follow` + hands the sweep back where it is, keeping a bouncing beam's direction and + staying out of a `cycleGap` rest. `speedListenable` wins over a + controller's `speed`, and reduced motion's `slow` quarters whichever rate + applies. +- `BeamShape.segment` with `BeamSegment`, `BeamAnchor`, and `BeamCorner` + lights part of the border; `BeamShape.dashes` breaks it into dashes; + per-corner, direction-aware radii; stadiums; `ringOffset`. +- `BeamTiming.cycleGap` (changing only the gap keeps the sweep where it is), + `direction` (`forward` / `reverse` / `bounce`), and `phaseOffset`; + `BeamStyle.hueMode` (`pingPong` / `continuous` / `none`). +- `BeamPlayback.repeat`, four `reducedMotion` behaviours (`staticFrame`, + `hide`, `slow`, `animate`), `pauseWhenOffscreen`, `fadeCurve` with + `BeamPlayback.cssEase`, and `debugFrozenAt`, which can be switched on and + off at runtime. +- `BorderBeamController.pulse()` and `flash()`, one-shot brightness accents + that, like the fades, run in real time. +- `BeamDecoration` (which honours `playback.repeat`), and the + `BeamFocusRing`, `BeamHover`, and `BeamPress` wrappers. -#### Engine +### Changed -- The transcribed rotate stop tables, line geometry, and pulse constants moved - into `lib/src/constants/`, with rendering unchanged. -- Every new style and shape option folds into layers each variant already - composites, so the per-variant `saveLayer` budget holds under any - combination. +- **Material comes from `material_ui`, and the floor is Flutter 3.47 (Dart + 3.13).** Flutter 3.47 deprecated `package:flutter/material.dart` in favour + of the standalone `material_ui` package, and the package now depends on + `material_ui` alone. Its `Theme` and `ColorScheme` are separate types from + the framework's, so `BeamTheme.auto` reads a `material_ui` theme and + `BeamColors.fromScheme` takes a `material_ui` `ColorScheme`. An app still on + `package:flutter/material.dart` should migrate (`dart fix --apply + --code=migrate_design_widgets`) or set `BeamStyle.theme`; until then `auto` + tunes for a light surface. +- **Every golden was regenerated.** Each effect is rebuilt from 0.1's + layers and checked against it side by side, but blurs evaluated + analytically are not pixel-identical to blur filters, and the pulse + breathes differently (below). +- **Fades glide.** Toggling `active` fades on critically damped springs + (Apple's `.smooth`): about 0.5s in and a gentler 0.6s out, easing from + rest and settling without overshoot. `BeamPlayback.fadeCurve` swaps in + your own curve. +- **`pulse` breathes like a breath.** Each corner's light swells a little + quicker than it fades back, on Apple's ease-in-out, instead of an even + swing. +- **`small` is folded into `rotate`.** `rotate`'s glow scales with the box, so + one effect reads on a chip and on a full-screen surface. The default radius + is 16 for every effect. +- **`pulseInside` is `pulse`.** +- **Default timings:** `rotate`'s cycle is 2.4s (was 1.96s). `line`'s two + hue tracks both follow `huePeriod` — the bloom's period is `huePeriod` + (8s by default) and the stroke's one and a half times it, the same 8s and + 12s as 0.1 — so `bloomHuePeriod` is gone. +- **Palettes are stop rings.** A palette is a ring of colour stops rather + than a list of blob specs. The four original presets and the seven extras + are given as stops placed where 0.1 put their glows. The originals keep + their hand-tuned blob tables behind them, and the extras keep cycling their + own colours over `colorful`'s tables, as in 0.1; every other palette is + drawn by sampling its stops over `colorful`'s tables. `mono` keeps its + half-opacity layers. +- **`BeamColors.lerp`** clamps `t` to 0–1 and mixes gamma-aware at eight + sampled positions; **`scaleAlpha`** scales each stop's alpha. +- **`hueRange` is `hueShift`.** +- **Every effect runs at the display rate**; the pulse variants' ~30fps cap is + gone. +- **Superellipse corners** are computed in the shader and follow Flutter's own + `RSuperellipse` construction, so pills, circles, and large radii sit on + `RoundedSuperellipseBorder` as exactly as ordinary corners do. +- **`BeamFocusRing`** defaults to `BeamEffect.rotate()` (was `small`, whose + compact look `rotate` takes on small controls); **`BeamPress`** defaults to + `BeamEffect.pulse()` (was `pulseInside`). +- **`BorderBeamController.start()` resumes a paused beam** from its held + frame, as `resume()` does (it was a no-op while the beam was showing). On a + hidden or fading-out beam it still fades in, and on a running one it still + does nothing. ### Removed -- `BeamPlayback.respectReducedMotion`, replaced by - `BeamPlayback.reducedMotion`; `reducedMotion: BeamReducedMotion.animate` is - what `respectReducedMotion: false` used to say. -- The `sprung` dependency. The fade envelope is eased by the in-package - `FadeSpringCurve` (mass 1, stiffness 180, damping 20 — the same spring, - reproduced bit-for-bit with a linear end correction so t=1 lands on 1), so - the package depends on the Flutter SDK alone. -- The example app's boilerplate and its unused `cupertino_icons` dependency. +- `BeamVariant` and the named constructors `BorderBeam.rotate`, `.small`, + `.line`, `.pulseInside`, and `.pulseOutside` — use `effect:`. +- `pulseOutside`'s outward halo. Nothing in 0.2.0 paints it: + `BeamEffect.pulse()` breathes on the border instead, and + `BeamEffect.rotate(comet: true)` carries light outside the box. +- `BeamThemeConfig`, `BeamBlob`, `LineBlob`, `BeamColors.custom`, + `BeamColors.spec`, `BeamContour`, `BeamPathContour`, + `BeamPulseOutsideTuning`, and `BeamStyle.pulseOutsideStock`. +- `BeamStyle`: `brightness`, `saturation`, `staticColors`, + `strokeOpacityFactor`, `innerOpacityFactor`, `bloomOpacityFactor`, + `glowBoost`, `coreBlur`, `bloomBlur`, `glowBrightness`, `glowSaturation`, + `tailLength`, `glowSpread`, `comet`, `sparkle`, `segments`, + `innerSizeScale`, `renderScale`, `pulseOutsideTuning`, and `themeConfig`. +- `BeamShape`: `edge`, `contour`, and `wrapCorners`. Outlines are rounded + rectangles with circular or superellipse corners; arbitrary paths are not + supported. +- `BeamTiming`: `beamCount`, `bloomHuePeriod`, `breatheFactor`, + `spikeFactor`, and `spike2Factor`. +- `BorderBeamController.attach`/`detach` and `BeamSync.clockOf`/ + `reducedMotionOf`. They were plumbing between the widgets, documented as + "do not call", and took or returned a clock type the package never + exported. +- The frame-rate cap on the pulse variants. +- The transcribed upstream constants (`lib/src/constants/`), the vendored + upstream spec and its parity test, `tool/spec/`, and the upstream-drift + workflow. ### Fixed -- A beam laid out thinner than twice its border width no longer asserts in - `RRect` construction: `BeamRingGeometry` returns empty contours for empty or - inverted rects, floors corner radii at zero, and paints the whole outer - shape as the ring for sub-2px boxes. -- The reduced-motion static frame keeps the traveling variants' mid-cycle - geometry but no longer samples the hue ping-pong, so it shows the palette's - own colors, as documented. -- Changing `cycle` mid-run rescales the clock so every cycle-derived track - keeps its fraction, while the fixed-period hue tracks are held by a - resolver-side time offset — the beam speeds up or slows down without a snap, - mid-fade included. -- Reduced motion is tracked where its change is delivered: turning it on - pauses the clock, turning it off resumes only a pause it caused (a - controller pause wins) or starts an autoplay beam that never got to run. - `build` no longer mutates the clock. -- `BeamColors.spec` derives its fallback tables directly instead of through a - throwaway custom palette, and the phase resolver resolves `PulseParams` - once. +- **Fades run in real time.** `speed`, `seek`, and a retime move only the + animation; none of them stretches, skips, or replays a fade, and neither + does reduced motion's `slow`. Pausing still freezes the fade. +- A `BorderBeamController` can move from one beam to another in the same + frame. +- Reduced motion holds a controller-driven beam too. Under `staticFrame` or + `hide`, `start()` and `resume()` show the still frame (or nothing) without + ticking, and turning reduced motion off lets the beam run on. +- `BeamFocusRing` no longer overrides `style.colors` and theme colours with + its `ocean` default. `colors` is now nullable: null inherits, and `ocean` + applies only when nothing else sets colours. +- A NaN or infinite style or shape number is treated as unset (an infinite + `strength` clamps instead), as are a NaN `progress` and a non-finite + `follow`, so the shader is never handed one. + +### Migrating to 0.2.0 + +| Before | 0.2.0 | +| --- | --- | +| `import 'package:flutter_border_beam/flutter_border_beam.dart'` | unchanged | +| `import 'package:flutter/material.dart'` in your app | `import 'package:material_ui/material_ui.dart'` (`dart fix --apply --code=migrate_design_widgets`), so `BeamTheme.auto` sees your theme — or set `BeamStyle(theme: …)` | +| `BorderBeam.rotate(…)` | `BorderBeam(…)` — `rotate` is the default — or `BorderBeam(effect: const BeamEffect.rotate(), …)` | +| `BorderBeam.small(…)` | `BorderBeam(effect: const BeamEffect.rotate(), borderRadius: 32, …)` — set the radius you relied on; the default is 16 | +| `BorderBeam.line(…)` | `BorderBeam(effect: const BeamEffect.line(), …)` | +| `BorderBeam.pulseInside(…)` | `BorderBeam(effect: const BeamEffect.pulse(), …)` | +| `BorderBeam.pulseOutside(…)` | no direct replacement — `BorderBeam(effect: const BeamEffect.pulse(), …)` for a breathing state on the border, or `BeamEffect.rotate(comet: true)` for light that reaches outside the box | +| `BorderBeam(variant: BeamVariant.x, …)` | `BorderBeam(effect: const BeamEffect.x(), …)` | +| `BeamDecoration(variant: …)` | `BeamDecoration(effect: …)`, in `foregroundDecoration:` for every effect | +| `BeamFocusRing` / `BeamHover` / `BeamPress` `(variant: …)` | `(effect: …)` | +| `BeamVariant.defaultHuePeriod` and friends | `BeamEffect.defaultHuePeriod`, `defaultCycle`, `defaultCycleGap`, `defaultHueMode` | +| `BeamShape(edge: e)` | `BeamEffect.line(edge: e)` | +| `BeamShape(wrapCorners: true)` on a line | `BeamShape(segment: BeamSegment.bottomEdge)` (or the preset for your edge) with `BeamEffect.line()` | +| `BeamShape(contour: …)`, `BeamContour`, `BeamPathContour` | no replacement | +| `BeamStyle(tailLength: x)` | `BeamEffect.rotate(length: x)` | +| `BeamStyle(comet: true)` | `BeamEffect.rotate(comet: true)` | +| `BeamTiming(beamCount: n)` | `BeamEffect.rotate(count: n)` (1–4) | +| `BeamStyle(segments: n)` | `BeamShape(dashes: n)` | +| `BeamStyle(glowSpread: x)` | `BeamStyle(glow: x)` | +| `glowBoost`, `coreBlur`, `bloomBlur`, `glowBrightness`, `glowSaturation`, `innerSizeScale` | `BeamStyle(glow: …)` | +| `strokeOpacityFactor`, `innerOpacityFactor`, `bloomOpacityFactor` | `BeamStyle(strength: …)` for the whole beam, `glow` for the glows | +| `hueRange: x` | `BeamStyle(hueShift: x)` | +| `staticColors: true` | `BeamStyle(hueMode: BeamHueMode.none)` | +| `brightness:`, `saturation:` | no replacement — adjust the palette's colours; `hueBase` still rotates the hue | +| `sparkle`, `renderScale` | no replacement; glows scale with the box | +| `themeConfig`, `BeamThemeConfig` | no replacement — `theme`, `strength`, and `glow` | +| `pulseOutsideTuning`, `BeamPulseOutsideTuning`, `BeamStyle.pulseOutsideStock` | no replacement | +| `bloomHuePeriod` | `BeamTiming(huePeriod: …)`, which paces both of `line`'s hue tracks | +| `breatheFactor`, `spikeFactor`, `spike2Factor` | no replacement | +| `BeamColors.custom(colors)` / `custom(colors, base: …)` | `BeamColors(colors)`, optionally with `stops:` | +| `BeamColors.spec(…)`, `BeamBlob`, `LineBlob` | `BeamColors(colors, stops: …)` | +| 0.1.0 `useSuperellipse: true` | `shape: const BeamShape(superellipse: true)` | +| 0.1.0 `borderWidth:` | `shape: BeamShape(borderWidth: …)` | +| 0.1.0 `cycleDuration: d` | `timing: BeamTiming(cycle: d)` | +| 0.1.0 `strength:`, `theme:`, `hueBase:` | `style: BeamStyle(…)` | +| 0.1.0 `autoPlay:`, `startAfter:`, `duration:` | `playback: BeamPlayback(…)` | +| 0.1.0 `respectReducedMotion: false` | `playback: const BeamPlayback(reducedMotion: BeamReducedMotion.animate)` | ### Tooling & CI -- CI runs five independent jobs: format/analyze/test with coverage to Codecov - (tokenless OIDC) and a publish dry-run on the pinned Flutter the goldens - were rendered with; goldens on macOS with failure diffs uploaded as - artifacts; the declared 3.35.0 lower bound built and tested as a hard gate; - pana with a 20-point floor; and the example app analyzed, tested, and built - for web. -- Pushing a `vX.Y.Z` tag runs `release.yaml`: it checks the tag against the - pubspec and the changelog, re-runs the gate, publishes to pub.dev through - `dart-lang/setup-dart`'s OIDC token, and creates the GitHub Release from - that changelog section. -- The upstream library's machine-readable `spec/beam-spec.json` is vendored at - `test/fixtures/beam-spec.json` (with its provenance in - `test/fixtures/UPSTREAM`), refreshed by `tool/spec/refresh.sh`, and asserted - table by table by `test/constants/spec_parity_test.dart`. - `.github/workflows/upstream_drift.yaml` hashes upstream's `src/styles.ts`, - so a styles change that never reached the spec generator still raises the - alarm. `lib/src/constants/upstream.dart` records the tracked versions and - the source repository in one place. -- Dependabot groups weekly action and pub bumps; `codecov.yml` keeps coverage - informational. -- The example app exposes the whole API in an interactive playground with a - shareable link, and is deployed to GitHub Pages. -- Tests: a counting canvas pins each variant's per-frame `saveLayer` count - (rotate 4, small 3, line 4, pulseInside 4, pulseOutside 3) exactly, with - save/restore balance; lifecycle tests prove no ticker outlives disposal - mid-fade, a variant swap, `TickerMode`, or a controller that outlives its - beam; boundary tests sweep degenerate boxes, radius and width extremes, and - out-of-range parameters; seeded property tests check the phase resolver's - purity, per-cycle periodicity, and field ranges; and the goldens cover every - variant × theme × palette, with a later freeze for the two traveling - variants. +- CI pins Flutter 3.50.0, the SDK the goldens are generated on; the `min-sdk` + job builds and tests the declared 3.47.0 lower bound. +- `test/render/` holds the renderer's contracts: the frame budget (one draw, + no `saveLayer`, clip, or image / mask filter), the uniform layout (parsed + from `shaders/beam.frag` against `beamUniformFloats`), the Dart outline + mirror, per-effect emission sanity, degenerate geometry, a paint smoke sweep + through the real shader, and where light lands. +- Golden families: `beam_`, `palette_`, `motion_`, `surface_`, `widgets_`. +- Removed the upstream spec parity test, its fixtures, `tool/spec/`, and + `.github/workflows/upstream_drift.yaml`. +- CI runs format / analyze / test with coverage, macOS goldens, the minimum + SDK, pana, and the example app (analyze and a web build); pushing a + `vX.Y.Z` tag publishes through `release.yaml` over GitHub OIDC. ### Docs -- The README is rebuilt around a per-concept structure, with a full field - table (default and applicable variants) for each of the four value objects, - and sections for accessibility, performance, upstream parity, and how the - engine works. -- New guides in [`doc/`](doc): variants, palettes, shape, motion, theming, - performance, accessibility, parity, and architecture. -- `CLAUDE.md` keeps the commands and hard rules and points at - [doc/architecture.md](doc/architecture.md) for the module deep-dive. +- README rewritten for the effect model and the shader renderer, with a + Performance section (one draw, 120Hz setup, `precache`, Impeller notes). +- [`doc/effects.md`](doc/effects.md) replaces `doc/variants.md`; + `doc/parity.md` is gone; [`doc/architecture.md`](doc/architecture.md) + describes the frame pipeline, the light model, and the Dart / shader + contracts. +- [`example/`](example) is a one-screen showcase of the three effects, each + on the kind of widget it is made for, with palette swatches and a theme + toggle; its web build is the + [live demo](https://simplifyjobs.github.io/flutter_border_beam/). ## 0.1.0 diff --git a/CLAUDE.md b/CLAUDE.md index 7d8881e..5012c6f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,60 +1,87 @@ # flutter_border_beam — agent guide -Flutter package: animated border beam effects. A faithful port of the +Flutter package: animated light around a widget's border. Three effects +(`rotate`, `line`, `pulse`), all drawn by **one fragment shader in one draw +call per frame** — no `saveLayer`, blurs, or clips. Originally ported from the [border-beam](https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam) -React library (v1.4.0, MIT, by Jakub Antalik). +React library (MIT, by Jakub Antalik); since 0.2.0 an independent native +renderer that does not track upstream. ## Commands - `flutter analyze` — must stay at zero issues (lints include `public_member_api_docs`). -- `flutter test` — full suite (unit + widget + smoke + goldens). +- `flutter test` — full suite (unit + widget + render + goldens). - `flutter test --exclude-tags golden` — everything except goldens (use on non-macOS). -- `flutter test --update-goldens --tags golden` — regenerate goldens (macOS only; goldens are pinned to macOS rendering). +- `flutter test --update-goldens --tags golden` — regenerate goldens (macOS only, on the Flutter version `ci.yaml` pins — 3.50.0). Regenerate only the scenes you touched (`--plain-name`). - `dart format .` — formatting. -- `cd example && flutter run` — demo gallery app (React-demo-styled; tokens in `example/lib/src/demo_theme.dart`). +- `cd example && flutter run` — one-screen showcase app: swipe between the three effects, each on its own mock surface with continuous (superellipse) corners; palette swatches and a theme toggle (tokens in `example/lib/src/tokens.dart`); `--dart-define`s `START`, `PALETTE`, `THEME` set the opening state for captures. No tests — CI gates it on `flutter analyze --fatal-infos` and a web build. - `tool/record_demo.sh --target lib/showcase.dart --prefix SHOWCASE --contact` — record a demo reel mp4 into `.demos/` (needs a booted iOS simulator + ffmpeg). Reels use `example/lib/demo_harness.dart`'s marker contract (`::START/END`, `:DONE`); new reels are just a map of name → scene widget. -- `dart pub publish --dry-run` — pre-publish validation. +- `dart pub publish --dry-run` — pre-publish validation. `shaders/beam.frag` must be in the archive (`.pubignore` must never exclude `shaders/`). - **Cutting a release** — bump `version:` in `pubspec.yaml`, add a `## ` section to `CHANGELOG.md`, merge to `main`, then push the matching tag: `git tag v && git push origin v`. `.github/workflows/release.yaml` verifies the tag against the pubspec and the changelog, re-runs format/analyze/test, publishes to pub.dev over GitHub OIDC (no secrets), and creates the GitHub Release from that changelog section; a version with a `-suffix` is marked prerelease. Goldens are verified only by the macOS `goldens` job in `ci.yaml` — the release job runs on ubuntu and skips them, so tag a commit that is green on `main`. - **One-time, before the first automated release** — publish manually with `flutter pub publish` (pub.dev only automates publishing for packages that already exist), then enable pub.dev Admin → Automated publishing for `SimplifyJobs/flutter_border_beam` with tag pattern `v{{version}}`. +- **Bumping the Flutter pin** — change `FLUTTER_VERSION` in `ci.yaml`, `release.yaml`, and `pages.yaml` together, in the same commit as regenerated goldens. ## Architecture Everything animated is a **pure function of elapsed time** — one `Ticker` per -widget (`BeamClock`), or one per `BeamSync` group, mirroring the React -library's single shared rAF loop. No `AnimationController`s; phases are -recomputed from `elapsedSeconds` each frame. +widget (`BeamClock`), or one per `BeamSync` group. No `AnimationController`s. +A frame: -Full module deep-dive, the frame pipeline, and the invariants in prose: +```text +Ticker → BeamClock → BeamPhaseResolver → effect emitter → BeamFrameData → BeamRenderer → one shader draw +``` + +The look is the reference design's layer construction evaluated per pixel: +up to three layers (inner glow / hairline stroke / bloom), each a stack of +soft radial **blobs** (palette blob tables from `lib/src/look/`) with a conic +**overlay** (head highlight, bloom band), an inset shadow, a **geometry** (1px +ring AA'd over one device pixel, fill, blurred ring clipped to the shape, or a +glow outside the shape that fades out — rotate's comet, the only light past +the outline), a **window** (rotating conic table or radial ellipse on an +edge), an edge fade, a colour filter folded into its colours on the CPU, and +an opacity. Every blur of the design is analytic: a blurred ring is +`w/σ·φ(d/σ)`, a blurred blob is an energy-preserving gaussian (truncated where +the design cuts it), a blurred outside glow is `Φ`. + +Full pipeline, layer model, design data, uniform layout, and invariants in +prose: **[doc/architecture.md](doc/architecture.md)** — update it when the layout moves. The map below is the index. -- `lib/flutter_border_beam.dart` — barrel; ONLY `BorderBeam`, `BorderBeamController`, `BorderBeamTheme`/`BorderBeamThemeData`, `BeamSync`, `BeamVariant`, `BeamColors`/`BeamSeedHarmony`, `BeamBlob`/`LineBlob`, `BeamTheme`, `BeamThemeConfig`, the four value objects (`BeamStyle`, `BeamShape`, `BeamTiming`, `BeamPlayback`), the option types from `beam_options.dart`, and the four widgets (`BeamDecoration`, `BeamFocusRing`, `BeamHover`, `BeamPress`) are public. -- `lib/src/border_beam.dart` — widget: a generic constructor taking a `BeamVariant`, `BorderBeam.overlay`, and 5 named ones; three shorthands (`colors`/`active`/`borderRadius`) over the value objects; the driven inputs (`progress`, `follow`, `strengthListenable`, `speedListenable`); and scheduling/lifecycle. Controller attached ⇒ it owns playback exclusively (the resolved playback asserts `startAfter`/`duration` are null, and the controller's `speed` replaces `timing.speed`). `speed` never reaches `BeamConfig` — it is applied to the clock and deliberately kept out of the config-cache key. -- `lib/src/border_beam_theme.dart` — `BorderBeamTheme` (`InheritedWidget`) + `BorderBeamThemeData`. `of` walks every enclosing scope, depends on each, and merges them outside-in so nested themes compose. -- `lib/src/beam_sync.dart` — `BeamSync` + its internal scope: one clock for a whole subtree. The group owns playback; a member's `BorderBeamController` asserts. +- `lib/flutter_border_beam.dart` — barrel; ONLY `BorderBeam`, `BorderBeamController`, `BorderBeamTheme`/`BorderBeamThemeData`, `BeamSync`, `BeamEffect` + its three subclasses (`RotateEffect`, `LineEffect`, `PulseEffect`), `BeamColors`/`BeamSeedHarmony`, the option types (`BeamDirection`, `BeamEdge`, `BeamHueMode`, `BeamReducedMotion`, `BeamRepeat`), `BeamAnchor`/`BeamCorner`/`BeamSegment`, `BeamTheme`, the four value objects (`BeamStyle`, `BeamShape`, `BeamTiming`, `BeamPlayback`), and the four widgets are public. Nothing in `render/` or `effects/effect_emitters.dart` is exported. +- `lib/src/border_beam.dart` — widget: `BorderBeam({effect, …})` and `BorderBeam.overlay`; three shorthands (`colors`/`active`/`borderRadius`) over the value objects; the driven inputs (`progress`, `follow`, `strengthListenable`, `speedListenable`); `BorderBeam.precache()`; scheduling/lifecycle. Controller attached ⇒ it owns playback exclusively (the resolved playback asserts `startAfter`/`duration` are null, and the controller's `speed` replaces `timing.speed`). `speed` never reaches `BeamConfig` — it is applied to the clock and kept out of the config-cache key. +- `lib/src/border_beam_theme.dart` — `BorderBeamTheme` (`InheritedWidget`) + `BorderBeamThemeData` (`effect`, `style`, `shape`, `timing`, `playback`). `of` walks every enclosing scope, depends on each, and merges them outside-in. +- `lib/src/beam_sync.dart` — `BeamSync` + its internal scope: one clock for a subtree. The group owns playback; a member's `BorderBeamController` asserts. - `lib/src/border_beam_controller.dart` — `BorderBeamController`, a `ChangeNotifier` over one clock (`start`/`stop`/`pause`/`resume`/`seek`/`speed`, plus the one-shot `pulse`/`flash` accents). -- `lib/src/animation/` — `beam_clock.dart` (ticker, speed, pause, fade envelopes, optional fps cap, pulse/flash boosts), `spring_curve.dart` (the in-package fade spring: mass 1, stiffness 180, damping 20), `oscillator.dart` (pingPong + the 17-oscillator pulse bank), `beam_phases.dart` (per-frame value object + keyframe sampling). -- `lib/src/painting/` — `beam_painter.dart` (one `CustomPainter`, repaint driven by the clock, `behind`/`above` passes), `variant_strategy.dart` (the strategy interface, incl. `preferredFps`), `strategies/` (`rotate_strategy.dart`, `line_strategy.dart`, `pulse_inner_strategy.dart`, `pulse_outer_strategy.dart`, `pulse_common.dart`), `ring_geometry.dart` (rrect + `RSuperellipse` ring via `Path.combine` difference, contour and ring-offset handling), `gradient_builders.dart`, `color_matrix.dart` (hue/brightness/saturation matrices), `layer_utils.dart`. -- `lib/src/constants/` — **verbatim transcriptions** of the React source's tables (`palettes.dart`, `theme_presets.dart`, `pulse_tables.dart`, `pulse_params.dart`, `pulse_constants.dart`, `line_keyframes.dart`, `line_geometry.dart`, `rotate_stops.dart`), plus `upstream.dart` (internal; the single place `upstreamLibraryVersion` / `upstreamSpecVersion` / `upstreamRepository` live) and `extra_palettes.dart` — the seven Flutter-only presets, which are **not** transcriptions and are safe to edit. `tool/spec/refresh.sh` re-vendors upstream's `spec/beam-spec.json` into `test/fixtures/`; `test/constants/spec_parity_test.dart` asserts every table against it, and `.github/workflows/upstream_drift.yaml` hashes upstream's `src/styles.ts` so a change that never reached the spec generator still raises the alarm. -- `lib/src/models/` — public/internal data types. The four public value objects (`beam_style.dart`, `beam_shape.dart`, `beam_timing.dart`, `beam_playback.dart`) are all-nullable, `const`, with `copyWith`/`merge`/`==`; a null field means *inherit*. `beam_options.dart` holds the small option types those fields take (`BeamHueMode`, `BeamDirection`, `BeamEdge`, `BeamReducedMotion`, `BeamRepeat`, and the `BeamContour`/`BeamPathContour` pair — a contour is a config-cache key, so every implementer overrides `==`/`hashCode`). `beam_colors.dart` is the sealed `BeamColors` hierarchy (preset/custom/seed/scheme/lerp/scaled/spec) with a value-keyed LRU memo; `beam_palette.dart`/`beam_blob.dart` are the resolved tables; `beam_theme.dart`/`beam_theme_config.dart` the brightness selector and per-variant×brightness preset. `BeamConfig.resolve({variant, palette, brightness, style, shape, timing, textDirection})` flattens them into the painter's config and mirrors the React component's computed values (per-variant default durations and radii, the line 13° hue cap, mono forcing static colors); it carries the timing tracks (`gapSeconds`, hue periods, breathe/spike factors) and a per-corner resolved `BorderRadius`, and is value-equal so `BeamPainter.shouldRepaint` compares configs. -- `lib/src/widgets/` — `beam_decoration.dart` (the engine as a `Decoration`; no context, so brightness and `BorderBeamThemeData` are arguments and reduced motion is inert), `beam_focus_ring.dart`, `beam_hover.dart`, `beam_press.dart`. -- **Tests** — `test/models/` (value objects, config resolution, colors, variants), `test/animation/` (clock, spring, oscillators, phases, travel, periods, the seeded property test), `test/painting/` (ring geometry, color matrices, surface features, the saveLayer budget, boundaries, the paint smoke sweep), `test/widget/` (`BorderBeam` itself: lifecycle, updates, shorthands, theming, sync, speed, progress, motion, cycle gap), `test/widgets/` (the four widgets), `test/golden/` (seven golden families), `test/constants/` + `test/fixtures/` (the transcription check). +- `lib/src/effects/` — `beam_effect.dart` (sealed `BeamEffect`: `rotate({length, count, comet})`, `line({edge})`, `pulse`; each knows `travels`, `defaultCycle`, `defaultCycleGap`, `defaultHueMode`, `defaultHuePeriod`; `values` = [rotate, line, pulse]), `effect_emitters.dart` (`emitEffect` — one private emitter per effect writing its layers into `BeamFrameData`; `BeamFrame` context; `applyTrack`/`segmentTrack`; `conicFraction`, shared with `follow`). rotate switches to the compact chip tables at a shortest side ≤ 56px, and `comet` swaps its blurred-ring bloom for the outside `glow`; line runs on its edge (mirrored into reading order) or, with a segment, in path space, with two ping-pong hue tracks off one `huePeriod` (bloom 1×, stroke 1.5×, capped swing); pulse samples the 17-oscillator bank per frame, its corner opacities on a breath (quicker swell than fade). +- `lib/src/look/` — the design data, owned and tunable (goldens move when it does): `palette_tables.dart` (`BeamLookTables` + the 4 original palettes' blob tables), `extra_palettes.dart` (the 7 extras' colours, cycled over colorful's tables), `beam_look.dart` (`BeamLook.tablesFor`: own / cycled / sampled-from-stops tables, memoized per palette), `layer_presets.dart` (per-family × surface layer opacities, inset shadow, brightness, saturation), `rotate_look.dart`, `line_look.dart` (keyframes + geometry + `sampleKeyframes`), `pulse_tables.dart`, `pulse_look.dart` (breathing params, oscillator bank, `breath`), `look_blobs.dart`. +- `lib/src/render/` — `beam_renderer.dart` (`BeamRenderer`: per-beam `FragmentShader`/`Paint`/`BeamFrameData`, the upload, the draw bounds), `beam_frame.dart` (`BeamFrameData` — the uniform buffer in shader order and its writers; `BeamGeometry`/`BeamWindow`/`BeamTable`/`BeamBlobSpace`; `beamUniformFloats` = 672; blob slots 14/10/10; 16-stop tables), `beam_outline.dart` (`BeamOutline`, the Dart mirror of the shader's `outline()`, including a port of Flutter's `RSuperellipse` construction — per corner, two halves of superellipse-then-arc keyed on edge-to-radius ratio, `squircleReach` 2.5 radii), `beam_painter.dart` (the `CustomPainter`; repaint = clock ⊕ shader-ready ⊕ progress ⊕ strength), `beam_program.dart` (shared `FragmentProgram`, loaded once), `color_math.dart` (`mixColor`, `samplePalette` — CPU-only; the shader never blends palette stops, blobs arrive coloured). `BeamFrameData.setFilter` builds the hue-rotate → brightness → saturate matrix, which `finish` always folds into the layer's colours on the CPU. +- `shaders/beam.frag` — the layer model per pixel. Header documents it; the uniform block is a contract with `beam_frame.dart`. +- `lib/src/animation/` — `beam_clock.dart` (ticker, speed, pause, seek, retime, fade envelopes, pulse/flash boosts; no fps cap; `elapsedSeconds` is the speed-scaled animation timeline, `activeSeconds` unscaled time while ticking — fades, boosts, and `duration` run on `activeSeconds`, so `speed`/`seek`/`retime` move only the animation, never a fade, and pause freezes both), `spring_curve.dart` (`BeamSpringCurve`, Apple-style damping ratio + response: `fadeIn` ζ 1, `fadeOut` ζ 1 with a longer response, `pop` ζ 0.75 for the accents' rise; `BeamClock.fadeInSeconds`/`fadeOutSeconds` are their settling times), `beam_phases.dart` (`BeamFramePhases` + `BeamPhaseResolver`: fade incl. gap envelope, hue, travellers, `reversedNow`, ambient `cycles`, `driven`). +- `lib/src/models/` — the four public value objects (`beam_style.dart`, `beam_shape.dart`, `beam_timing.dart`, `beam_playback.dart`) are all-nullable, `const`, with `copyWith`/`merge`/`==`; null means *inherit*. `beam_options.dart` (enums + `BeamRepeat`), `beam_segment.dart` (`BeamAnchor`/`BeamCorner`/`BeamSegment`), `beam_colors.dart` (sealed `BeamColors`: preset/stops/solid/seed/lerp/scaled, value-keyed LRU memo), `beam_presets.dart` (the 19 presets' stops; each original points at its tables in `look/palette_tables.dart`, each extra at its table colours in `look/extra_palettes.dart`), `beam_palette.dart` (resolved ring of ≤ 8 stops, `maxPaletteStops`, carrying `tables`/`tableColors`/`mono`), `beam_theme.dart`, `model_validation.dart` (release-mode checks). `BeamConfig.resolve({effect, palette, brightness, style, shape, timing, textDirection})` settles every inherited value (effect defaults, 16px radius, fixed-hue palettes forcing `BeamHueMode.none`) into one value-equal config; `BeamPainter.shouldRepaint` compares configs. +- `lib/src/widgets/` — `beam_decoration.dart` (the renderer as a `Decoration`; no context, so brightness and `BorderBeamThemeData` are arguments and reduced motion is inert), `beam_focus_ring.dart`, `beam_hover.dart`, `beam_press.dart`. ## Hard rules -1. **Never tweak values in `lib/src/constants/`** — they are transcribed 1:1 from `src/styles.ts` of the React source (clone: `git clone https://github.com/Jakubantalik/Libraries /tmp/border-beam-upstream`). Visual parity depends on them, and `test/constants/` asserts them against fixtures extracted from that source. If a value looks wrong, verify against the source first. `extra_palettes.dart` is the exception: it holds the Flutter-only presets and is not a transcription. -2. **saveLayer budget — the measured per-variant table.** One frame (`paintBehind` + `paintAbove`) issues: **rotate 4, small 3, line 4, pulseInside 4, pulseOutside 3**. `test/painting/save_layer_budget_test.dart` measures every variant × brightness × palette × time sample through a counting canvas and asserts the count *exactly* (plus save/restore balance), so a regression and an improvement both fail until the table is updated in both places. Each entry is a layer the variant genuinely composites — inner, stroke, bloom, the mask sub-layer where two masks intersect (rotate/line/pulseInside), and pulse-outside's two behind-child glows. Hue/brightness/saturation are folded into gradient colors on the CPU (`BeamColorMatrix.transform`) — never add a saveLayer just to carry a `ColorFilter`; a filter rides on a layer that exists anyway, and blur is the only filter allowed to justify a layer of its own. -3. **CSS↔Flutter mapping conventions** (see `gradient_builders.dart`): CSS conic gradients start at 12 o'clock — `SweepGradient` needs the −90° rotation baked in; CSS `radial-gradient(ellipse W H ...)` sizes are RADII; CSS `filter: blur(Npx)` maps to sigma = N; gradient fades to `color.withValues(alpha: 0)` (never `Color(0x00000000)`, which lerps through black). -4. Layer opacity is a multiplied chain (fade × preset × mono × hook × strength), clamped at paint time — presets legitimately exceed 1 (line/dark stroke = 1.14). -5. The line variant does NOT use the mono ×0.5 opacity multiplier; its mono treatment is spike attenuation inside the bloom (see `LineStrategy._paintSpikes`). +1. **One draw call per frame; zero `saveLayer`, clip, `ImageFilter`, `MaskFilter`.** A lit frame is exactly one `drawRect`/`drawDRRect` whose paint carries the beam shader; a frame with no lit layer (fade, gap) draws nothing; saves and restores balance. `test/render/frame_budget_test.dart` asserts this across every effect × theme × palette subset × shape family × instant, plus effect options and driven progress. A blur in the design becomes analytic shader maths — never a layer, a blur, or a second draw. +2. **The uniform layout is a contract.** The `uniform` block in `shaders/beam.frag` and the offsets/slot counts in `lib/src/render/beam_frame.dart` change together, in one commit. Uniforms are `vec4`s and `vec4` arrays only (identical float layout on every backend), ≤ 896 floats (the 224 `vec4`s GLES 3.0 guarantees). Arrays are indexed only by constants and loop indices (SkSL strict ES2), so each layer has its own blob array and each table its own uniform. `test/render/uniform_layout_test.dart` parses the shader and checks types, array lengths against the Dart constants, loop bounds, the total, and the order: every `BeamFrameData` writer must land in the uniform the shader declares at that offset. +3. **`BeamOutline` mirrors the shader's `outline()` exactly** — corner model, distance, nearest-piece choice, and arc-length `u`. Emitters lay blobs along the outline with it, segments resolve against it, and `follow` maps the pointer with it. +4. **Fixed slots.** 14 blobs in layer 0, 10 in layers 1 and 2, 16 stops per conic table, ≤ 8 palette stops. `addBlob` drops extras silently; palettes with more stops are rejected at resolve. +5. **Nothing inside the shape reads `u`.** Inside the shape `u` jumps across the medial axis; inner glows are planar blobs (blobs laid along the outline are planar ellipses whose axes follow the normal) or path-space blobs kept within the edge fade. +6. **Emitters are pure and allocation-light per frame.** An emitter is a function of config, phases, outline, and the palette's tables; it writes into the renderer's reused `BeamFrameData`; table transforms use scratch lists, oscillator banks are cached per tuning, derived tables memoized per palette. +7. **Parity with the reference look is checked by eye, then pinned by goldens.** The original look (old goldens at `git show 85be4f8:test/golden/goldens/`) is the calibration: render side by side when retuning rotate/line/pulse. +8. **Don't quote or hard-code look values in docs** — tuning lives in `lib/src/look/` and the emitters and changes; docs describe behaviour. ## Testing conventions -- Goldens come in seven families, one file each: `beam_golden_test.dart` (variant × theme × palette), `palette_golden_test.dart` (the color factories and transforms), `motion_golden_test.dart` (direction, gap, multi-beam, driven progress), `surface_golden_test.dart` (shape: per-corner, stadium, superellipse, ring offset, contours), `research_golden_test.dart` (reference-implementation options: stock pulse-outside, pulse-inside wash, render scale), `segment_golden_test.dart` (partial-perimeter and corner-wrapped line travel), and `widgets_golden_test.dart` (`BeamDecoration` and the three interaction wrappers). A new scene belongs in the family that names its axis; add a file only for an axis none of them names, never one per feature. -- Golden scenes freeze the fake test clock at t=1.3s (post fade-in, mid-cycle) for every variant × theme × palette; the two traveling variants are captured a second time further along their sweep (`rotate_*_colorful_late` at 2.3s, `line_*_colorful_late` at 2.0s — inside the `beam-edge-fade` plateau, so the beam is at full strength). Regenerating on a different OS or Flutter version will produce diffs — keep goldens macOS-generated on the SDK `ci.yaml` pins. -- `test/painting/paint_smoke_test.dart` sweeps every variant×theme×palette×shape for "paints without throwing, produces pixels" — extend it when adding paint paths. -- `test/painting/boundary_test.dart` covers degenerate geometry (zero/1px/sliver boxes, radius past the short side, `borderWidth` 0) and out-of-range parameters, and pins `strength: 0` to painting *no* pixels in either pass. -- `test/animation/phase_property_test.dart` property-tests `BeamPhaseResolver.sample` over a seeded random sweep: purity, per-cycle periodicity of the cycle-driven tracks only, and the range of every phase field. -- `test/widget/border_beam_lifecycle_test.dart` asserts no ticker survives disposal mid-fade (per variant), a variant swap, `TickerMode`, or a controller outliving its beam — `tester.binding.transientCallbackCount` must return to 0. +- **Directories** — `test/models/` (value objects, config resolution, colours/palettes, effects, segments), `test/animation/` (clock, spring, phases, travel, seeded property test), `test/render/` (frame budget, uniform layout, `BeamOutline`, `beam_frame_test.dart` for frame sanity and per-effect layer structure, boundaries, paint smoke, `paint_structure_test.dart` for where light lands; helpers in `render_utils.dart`), `test/widget/` (`BorderBeam` itself: lifecycle, updates, shorthands, theming, sync, speed, progress, follow, motion, playback, cycle gap, shape), `test/widgets/` (the four widgets), `test/golden/`. +- **Pixel tests need the shader.** Anything that reads pixels or counts draws awaits `BorderBeam.precache()` in `setUpAll` (`setUpAll(BorderBeam.precache)`); before it resolves a beam paints nothing. +- **Golden families** (one file each, `@Tags(['golden'])`, staged by `test/golden/golden_scene.dart`): `beam_golden_test.dart` (effect × theme × palette, effect options), `palette_golden_test.dart` (every preset, the constructors and transforms), `motion_golden_test.dart` (direction, gap, count, phase offset, driven progress), `surface_golden_test.dart` (radii, superellipse, stadium, ring offset, border width, segments, dashes, line edges), `widgets_golden_test.dart` (`BeamDecoration` and the three wrappers). A new scene belongs in the family that names its axis; add a file only for an axis none of them names. +- **Goldens are macOS-generated on Flutter 3.50.0** (the `ci.yaml` pin) and run with `--tags golden`. Scenes freeze the fake clock at t = 1.3s (post fade-in, mid-cycle); travelling effects get a second `_late` capture at 2.0s. Regenerating on another OS or SDK produces diffs. +- **Structure tests over pixel pins.** `paint_structure_test.dart` compares regions of real frames against each other (lit here, dark there) rather than pinning values, so retuning the look leaves it standing. Prefer that style for new rendering behaviour; leave exact pixels to goldens. +- `test/render/paint_smoke_test.dart` sweeps every effect × theme × palette subset × shape family for "paints visible light through the real shader" — extend `render_utils.dart`'s `shapeVariety`/`paletteSubset` when adding a shape or palette path. +- `test/render/boundary_test.dart` covers degenerate geometry (zero/1px/sliver boxes, radius past the short side, `borderWidth` 0) and out-of-range parameters, asserts every packed uniform is finite, and pins `strength: 0` to painting *no* pixels. +- `test/animation/phase_property_test.dart` property-tests `BeamPhaseResolver.sample` over a seeded random sweep: purity, per-cycle periodicity, and the range of every phase field. +- `test/widget/border_beam_lifecycle_test.dart` asserts no ticker survives disposal mid-fade, an effect swap, `TickerMode`, or a controller outliving its beam — `tester.binding.transientCallbackCount` must return to 0. - Ticker tests: the first tick after `Ticker.start()` reports elapsed 0 — pump once before pumping durations. - A test that documents behavior the code does not yet have is marked `skip: 'defect: '` rather than rewritten to match the bug (`testWidgets` only takes a bool, so its reason goes in a comment). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 939912d..88c5ef3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,30 +1,29 @@ # Contributing to flutter_border_beam -Thanks for helping out. This package is a faithful Flutter port of the -[border-beam](https://github.com/Jakubantalik/border-beam) React library, and -most of its rules exist to keep that port honest. Read the two hard rules -below ([constants](#the-constants-rule) and the -[saveLayer budget](#the-savelayer-budget)) before changing anything under -`lib/src/constants/` or `lib/src/painting/` — they are what a reviewer will -check first. +Thanks for helping out. This package draws every beam with one fragment +shader in a single draw call, and most of its rules exist to keep it that +cheap. Read [the rendering rules](#the-rendering-rules) before changing +anything under `lib/src/render/`, `lib/src/effects/`, or `shaders/` — they are +what a reviewer will check first. [doc/architecture.md](doc/architecture.md) +explains how a frame is built. ## Setup -You need **Flutter ≥ 3.35** (the lower bound declared in `pubspec.yaml`; CI -tests that exact version in its `min-sdk` job) and, for goldens, **Flutter -3.44.2 on macOS**. +You need **Flutter ≥ 3.47** (the lower bound declared in `pubspec.yaml`, set +by `material_ui`; CI tests that exact version in its `min-sdk` job) and, for goldens, **Flutter +3.50.0 on macOS**. ```bash git clone https://github.com/SimplifyJobs/flutter_border_beam.git cd flutter_border_beam flutter pub get -# The demo gallery + interactive playground. It consumes the package by path, -# so it picks up your edits with a hot reload. +# The one-screen showcase. It consumes the package by path, so it picks up +# your edits with a hot reload — shader edits included. cd example && flutter pub get && flutter run ``` -The gallery is also live at +The showcase is also live at — useful for comparing your build against `main`. @@ -37,109 +36,122 @@ flutter test # everything, goldens included flutter test --exclude-tags golden # everything but goldens (non-macOS) flutter test --tags golden # goldens only (macOS) dart pub publish --dry-run # archive validation -cd example && flutter analyze && flutter test # the gallery is a CI gate too + +# The example has no tests; CI gates it on analyze and a web build. +cd example && flutter analyze --fatal-infos && flutter build web ``` `flutter analyze` must report **zero** issues, infos included. The lint set turns on `public_member_api_docs`, so every new public member — class, field, -enum value, constructor — needs a doc comment. That is not busywork: it is a -scored pub.dev signal, and CI's `pana` job fails when the score drops. +enum value, constructor — needs a doc comment. That is a scored pub.dev +signal, and CI's `pana` job fails when the score drops. ### Goldens -Golden files are **macOS-generated and pinned to Flutter 3.44.2**. Blur and -gradient rasterization shifts between Flutter releases and between platforms, -so a golden regenerated anywhere else will produce a diff that has nothing to -do with your change. CI runs them in a single `macos-latest` job. +Golden files are **macOS-generated and pinned to Flutter 3.50.0**. Shader +compilation and rasterization shift between Flutter releases and between +platforms, so a golden regenerated anywhere else produces a diff that has +nothing to do with your change. CI runs them in a single `macos-latest` job. -Regenerate **only the scenes you added**, by name: +Regenerate **only the scenes you added or deliberately changed**, by name: ```bash -flutter test --update-goldens --tags golden --plain-name 'rotate dark aurora' +flutter test --update-goldens --tags golden --plain-name 'rotate dark colorful' ``` -Never run a blanket `flutter test --update-goldens`. Rewriting existing -goldens is a rendering change, and a PR that does it must say in its -description **which** goldens changed and **why the pixels legitimately -moved** — a new blur radius, a corrected gradient stop, a Flutter pin bump. +Never run a blanket `flutter test --update-goldens` to make a failure go away. +Rewriting existing goldens is a rendering change, and a PR that does it must +say in its description **which** goldens changed and **why the pixels +legitimately moved** — a retuned effect, a shader fix, a Flutter pin bump. "The test was failing" is not a justification; that is the test doing its job. -If you must bump the Flutter pin, do it in the same commit as the regenerated +If you bump the Flutter pin, do it in the same commit as the regenerated goldens and update `FLUTTER_VERSION` in `.github/workflows/ci.yaml`, `.github/workflows/release.yaml`, and `.github/workflows/pages.yaml` together. Golden failures in CI upload as a `golden-failures` artifact — download it to see the actual/expected/diff triple. -## The constants rule - -**Everything in `lib/src/constants/` is a verbatim transcription of the React -source's `src/styles.ts`. Never tweak a value there to make something look -better.** Visual parity with the React library is the whole point of the port; -these tables are the parity. If a number looks wrong, check the source first: - -```bash -git clone https://github.com/Jakubantalik/border-beam /tmp/border-beam-react -``` - -That covers `palettes.dart`, `theme_presets.dart`, `pulse_tables.dart`, -`pulse_params.dart`, and `line_keyframes.dart`. A change to any of them needs -a source citation in the PR description. - -Flutter-only additions are fine, but they live in **clearly headed separate -files** that say up front they are not transcriptions — `extra_palettes.dart` -is the model. Do not mix an original value into a transcription table. - -## The saveLayer budget - -`saveLayer` is the expensive primitive in this package and the best single -proxy for the cost of a frame. One frame (`paintBehind` + `paintAbove`) is -budgeted per variant: - -| variant | layers | what they are | -| --- | --- | --- | -| `rotate` | 4 | inner + inner mask + stroke + blurred bloom | -| `small` | 3 | inner + stroke + blurred bloom (single-mask inner) | -| `line` | 4 | inner + inner mask + stroke + blurred bloom | -| `pulseInside` | 4 | inner + inner mask + stroke + blurred bloom | -| `pulseOutside` | 3 | behind: core glow + bloom halo; above: stroke | - -`test/painting/save_layer_budget_test.dart` measures every variant × brightness -× palette × time sample through a counting canvas and asserts the count -**exactly**, plus save/restore balance. A regression *and* an improvement both -fail until the table is updated in the test and in `CLAUDE.md`. - -So: a new option must fold into a layer that already exists. If it genuinely -cannot, add a budget row and justify it in the PR — say which layer, why it is -unavoidable, and what you tried instead. Two things are never a justification: - -- A `ColorFilter`. Hue, brightness, and saturation are folded into gradient - colors on the CPU (`BeamColorMatrix.transform`). A filter may ride on a - layer that exists anyway; it never earns one. -- Convenience. Blur is the only effect allowed to justify a layer of its own. +## The rendering rules + +### One draw, no offscreen work + +A beam frame is **one** `drawRect` or `drawDRRect` with the beam shader, and +nothing else: no `saveLayer`, no clip, no `ImageFilter`, no `MaskFilter`. +`test/render/frame_budget_test.dart` records every effect across themes, +palettes, shape families, options, and instants through a counting canvas and +asserts exactly that. A new look is new shader maths or new data in +`BeamFrameData` — never a layer, a blur, or a second draw. If something truly +cannot be expressed that way, open an issue before writing it. + +### The uniform contract + +The `uniform` block in `shaders/beam.frag` and the offsets and slot counts in +`lib/src/render/beam_frame.dart` (`BeamFrameData`, `beamUniformFloats`) agree +float for float. Change both in the same commit. Uniforms are `vec4`s and +`vec4` arrays only, so the layout is the same on every backend, and arrays are +indexed only by constants and loop indices (SkSL's strict ES2), which is why +each layer has its own blob array. `test/render/uniform_layout_test.dart` +parses the shader and checks the types, the array lengths, the loop bounds, +and the total — but it cannot see the order, so check that by hand: a uniform +reordered on one side only shifts every value after it. + +### The CPU mirrors + +Two pieces of shader maths also run in Dart, and must match exactly: + +- **`BeamOutline`** (`lib/src/render/beam_outline.dart`) mirrors the shader's + `outline()` — the corner model, the signed distance, the nearest-piece + choice, and the perimeter coordinate `u`. Emitters lay blobs along the + outline with it, segments resolve against it, and `follow` maps the pointer + with it. +- **Conic tables** — `BeamFrameData.tableAt` reads a table exactly as the + shader's `TABLE_LOOKUP` does. + +### Slots and light + +- **Fixed slots:** 14 blobs in layer 0, 10 in layers 1 and 2, and 16 stops per + conic table; `addBlob` drops anything past a layer's slots. A palette + carries at most 8 colour stops. +- Glows that reach **inside** the shape are planar blobs, or path-space blobs + kept within the edge fade. Never shade an inward glow from `u`: inside the + shape it jumps across the medial axis and shows a seam. +- Emitters are **pure** (a function of the config, the phases, the outline, + and the palette's blob tables) and **allocation-light per frame**: they + write into the renderer's reused `BeamFrameData`; table transforms use + scratch lists, oscillator banks are cached per tuning, and derived tables + are memoized per palette. ## Where things go -**Adding a variant** — `lib/src/models/beam_variant.dart` (the enum value, its -doc comment, and its default cycle duration), a strategy in -`lib/src/painting/strategies/` implementing `BeamVariantStrategy`, the -dispatch map at the top of `lib/src/painting/beam_painter.dart`, a named -constructor on `BorderBeam` in `lib/src/border_beam.dart`, any per-variant -defaults in `lib/src/models/beam_config.dart` — plus a budget row, a golden -scene, and a paint-smoke case. +**Adding an effect** — a `final class` extending `BeamEffect` in +`lib/src/effects/beam_effect.dart` (with a `const factory` on `BeamEffect`, a +doc comment, `travels`, `defaultCycle`, and any non-default `defaultCycleGap` / +`defaultHueMode` / `defaultHuePeriod`, plus `==` / `hashCode`), an entry in +`BeamEffect.values`, the export in `lib/flutter_border_beam.dart`, and an +emitter in `lib/src/effects/effect_emitters.dart`. The `switch` statements over +`BeamEffect` (the emitter dispatch, `BorderBeam.follow`) are exhaustive, so the +analyzer lists every place that needs a case; `BeamConfig.beamCount` falls +back to one beam for anything but `rotate`. Then a golden scene, and the +effect shows up in the render tests automatically through `render_utils.dart`'s +`effectsByName`. **Adding an option** — declare it on the value object it belongs to (`beam_style.dart`, `beam_shape.dart`, `beam_timing.dart`, -`beam_playback.dart`), extending `copyWith`/`merge`/`==`/`hashCode`. A null -field means *inherit*, so the default must be null. Small option types live in -`beam_options.dart`. Resolve it in `BeamConfig.resolve` and consume it in the -strategy. Value equality is load-bearing: `BeamPainter.shouldRepaint` compares -configs, so an option that does not participate in `==` will silently fail to -repaint. - -**Adding a palette** — source colors in -`lib/src/constants/extra_palettes.dart`, exposed as a `static const BeamColors` -on `BeamColors` in `lib/src/models/beam_colors.dart`, plus a palette golden and -a playground entry (`example/lib/src/playground/`). +`beam_playback.dart`), extending `copyWith` / `merge` / `==` / `hashCode`. A +null field means *inherit*, so the default must be null. Small option types +live in `beam_options.dart`. Resolve it in `BeamConfig.resolve` and consume it +in the emitter or the renderer. Value equality is load-bearing: +`BeamPainter.shouldRepaint` compares configs, so an option that does not take +part in `==` silently fails to repaint. An option parameter that belongs to one +effect goes on that effect's class instead (`BeamEffect.rotate(length:)`). + +**Adding a palette** — a `const BeamPalette` in +`lib/src/models/beam_presets.dart` (at most 8 stops, ascending, in `[0, 1)`), +exposed as a `static const BeamColors` on `BeamColors` and added to +`BeamColors.presets`, plus a palette golden (the example's swatch row picks +it up from `BeamColors.presets`). Without blob tables of its own, a preset +is drawn by sampling its stops over `colorful`'s tables. Presets are design +data: edit freely, and check the result on both dark and light surfaces. Anything public also needs a doc comment, a `CHANGELOG.md` entry, and a README mention if it changes what a user would reach for first. @@ -150,18 +162,23 @@ Tests are grouped by what they protect. Put a new test with its family: | directory | covers | | --- | --- | -| `test/models/` | value objects, `BeamConfig.resolve`, palettes, equality | -| `test/widget/` | `BorderBeam` behavior — lifecycle, theming, shorthands, speed, sync | +| `test/models/` | value objects, `BeamConfig.resolve`, palettes, effects, segments, equality | +| `test/animation/` | the clock, the spring, phase sampling, travel | +| `test/render/` | the frame budget, the uniform layout, the outline mirror, emission sanity, boundaries, paint smoke, where light lands | +| `test/widget/` | `BorderBeam` behaviour — lifecycle, theming, shorthands, speed, sync, progress, follow | | `test/widgets/` | the surface widgets (`BeamDecoration`, `BeamFocusRing`, `BeamHover`, `BeamPress`) | -| `test/painting/` | paint smoke, boundary geometry, ring geometry, color matrix, the saveLayer budget | -| `test/animation/` | the clock, oscillators, phase sampling, spring curves | | `test/golden/*_golden_test.dart` | pixel scenes (macOS only, `@Tags(['golden'])`) | -Two conventions worth knowing: +Conventions worth knowing: +- Anything that reads pixels needs the shader loaded: + `setUpAll(BorderBeam.precache)`. +- For new rendering behaviour, prefer comparing regions of a real frame + against each other (see `test/render/paint_structure_test.dart`) over + pinning pixel values — those survive a retune; goldens are for the look. - The first tick after `Ticker.start()` reports elapsed 0 — pump once before pumping durations. -- A test that documents behavior the code does not have yet is marked +- A test that documents behaviour the code does not have yet is marked `skip: 'defect: '`, not rewritten to match the bug. (`testWidgets` only takes a bool, so the reason goes in a comment beside it.) @@ -170,10 +187,11 @@ Every bug fix ships with a regression test. ## Writing prose Docs and code comments **describe how the code works now**. No change-history -prose — no "no longer", "was removed", "previously", "this used to". Git -carries the history; a comment that narrates a change goes stale the moment -someone reads it out of context. Describe the current behavior and why it is -that way. +prose — no "no longer", "was removed", "previously", "this used to". Git and +`CHANGELOG.md` carry the history; a comment that narrates a change goes stale +the moment someone reads it out of context. Describe the current behaviour and +why it is that way. Don't quote tuning values (glow reaches, layer weights) in +docs — they live in `lib/src/look/` and the emitters, and they change. ## Commits and PRs @@ -184,12 +202,13 @@ Conventional Commits, for both commit subjects and PR titles: ``` Lowercase type (`feat`, `fix`, `refactor`, `docs`, `chore`, `ci`, `test`, -`perf`), an optional short scope (`painting`, `motion`, `colors`, `widgets`, -`api`), imperative summary under 72 characters. For example: +`perf`, `style`), an optional short scope (`render`, `shader`, `effects`, +`motion`, `colors`, `widgets`, `api`), imperative summary under 72 +characters. For example: ``` -feat(painting): add a comet tail to the rotate strategy -fix(motion): keep the line beam inside its edge-fade plateau +feat(effects): add a comet tail to the rotate effect +fix(shader): keep the dash ends soft on the bloom ``` Before opening a PR: @@ -198,7 +217,8 @@ Before opening a PR: - [ ] `flutter analyze --fatal-infos` — zero issues (package **and** `example/`) - [ ] `flutter test` — green (say if you could not run goldens) - [ ] Goldens: none regenerated, or the PR names which and why -- [ ] saveLayer budget: unchanged, or the new rows are justified +- [ ] Frame budget: still one draw, no layers, clips, or filters +- [ ] Shader uniforms and `beam_frame.dart`'s offsets and slot counts changed together (if touched) - [ ] Public API is documented, and the README covers anything user-facing - [ ] `CHANGELOG.md` has an entry under the unreleased version diff --git a/LICENSE b/LICENSE index 200c6e9..5f29ba0 100644 --- a/LICENSE +++ b/LICENSE @@ -24,7 +24,8 @@ SOFTWARE. Third-party notice -This package is a Flutter port of the "border-beam" React library: +This package was originally a Flutter port of, and remains inspired by, the +"border-beam" React library: Copyright (c) 2026 Jakub Antalik (https://github.com/Jakubantalik/border-beam), released under the MIT License. All visual designs, color palettes, gradient geometry, and animation timings are derived from that work. diff --git a/README.md b/README.md index 6cf346f..68a1276 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@

flutter_border_beam

- A traveling or breathing glow around any widget — cards, buttons, inputs, search bars. + Animated light around any widget's border — cards, buttons, inputs, search bars.

pub package pub points - Flutter 3.35+ + Flutter 3.47+ Dart 3.9+ CI codecov @@ -16,59 +16,60 @@

- The five beam variants animating in the example gallery + Border beams animating in the demo reel
## Overview -A faithful Flutter port of the [border-beam](https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam) React library by [Jakub Antalik](https://x.com/jakubantalik) ([live demo](https://beam.jakubantalik.com)). Every palette, gradient, mask, blur, and timing constant is transcribed from the original source, so the effects are pixel-matched — with Flutter-native additions on top. +`flutter_border_beam` draws light that travels or breathes around a widget's border. Wrap a widget in `BorderBeam`, pick an effect, and the beam paints over it — matched to its corner radius, adapted to a dark or light surface, and animated by one ticker. -**Five variants**, each a named constructor with tuned defaults: +The whole beam is **one fragment shader drawn in one pass**: no `saveLayer`, no blur filters, no clips, and no offscreen render targets. It runs at the display's refresh rate, 120Hz included, and is cheap enough to leave on a card while the user scrolls. -- **`rotate`** — a beam travels the full border. Cards, surfaces, panels. -- **`small`** — the compact cut, on a 32px radius. Icon buttons, chips. -- **`line`** — a streak rides one edge, with a bloom and spikes. Inputs, search bars. -- **`pulseInside`** — a contained glow breathing inward from the border. -- **`pulseOutside`** — a halo blooming outward, behind the child. +**Three effects**, chosen with `effect:`: + +| Effect | Family | Default cycle | Use it for | +| --- | --- | --- | --- | +| `BeamEffect.rotate()` | travelling | 2.4s | A beam with a soft tail laps the border. Cards, panels, surfaces. The default. | +| `BeamEffect.line()` | travelling | 3.1s | A streak rides one edge with light spiking up from it. Inputs, search bars, composers. | +| `BeamEffect.pulse()` | ambient | 2.3s | Colour breathes inward from the whole border, strongest at the corners. A contained "thinking" state. |
- Rotate beam
- Rotate — a beam travels around the border + Rotate effect on a card
+ rotate — a beam laps the border
- Pulse outside halo
- Pulse outside — a breathing halo blooms behind the child + Pulse effect on a card
+ pulse — colour breathes in from the border
- Line beam
- Line — the beam rides the bottom edge + Line effect on an input
+ line — a streak rides the bottom edge
- Squircle beam
- Superellipse — Apple-style squircle borders, ocean palette + Superellipse corners in the ocean palette
+ superellipse corners, ocean palette
-And on top of the effects themselves: +Around the effects: -- **Eleven palettes** — the four from the original plus seven Flutter-only ones, with `custom`, `fromSeed` harmonies, `fromScheme`, `lerp`, `scaleAlpha`, and per-blob `spec`. -- **Value-object API** — `BeamStyle`, `BeamShape`, `BeamTiming`, `BeamPlayback`; every field nullable, so anything you leave out is inherited from a `BorderBeamTheme` or the variant default. -- **Shapes** — per-corner direction-aware radii, stadium, Apple-style superellipse, ring offset, arbitrary path contours, partial segments, and corner-wrapping lines. -- **Motion** — cycle gap, forward / reverse / bounce, phase offset, several beams on one contour, driven `progress`, pointer `follow`. -- **Synchronized groups** — `BeamSync` puts a whole subtree on one ticker and one timeline, so a row of cards reads as one system. -- **Surfaces & interactions** — `BorderBeam.overlay`, a `BeamDecoration` for existing `Container`s, and `BeamFocusRing` / `BeamHover` / `BeamPress`. -- **Accessible** — four documented reduced-motion behaviors; beams add no semantics and never intercept a pointer. -- **Fast** — one ticker per beam, a ~30fps cap on the pulse variants, `RepaintBoundary` isolation, CPU-folded color matrices, an offscreen pause, and a `saveLayer` budget pinned by a test. +- **19 palettes** plus your own: colour stops anywhere on the ring, `fromSeed` harmonies, `fromScheme`, `lerp`, and `scaleAlpha`. +- **Value-object API** — `BeamStyle`, `BeamShape`, `BeamTiming`, `BeamPlayback`. Every field is nullable, so anything you leave out comes from a `BorderBeamTheme` or the effect's default. +- **Shapes** — per-corner, direction-aware radii, stadiums, superellipse ("squircle") corners, ring offset, partial segments, and dashes. +- **Motion** — rest between sweeps, forward / reverse / bounce, phase offset, several beams at once, a driven `progress`, and pointer `follow`. +- **Synchronized groups** — `BeamSync` puts a subtree on one ticker and one timeline. +- **Surfaces and interactions** — `BorderBeam.overlay`, `BeamDecoration` for an existing `Container`, and `BeamFocusRing` / `BeamHover` / `BeamPress`. +- **Accessible** — four reduced-motion behaviours; beams add no semantics and never intercept a pointer. -### Live playground +### Live demo -**** — every variant, palette, and tuning hook on live controls, with the matching Dart snippet and a shareable link. Built from [`example/`](example). +**** — the example app built for web: each effect on the kind of widget it is made for, recoloured with any preset, in either theme. Built from [`example/`](example). ## Installation @@ -83,11 +84,13 @@ import 'package:flutter_border_beam/flutter_border_beam.dart'; | Requirement | Version | | --- | --- | -| Flutter | ≥ 3.35 (stable `RoundedSuperellipseBorder` / `RSuperellipse`) | -| Dart | ≥ 3.9 | -| Dependencies | none beyond the Flutter SDK | +| Flutter | ≥ 3.47 | +| Dart | ≥ 3.13 | +| Dependencies | [`material_ui`](https://pub.dev/packages/material_ui) | + +The shader is declared in the package's own `pubspec.yaml`, so Flutter compiles and bundles it into your app. There is nothing to add to your app's pubspec. -> Tracks upstream **border-beam 1.4.0**. Where this package deliberately differs from the original, and why, is spelled out in [Parity with the original](#parity-with-the-original). +The package reads Material through [`material_ui`](https://pub.dev/packages/material_ui), not the `package:flutter/material.dart` that Flutter 3.47 deprecated. The two libraries' `Theme` and `ColorScheme` are separate types, so an app still on `package:flutter/material.dart` should migrate (`dart fix --apply --code=migrate_design_widgets`) or set `BeamStyle.theme` explicitly: until then, `BeamTheme.auto` finds no `material_ui` theme and tunes for a light surface, and `BeamColors.fromScheme` takes `material_ui`'s `ColorScheme`. ## Usage @@ -95,7 +98,7 @@ import 'package:flutter_border_beam/flutter_border_beam.dart'; ### Quick start ```dart -BorderBeam.rotate( +BorderBeam( borderRadius: 16, colors: BeamColors.ocean, child: Card( @@ -108,11 +111,13 @@ BorderBeam.rotate( ) ``` -That is the whole API for the common case. Everything else is a field on one of four value objects — `style`, `shape`, `timing`, `playback` — and every one of their fields is nullable, meaning *inherit*. +That is a rotating beam — `BeamEffect.rotate()` is the default effect. Pass the same radius your child uses; the beam does not read it from the child. + +Everything else is a field on one of four value objects — `style`, `shape`, `timing`, `playback` — and every field on them is nullable, meaning *inherit*: ```dart BorderBeam( - variant: BeamVariant.line, + effect: const BeamEffect.line(), style: const BeamStyle(colors: BeamColors.sunset, strength: 0.8), shape: const BeamShape.all(24, superellipse: true), timing: const BeamTiming(cycleGap: Duration(seconds: 1)), @@ -121,47 +126,67 @@ BorderBeam( ) ``` -### Variants +Optionally load the shader before the first beam appears: + +```dart +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await BorderBeam.precache(); + runApp(const App()); +} +``` + +Without it, a beam loads the shader on demand and paints nothing for the few milliseconds that takes, which its fade-in hides. + +### Effects ```dart -BorderBeam.rotate(child: card); // full border beam — cards, surfaces -BorderBeam.small(child: iconButton); // compact — buttons, chips (32px radius) -BorderBeam.line(child: searchBar); // travels one edge — inputs -BorderBeam.pulseInside(child: card); // contained breathing glow -BorderBeam.pulseOutside(child: card); // halo blooming outward behind the child - -// Picked at runtime — same parameters, no switch: -BorderBeam(variant: variant, child: card); +BorderBeam(effect: const BeamEffect.rotate(), child: card); +BorderBeam(effect: const BeamEffect.rotate(length: 1.5, count: 2, comet: true), child: card); +BorderBeam(effect: const BeamEffect.line(edge: BeamEdge.top), child: searchBar); +BorderBeam(effect: const BeamEffect.pulse(), child: card); ``` -| Variant | Upstream name | Family | Default cycle | Default radius | Default hue track | Paints | -| --- | --- | --- | --- | --- | --- | --- | -| `rotate` | `md` | traveling | 1.96s | 16 | ping-pong, 12s | over the child | -| `small` | `sm` | traveling | 1.96s | 32 | ping-pong, 12s | over the child | -| `line` | `line` | traveling | 3.1s | 16 | ping-pong, 12s (bloom 8s) | over the child | -| `pulseInside` | `pulse-inner` | pulse | 2.3s | 16 | continuous, 16s | over the child | -| `pulseOutside` | `pulse-outside` | pulse | 2.3s | 16 | continuous, 14s | behind and outside the child | +| Effect | Parameters | Default hue drift | +| --- | --- | --- | +| `rotate` | `length` (tail, 0.25–2, default 1), `count` (1–4 beams, default 1), `comet` (outer trailing glow, default false) | ping-pong, 12s | +| `line` | `edge` (default `BeamEdge.bottom`) | ping-pong, 8s | +| `pulse` | — | continuous, 16s | + +The two families take different inputs. **Travelling** effects (`rotate`, `line`) move a position along the border once per cycle; they respond to `direction`, `cycleGap`, `progress`, and `follow`. The **ambient** `pulse` lights the whole border at once and ignores those inputs. `phaseOffset` applies to both families. -The two families differ in more than looks: the traveling variants sweep a window around the contour and respond to `direction`, `cycleGap`, `beamCount`, `progress`, and `follow`; the pulse variants breathe from a bank of oscillators and ignore all of those. +Every effect is drawn by the same shader in the same single draw, so they cost the same order of GPU time. Pick for the look. -> ⚠️ **pulse-outside contract** (the same one the original states): the child must be **opaque**, so only the outward spill shows; it should carry its **own 1px border** for a defined idle edge; and it needs **clip-free room** around it — padding in the parent, no tight `ClipRRect`. A halo with nowhere to bloom is a halo you cannot see. +`BeamEffect.values` lists all three with their defaults, and each effect is a value type, so `BorderBeam(effect: someEffect)` picked at runtime needs no switch. -[Full documentation →](doc/variants.md) +[Full documentation →](doc/effects.md) ### Palettes ```dart -// Presets -BorderBeam.rotate(colors: BeamColors.ocean, child: card); +// A preset +BorderBeam(colors: BeamColors.aurora, child: card); -// Your own colors, distributed over the preset blob geometry -BorderBeam.rotate( - colors: const BeamColors.custom([Colors.pink, Colors.cyan, Colors.amber]), +// Your own colours, evenly spaced clockwise from top-centre +BorderBeam( + colors: const BeamColors([Colors.pink, Colors.cyan, Colors.amber]), + child: card, +); + +// …or placed at chosen positions around the ring +BorderBeam( + colors: const BeamColors( + [Colors.indigo, Colors.pink, Colors.orange], + stops: [0.0, 0.4, 0.7], + ), child: card, ); -// One brand color, spread into a harmony -BorderBeam.rotate( +// One colour all the way round +BorderBeam(colors: const BeamColors.solid(Color(0xFF18A8F0)), child: card); + +// One brand colour, spread into a harmony +BorderBeam( colors: const BeamColors.fromSeed( Color(0xFF18A8F0), harmony: BeamSeedHarmony.triadic, @@ -170,34 +195,44 @@ BorderBeam.rotate( ); // The app's Material scheme -BorderBeam.rotate( +BorderBeam( colors: BeamColors.fromScheme(Theme.of(context).colorScheme), child: card, ); // Blend two palettes, and dim one -BorderBeam.rotate( +BorderBeam( colors: const BeamColors.lerp(BeamColors.ocean, BeamColors.sunset, 0.35), child: card, ); -BorderBeam.rotate(colors: BeamColors.ember.scaleAlpha(0.6), child: card); +BorderBeam(colors: BeamColors.ember.scaleAlpha(0.6), child: card); ``` -| Preset | Origin | Colors | Notes | -| --- | --- | --- | --- | -| `colorful` | upstream | rainbow spectrum | the default | -| `mono` | upstream | grayscale | pins the hue and halves layer opacity | -| `ocean` | upstream | blue, purple | | -| `sunset` | upstream | orange, yellow, red | | -| `aurora` | Flutter-only | teal, violet, green, glacier blue | | -| `neon` | Flutter-only | magenta, cyan, lime | the loudest | -| `candy` | Flutter-only | pink, lavender, peach | pastel | -| `ember` | Flutter-only | deep red, orange, gold | | -| `ice` | Flutter-only | pale blue, white, cyan | | -| `gold` | Flutter-only | amber, gold, bronze | pins the hue, keeps full opacity | -| `holographic` | Flutter-only | desaturated pastels | built to be paired with a fast continuous hue drift | - -Every `BeamColors` is a value type and resolution is memoized by value, so rebuilding `BeamColors.custom([...])` inline in `build` does not re-resolve the gradient tables. +A palette is a ring of 1–8 colour stops around the border: position 0 is top-centre and positions increase clockwise. Neighbouring stops blend, and the last blends back into the first. `rotate` and `pulse` reveal the colours wherever their light falls; `line` spreads the palette across its streak. + +| Preset | Colours | Notes | +| --- | --- | --- | +| `colorful` | orange, magenta, violet, blue, green, hot pink | the default | +| `mono` | whites and greys | hue never drifts | +| `ocean` | blues and violets | | +| `sunset` | reds, oranges, amber | | +| `aurora` | teal, violet, green | | +| `neon` | magenta, lime, cyan | the loudest | +| `candy` | pastel pink, lavender, peach | | +| `ember` | deep red, orange, gold | | +| `ice` | pale blue, white, cyan | | +| `gold` | amber, gold, bronze | hue never drifts | +| `holographic` | desaturated pastels | pair with a fast continuous hue drift | +| `lagoon` | teal, aqua, mint | | +| `dusk` | indigo, violet, rose | | +| `forest` | emerald, lime, teal | | +| `rose` | pink, coral, mauve | | +| `cosmic` | deep violet, electric blue, magenta | | +| `citrus` | lime, yellow, tangerine | | +| `sky` | cerulean, periwinkle, white-blue | | +| `lavender` | lilac, lavender, soft pink | | + +`BeamColors.presets` maps every preset's name to its value, in this order. Every `BeamColors` is a value type and resolution is memoized by value in a bounded LRU, so building `BeamColors([...])` inline in `build` costs nothing after the first frame; an app that cycles through more distinct palettes than the memo holds rebuilds an evicted one when it comes back. [Full documentation →](doc/palettes.md) @@ -205,13 +240,10 @@ Every `BeamColors` is a value type and resolution is memoized by value, so rebui ```dart // Uniform radius, const -BorderBeam.rotate( - shape: const BeamShape.all(24, superellipse: true), - child: card, -); +BorderBeam(shape: const BeamShape.all(24, superellipse: true), child: card); // Per-corner, direction-aware -BorderBeam.rotate( +BorderBeam( shape: const BeamShape( radius: BorderRadiusDirectional.only(topStart: Radius.circular(28)), ), @@ -219,35 +251,27 @@ BorderBeam.rotate( ); // A pill (a circle on a square box) that tracks the box as it resizes -BorderBeam.small(shape: const BeamShape.stadium(), child: chip); - -// The ring 8px outside the child, with the beam on the top edge -BorderBeam.line( - shape: const BeamShape.all(16, ringOffset: 8, edge: BeamEdge.top), - child: card, -); +BorderBeam(shape: const BeamShape.stadium(), child: chip); -// An arbitrary contour -BorderBeam.rotate( - shape: BeamShape( - contour: BeamPathContour((rect) => Path()..addOval(rect), key: 'oval'), - ), +// The outline 8px outside the child, with a 2px stroke +BorderBeam( + shape: const BeamShape.all(24, ringOffset: 8, borderWidth: 2), child: card, ); ``` -Three constructors cover the common cases: `BeamShape.all(r)` is the **const** path to a uniform radius (it stores the number rather than building a `BorderRadius`), `BeamShape.circular(r)` is the same shape when you already think in `BorderRadius` terms (**not** const), and `BeamShape.stadium()` rounds each corner to half the shortest side. `radius` resolves against the ambient `Directionality` and clamps per corner the way `RRect.scaleRadii` does. +`BeamShape.all(r)` is the **const** path to a uniform radius, `BeamShape.circular(r)` builds the same shape from a `BorderRadius` (not const), and `BeamShape.stadium()` rounds each corner to half the shortest side. `radius` resolves against the ambient `Directionality` and is clamped per corner the way `RRect.scaleRadii` does. `superellipse: true` follows Flutter's `RoundedSuperellipseBorder`, so the stroke sits on the edge of a squircle-clipped child. -There is **no auto-detection of the child's radius** — pass the same value your child uses. +The default radius is 16. There is **no auto-detection of the child's radius** — pass the value your child uses. [Full documentation →](doc/shape.md) -### Segments and partial contours +### Segments and dashes -`BeamShape.segment` masks the unchanged full-ring animation to a clockwise portion of the contour. Constants and blob positions stay in full-ring space, and the mask adds no compositing layer. +`BeamShape.segment` limits the light to a clockwise portion of the border. The animation runs unchanged on the whole border; the segment shows the part inside it and fades its ends over `feather` logical pixels (32 by default). ```dart -BorderBeam.rotate( +BorderBeam( shape: const BeamShape( radius: BorderRadius.all(Radius.circular(24)), segment: BeamSegment.bottomHalf, @@ -256,91 +280,80 @@ BorderBeam.rotate( ); ``` -Positions are arc-length fractions from top-center, clockwise: `0` is top-center, `0.25` approximately right-center on a square, `0.5` bottom-center, `0.75` approximately left-center. Build endpoints with `BeamAnchor.fraction(t)`, `BeamAnchor.edge(edge, t)`, or `BeamAnchor.corner(corner, t)`, or use `topCenter` / `rightCenter` / `bottomCenter` / `leftCenter`. `BeamSegment(start: …, end: …, feather: 32)` runs clockwise from start to end, wrapping through top-center when necessary; `feather` is the fade distance in logical pixels at each end, and `0` makes a hard cut. +Positions are arc-length fractions from top-centre, clockwise. Build endpoints with `BeamAnchor.fraction(t)`, `BeamAnchor.edge(edge, t)`, or `BeamAnchor.corner(corner, t)`, or use `BeamAnchor.topCenter` / `rightCenter` / `bottomCenter` / `leftCenter`. `BeamSegment(start: …, end: …, feather: 32)` runs clockwise from `start` to `end`, wrapping through top-centre when needed; `feather: 0` makes a hard cut. | Preset | Coverage | | --- | --- | -| `bottomHalf` / `topHalf` | The lower / upper half between the side centers | -| `leftHalf` / `rightHalf` | The left / right half between the top and bottom centers | -| `bottomEdge` / `topEdge` | The named straight run plus both adjacent corner arcs | -| `leftEdge` / `rightEdge` | The named straight run plus both adjacent corner arcs | - -Each family reads a segment differently: **`rotate` / `small`** keep the conic window's full sweep, appearing at `start` and traveling to `end`; **`line`** rides the segment, rounding its corners and fading at both ends (`shape.edge` is ignored while a segment is set); **pulse** hides blobs outside the segment and fades those near either end. +| `bottomHalf` / `topHalf` | The lower / upper half between the side centres | +| `leftHalf` / `rightHalf` | The left / right half between the top and bottom centres | +| `bottomEdge` / `topEdge` / `leftEdge` / `rightEdge` | The named straight run plus both adjacent corner curves | -For two counter-sweeping arcs, stack a second beam with `timing: const BeamTiming(direction: BeamDirection.reverse)`. For a full-contour line, `wrapCorners: true` bends the streak around the two corner arcs adjacent to `edge`. +`rotate` appears at `start` and travels to `end`; `line` rides the segment instead of its `edge`, around corners included; the ambient effects light only the part inside it. -### Style +`BeamShape.dashes` breaks the border into that many evenly spaced dashes (2 or more; 0 and 1 keep it solid): ```dart -BorderBeam.rotate( - style: const BeamStyle( - colors: BeamColors.aurora, - strength: 0.8, - comet: true, - sparkle: 0.4, - tailLength: 1.4, - ), - child: card, +BorderBeam( + shape: const BeamShape.all(16, dashes: 12), + child: badge, ); ``` -Twenty-six fields, all listed in the [`BeamStyle` reference](#beamstyle). Four are worth a sentence each. - -**`themeConfig`** replaces the whole variant × brightness preset — layer opacities, inset shadow, and the default brightness/saturation. Start from a preset rather than inventing one: +### Style ```dart -BorderBeam.rotate( - style: BeamStyle( - themeConfig: BeamThemeConfig.presetFor( - BeamVariant.rotate, - Brightness.dark, - ).copyWith(bloomOpacity: 0.4), +BorderBeam( + style: const BeamStyle( + colors: BeamColors.aurora, + theme: BeamTheme.dark, + strength: 0.8, + glow: 1.3, + hueMode: BeamHueMode.continuous, + hueBase: 40, ), child: card, ); ``` -**`innerSizeScale`** multiplies the size of `pulseInside`'s inner blobs. Below 1 the wash pulls tighter to the border, leaving more of the child clear; above 1 it floods further in. The perimeter ring and the bloom keep their own geometry, so the border itself does not move. - -**`renderScale`** is the fraction of the box the beam is *painted* at before being magnified back to fill it (0.25–1). The palettes are authored against a 350×140 card, so on a screen-width box the blobs read as small and sparse; painting at 0.5 and magnifying restores the proportions the palette was drawn for — glow, blurs, and corner radii all grow together. It costs one canvas transform and no extra layer, but it *is* a magnification, so the ring's own edge softens as the factor drops. - -```dart -BorderBeam.rotate( - style: const BeamStyle(renderScale: 0.35), - child: fullScreenSurface, -); -``` - -**`BeamStyle.pulseOutsideStock`** is a ready-made style carrying the upstream library's **stock** pulse-outside look — a tighter, dimmer halo sitting closer to the child. `BorderBeam.pulseOutside` paints the tuned demo recipe by default, because that is the look the library is known for; the stock style rolls every part of that tuning back. Layer your own fields over it with `copyWith` — anything you set wins. +| Field | Meaning | +| --- | --- | +| `colors` | The palette. | +| `theme` | `dark`, `light`, or `auto` (follows `material_ui`'s `Theme.of(context).brightness`). Each effect is tuned separately for dark and light surfaces. | +| `strength` | Overall opacity, 0–1. | +| `glow` | Scales every glow around the stroke: how far it reaches and, below 1, how bright it is; 0 leaves only the stroke, which `glow` never changes. | +| `hueMode` | How the colours drift: `pingPong` (swing ±`hueShift`), `continuous` (a full turn per `huePeriod`), or `none`. Defaults per effect. | +| `hueShift` | Degrees either side for `pingPong`. | +| `hueBase` | A fixed hue rotation, in degrees, on top of any drift. | -```dart -BorderBeam.pulseOutside(style: BeamStyle.pulseOutsideStock, child: card); -``` +`mono` and `gold` never drift, whatever `hueMode` says. ### Motion ```dart -BorderBeam.rotate( +BorderBeam( + effect: const BeamEffect.rotate(count: 3), timing: const BeamTiming( - cycle: Duration(seconds: 3), // one sweep - cycleGap: Duration(seconds: 1), // rest between sweeps + cycle: Duration(seconds: 3), // one lap + cycleGap: Duration(seconds: 1), // rest between laps direction: BeamDirection.bounce, // alternate each cycle - beamCount: 3, // three beams, equally spaced + phaseOffset: 0.25, // start a quarter of the way in speed: 1.5, // playback rate + huePeriod: Duration(seconds: 8), // colour drift period ), child: card, ); ``` -Changing `cycle` while the beam runs **retimes it in place** — every track keeps its phase, so the beam speeds up or slows down without a jump. `cycleGap` parks the beam at the end of its travel between sweeps, fading out and back in over `min(0.25s, gap / 2)` at each end; the hue, breathe, and spike tracks are textures rather than the sweep, so they keep running through the gap. Every field is in the [`BeamTiming` reference](#beamtiming). +Changing `cycle` while the beam runs **retimes it in place** — the beam keeps its position and speeds up or slows down without a jump. `cycleGap` parks a travelling effect at the end of its travel after each sweep and fades it out and back in over `min(0.25s, gap / 2)` at each end; the hue drift keeps running through the gap. [Full documentation →](doc/motion.md) ### Playback ```dart -BorderBeam.pulseInside( - active: isLoading, // fades in 0.6s / out 0.5s +BorderBeam( + effect: const BeamEffect.pulse(), + active: isLoading, // fades in ~0.5s / out ~0.6s playback: const BeamPlayback( startAfter: Duration(milliseconds: 500), duration: Duration(seconds: 10), @@ -353,20 +366,14 @@ BorderBeam.pulseInside( ); ``` -`reducedMotion` has four behaviors, all of them applying to all five variants: - -| `BeamReducedMotion` | Behavior | +| `BeamReducedMotion` | Behaviour | | --- | --- | -| `staticFrame` | Paints a single static frame and stops ticking. **The default.** | +| `staticFrame` | Paints one static frame and stops ticking. **The default.** | | `hide` | Paints nothing; the child is left bare and no ticker runs. | | `slow` | Keeps animating at a quarter of the configured speed. | -| `animate` | Ignores the request and animates normally. | - -`debugFrozenAt` pins the beam to one instant and never starts its clock — for screenshots and tests rather than product code. Every animated value is a pure function of elapsed time, so a fixed time is a fixed frame: two runs a week apart paint the same pixels. - -`fadeCurve` swaps the fade envelope. The package eases fades with a spring, which carries a little momentum and overshoots slightly; `BeamPlayback.cssEase` is the web's `cubic-bezier(0.25, 0.1, 0.25, 1)`, for a fade that matches the original exactly. +| `animate` | Ignores the request. | -The full field list is in the [`BeamPlayback` reference](#beamplayback). +`pauseWhenOffscreen` (default on) stops a beam's clock while it is scrolled more than 256px out of its nearest `Scrollable`, and resumes it where it left off. `fadeCurve` replaces the critically damped springs that ease the fades. `debugFrozenAt` pins the beam to one instant of its timeline — for screenshots and golden tests, not product code. ## Advanced @@ -376,6 +383,7 @@ The full field list is in the [`BeamPlayback` reference](#beamplayback). ```dart BorderBeamTheme( data: const BorderBeamThemeData( + effect: BeamEffect.pulse(), style: BeamStyle(colors: BeamColors.ocean, strength: 0.8), shape: BeamShape.all(20, superellipse: true), timing: BeamTiming(cycle: Duration(seconds: 3)), @@ -385,71 +393,67 @@ BorderBeamTheme( ); ``` -`BorderBeamThemeData` has one slot per value object, and each slot's fields are nullable, so a theme fills in only what it sets. `BorderBeamTheme.of` walks **every** enclosing scope, depends on each, and merges them outside-in — an inner theme overrides just the fields it names, and a change to an outer one rebuilds the beam exactly as an inner one does. +`BorderBeamThemeData` has a slot for the effect and one per value object; each object's fields are nullable, so a theme fills in only what it sets. `BorderBeamTheme.of` walks **every** enclosing theme and merges them outside-in, so an inner theme overrides only the fields it names. [Full documentation →](doc/theming.md) ### Controller -Attach a `BorderBeamController` for programmatic playback. The controller takes **full ownership**: `playback.startAfter` and `playback.duration` must not be set (on the widget or on a theme — it is asserted), `active` and `autoPlay` are ignored, the controller's `speed` replaces `timing.speed`, and the beam starts hidden until you `start()`. +A `BorderBeamController` takes **full ownership** of playback: `playback.startAfter` and `playback.duration` must not be set (on the widget or a theme — it is asserted), `active` and `autoPlay` are ignored, the controller's `speed` replaces `timing.speed`, and the beam starts hidden until you call `start()`. ```dart final controller = BorderBeamController(); -BorderBeam.rotate(controller: controller, child: card); +BorderBeam(controller: controller, child: card); -controller.start(); // fade in, play +controller.start(); // fade in, play (or resume if paused) controller.pause(); // freeze the current frame controller.resume(); controller.speed = 2; // playback rate; must be positive controller.seek(const Duration(seconds: 1)); controller.pulse(); // one brightness bump, ~0.6s settle -controller.flash(); // blink to full, hold 120ms, decay +controller.flash(); // a sharper blink, hold 120ms, decay controller.stop(); // fade out, halt ``` -`isAttached`, `isActive`, and `isRunning` report state, and the controller is a `ChangeNotifier`, so a button can rebuild from it. **One controller drives one beam** — attaching a second asserts. A beam under a `BeamSync` runs on the group's clock and cannot also take a controller; drive the group through `BeamSync` instead. - -`stop()` fades out over 0.5s; `pause()` freezes the current frame with no fade at all, and `resume()` continues from exactly there. `pulse()` and `flash()` are accents on a running beam: they raise brightness and let it settle without touching the timeline, so a beam already sweeping can mark a moment. Both are no-ops while the beam is hidden or frozen. +`speed` and `seek` move the animation, never a fade or an accent, which run in real time; a `speedListenable` still wins over the controller's rate, and reduced motion's `slow` still quarters it. `isAttached`, `isActive`, and `isRunning` report state, and the controller is a `ChangeNotifier`. **One controller drives one beam** at a time; handing it to another beam in the same frame is fine. A beam under a `BeamSync` runs on the group's clock and cannot also take a controller. ### Driving the beam yourself -Four inputs take the beam off its own schedule without a controller. - ```dart -// A glowing progress ring (or, with .line, a progress bar). -BorderBeam.rotate(progress: downloaded / total, child: card); +// A glowing progress ring; with BeamEffect.line() a progress bar. +BorderBeam(progress: downloaded / total, child: card); -// The sweep gravitates to a point in the box. -BorderBeam.rotate(follow: const Offset(0.5, 0.2), child: card); +// The sweep gravitates to a point in the box (normalized 0–1). +BorderBeam(follow: const Offset(0.5, 0.2), child: card); // Live opacity and rate, without rebuilding. -BorderBeam.rotate( +BorderBeam( strengthListenable: micLevel, // ValueListenable speedListenable: tempo, // ValueListenable, positive child: card, ); ``` -| Input | Type | Effect | +| Input | Type | What it does | | --- | --- | --- | -| `progress` | `double?` (0–1) | Places the sweep instead of the clock. The clock still runs, so the fade, hue, and line tracks stay alive — the beam looks lit, not frozen. Repaints without re-resolving the config, so it is cheap to drive from an animation. | -| `follow` | `Offset?` (normalized) | Eases the sweep to the perimeter point nearest a point in the box — critically damped, ~150ms. Setting it back to null hands the sweep back to the clock without a snap. `progress` wins over it. | -| `strengthListenable` | `ValueListenable?` | The live twin of `style.strength`: scales every layer's opacity each frame, no rebuild. | -| `speedListenable` | `ValueListenable?` | The live twin of `timing.speed`, and it wins over both that and a controller's rate. | +| `progress` | `double?` (0–1) | Places the travel instead of the clock: `rotate` becomes a progress ring, `line` a progress bar. The clock keeps running underneath, so the fade and hue stay alive. Cheap to drive every frame. | +| `follow` | `Offset?` (normalized) | Eases the travel to the border point nearest a point in the box — critically damped, about 150ms. Null hands it back to the clock without a snap, keeping the direction it was travelling. `progress` wins over it. | +| `strengthListenable` | `ValueListenable?` | Scales the beam's opacity each frame, without a rebuild. | +| `speedListenable` | `ValueListenable?` | Sets the playback rate each frame; wins over `timing.speed` and a controller's rate. | -The pulse variants have no travel, so they ignore `progress` and `follow`. Feeding `follow` from a `MouseRegion` is what `BeamHover` does for you. +Ambient effects ignore `progress` and `follow`. `BeamHover` wires `follow` to the mouse for you. ### Synchronized groups -A beam owns its own ticker. Ten beams on a screen means ten tickers, each started at a different instant, so their sweeps drift apart — right for beams that have nothing to do with each other, wrong for a row of cards that should read as one system. `BeamSync` hands the whole subtree **one clock**: one ticker, one timeline, identical phases. +Each beam owns its own ticker, so beams started at different moments drift apart. `BeamSync` gives a subtree **one clock** — one ticker, one timeline, identical phases: ```dart BeamSync( child: Row( children: [ for (final (i, card) in cards.indexed) - BorderBeam.rotate( + BorderBeam( timing: BeamTiming(phaseOffset: i / cards.length), child: card, ), @@ -458,11 +462,11 @@ BeamSync( ); ``` -Beams stay individually configurable — palette, variant, shape, and `phaseOffset` are per beam — but **the group owns playback**: `active`, `autoPlay`, `startAfter`, `duration`, and `repeat` are ignored below a `BeamSync`. Use its own `active` and `speed` instead. Reduced motion is group-owned too, through `BeamSync.reducedMotion`. +Effect, palette, shape, and `phaseOffset` stay per beam, but **the group owns playback**: `active`, `autoPlay`, `startAfter`, `duration`, `repeat`, `fadeCurve`, `pauseWhenOffscreen`, and `timing.speed` are ignored below a `BeamSync`. Use its own `active`, `speed`, and `reducedMotion` instead. A member that changes its `cycle` retimes only itself. ### Overlay and decoration -`BorderBeam.overlay` is a beam with no child of its own, sized by its parent — it traces content it does not have to wrap: +`BorderBeam.overlay` is a beam with no child of its own, sized by its parent: ```dart Stack( @@ -473,12 +477,12 @@ Stack( ); ``` -`BeamDecoration` is the same engine as a `Decoration`, for dropping into a `Container` you already have: +`BeamDecoration` is the same renderer as a `Decoration`, for a `Container` you already have. Put it in `foregroundDecoration:` so it paints over the child, as `BorderBeam` does: ```dart Container( foregroundDecoration: BeamDecoration( - variant: BeamVariant.rotate, + effect: const BeamEffect.rotate(), brightness: Theme.of(context).brightness, theme: BorderBeamTheme.of(context), colors: BeamColors.ocean, @@ -492,16 +496,7 @@ Container( ); ``` -A decoration paints in exactly one slot, so the variant decides which: `rotate`, `small`, `line`, and `pulseInside` go in `foregroundDecoration:`; `pulseOutside` goes in `decoration:`, because its halo blooms behind the child. - -A `BoxPainter` gets a canvas and nothing else, which costs the decoration four things the widget has. Prefer `BorderBeam` when any of them matter: - -- **Ambient theming is passed in, not read.** `brightness` is required and `theme:` takes what `BorderBeamTheme.of(context)` would have returned. -- **The ticker is unmanaged.** It is not created through a `TickerProvider`, so `TickerMode` does not mute it — a beam in a scrollable's cache extent or under an inactive route keeps ticking until the decoration is replaced or its render object is disposed. -- **Reduced motion is not observed.** `MediaQuery.disableAnimationsOf` is unreachable, so `playback.reducedMotion` is inert here. -- **`active` is a starting state, not a toggle**, and the decoration does not interpolate: `lerpFrom`/`lerpTo` return null, so an `AnimatedContainer` snaps between two beam decorations at the halfway point. - -Like the widget, it never absorbs a pointer: `hitTest` returns false. +A `BoxPainter` has no `BuildContext`, so the decoration form gives up four things the widget has: ambient theming is passed in (`brightness` is required, `theme:` takes `BorderBeamTheme.of(context)`); its ticker is not muted by `TickerMode`; reduced motion and `pauseWhenOffscreen` are not observed; and `active` is a starting state, not a toggle. Prefer `BorderBeam` when any of those matter. ### Interaction wrappers @@ -511,211 +506,139 @@ BeamHover(borderRadius: 20, child: pricingCard); BeamPress(borderRadius: 20, onTap: submit, child: card); ``` -| Widget | Lights when | Default variant | Notable knobs | +| Widget | Lights when | Default effect | Notable options | | --- | --- | --- | --- | -| `BeamFocusRing` | `child`'s subtree (or `focusNode`) holds focus | `small`, `ocean` | `alwaysShow` lights it under `FocusHighlightMode.touch` too | -| `BeamHover` | the cursor is over `child`, pulling the sweep toward it | `rotate` | `followPointer`, `holdAfterExit` (300ms) | -| `BeamPress` | a finger is down on `child` | `pulseInside` | `minimumDuration` (600ms), `onTap` | +| `BeamFocusRing` | `child`'s subtree (or `focusNode`) holds focus | `rotate` (compact on small controls), `ocean` palette unless `style` or a theme sets colours | `alwaysShow` lights it under touch focus too | +| `BeamHover` | the cursor is over `child`, pulling the travel toward it | `rotate` | `followPointer`, `holdAfterExit` (300ms) | +| `BeamPress` | a finger is down on `child` | `pulse` | `minimumDuration` (600ms), `onTap` | -Each is a thin wrapper that flips `BorderBeam`'s `active` (and, for `BeamHover`, feeds `follow`), so a transition gets the beam's own fades rather than a cut, and each passes `style`, `shape`, and `timing` straight through. - -`BeamFocusRing` follows `FocusManager.highlightMode`, the same rule `FocusableActionDetector` uses: it shows for keyboard and mouse focus and stays dark for touch. `BeamHover` is a desktop and web wrapper — on a touch device no mouse ever enters and the beam stays dark; `BeamPress` is its touch counterpart, holding the beam lit until `minimumDuration` has passed so a quick tap is a pulse rather than a flicker. `BeamPress` observes raw pointer events through a translucent `Listener` and never enters the gesture arena, so a button inside keeps its own taps and a scrollable above keeps its drags. +Each flips `BorderBeam`'s `active` (and `BeamHover` feeds `follow`), so transitions use the beam's own fades, and each passes `effect`, `style`, `shape`, and `timing` through. `BeamPress` listens through a translucent `Listener` and never enters the gesture arena, so buttons inside keep their taps and scrollables above keep their drags. ## Reference -Every field is nullable and a null means *inherit*, so these tables are the defaults you get by leaving a field out. +Every field is nullable and null means *inherit*; the defaults below are what you get when nothing sets a field. ### `BeamStyle` -| Field | Type | Default | Applies to | -| --- | --- | --- | --- | -| `colors` | `BeamColors?` | `BeamColors.colorful` | all | -| `theme` | `BeamTheme?` | `BeamTheme.auto` | all | -| `strength` | `double?` | `1.0` (clamped 0–1) | all | -| `brightness` | `double?` | preset, else `1.3` | all | -| `saturation` | `double?` | preset | all | -| `hueRange` | `double?` | `30` (`line` caps at 13) | all | -| `hueMode` | `BeamHueMode?` | `pingPong` traveling, `continuous` pulse | all | -| `hueBase` | `double?` | `0` | all | -| `staticColors` | `bool?` | `false` (forced on by `mono` and `gold`) | all | -| `strokeOpacityFactor` | `double?` | `1` | all | -| `innerOpacityFactor` | `double?` | `1` | all | -| `bloomOpacityFactor` | `double?` | `1` | all | -| `glowBoost` | `double?` | `1` | `pulseInside`, `pulseOutside` | -| `coreBlur` | `double?` | preset | `pulseOutside` | -| `bloomBlur` | `double?` | preset | `pulseOutside` | -| `glowBrightness` | `double?` | preset | `pulseOutside` | -| `glowSaturation` | `double?` | preset | `pulseOutside` | -| `tailLength` | `double?` | `1` | `rotate`, `small` | -| `glowSpread` | `double?` | `1` | all | -| `comet` | `bool?` | `false` | `rotate`, `small` | -| `sparkle` | `double?` | `0` (clamped 0–1) | `rotate`, `small` | -| `segments` | `int?` | none (solid ring) | `rotate`, `small`, `line` | -| `innerSizeScale` | `double?` | `1` | `pulseInside` | -| `renderScale` | `double?` | `1` (clamped 0.25–1) | all | -| `pulseOutsideTuning` | `BeamPulseOutsideTuning?` | `demo` | `pulseOutside` | -| `themeConfig` | `BeamThemeConfig?` | per variant × brightness | all | - -`pulseOutsideTuning` switches only the glow geometry: `BeamPulseOutsideTuning.demo` (the default) scales insets and blurs by the element's size, melting the separate blobs into one continuous edge-hugging glow; `.stock` uses the library's fixed insets and per-brightness blur. +| Field | Type | Default | +| --- | --- | --- | +| `colors` | `BeamColors?` | `BeamColors.colorful` | +| `theme` | `BeamTheme?` | `BeamTheme.auto` | +| `strength` | `double?` | `1` (clamped 0–1) | +| `glow` | `double?` | `1` (must not be negative) | +| `hueMode` | `BeamHueMode?` | per effect (see [Effects](#effects)) | +| `hueShift` | `double?` | `30` | +| `hueBase` | `double?` | `0` | ### `BeamShape` -| Field | Type | Default | Applies to | -| --- | --- | --- | --- | -| `radius` | `BorderRadiusGeometry?` | 16 (32 for `small`) | all — ignored when `contour` is set | -| `borderWidth` | `double?` | `1` | all | -| `superellipse` | `bool?` | `false` | all — ignored when `contour` is set | -| `edge` | `BeamEdge?` | `BeamEdge.bottom` | `line` | -| `ringOffset` | `double?` | `0` | all | -| `contour` | `BeamContour?` | none | all | -| `segment` | `BeamSegment?` | none (full contour) | all | -| `wrapCorners` | `bool?` | `false` | `line`, without a segment | +| Field | Type | Default | +| --- | --- | --- | +| `radius` | `BorderRadiusGeometry?` | 16 on every corner | +| `superellipse` | `bool?` | `false` | +| `borderWidth` | `double?` | `1` | +| `ringOffset` | `double?` | `0` | +| `segment` | `BeamSegment?` | the whole border | +| `dashes` | `int?` | `0` (solid) | ### `BeamTiming` -| Field | Type | Default | Applies to | -| --- | --- | --- | --- | -| `cycle` | `Duration?` | 1.96s rotate/small · 3.1s line · 2.3s pulse | all | -| `cycleGap` | `Duration?` | `Duration.zero` | `rotate`, `small`, `line` | -| `speed` | `double?` | `1` (a controller's `speed` wins) | all | -| `direction` | `BeamDirection?` | `forward` | `rotate`, `small`, `line` | -| `phaseOffset` | `double?` | `0` (fraction of a cycle, 0–1) | all | -| `beamCount` | `int?` | `1` | `rotate`, `small`, `line` | -| `huePeriod` | `Duration?` | 12s traveling · 16s pulseInside · 14s pulseOutside | all | -| `bloomHuePeriod` | `Duration?` | 8s | `line` | -| `breatheFactor` | `double?` | `1.3` × `cycle` | `line` | -| `spikeFactor` | `double?` | `1.33` × `cycle` | `line` | -| `spike2Factor` | `double?` | `1.7` × `cycle` | `line` | +| Field | Type | Default | +| --- | --- | --- | +| `cycle` | `Duration?` | per effect (see [Overview](#overview)) | +| `cycleGap` | `Duration?` | zero; travelling effects only | +| `speed` | `double?` | `1` (a controller's `speed` replaces it; the fades always run in real time) | +| `direction` | `BeamDirection?` | `forward` | +| `phaseOffset` | `double?` | `0` (fraction of a cycle, 0–1) | +| `huePeriod` | `Duration?` | per effect (see [Effects](#effects)) | ### `BeamPlayback` | Field | Type | Default | Meaning | | --- | --- | --- | --- | -| `active` | `bool?` | `true` | Play state. Toggling fades in (0.6s) / out (0.5s). | +| `active` | `bool?` | `true` | Play state. Toggling fades in (~0.5s) / out (~0.6s). | | `autoPlay` | `bool?` | `true` | Whether the beam starts by itself. | | `startAfter` | `Duration?` | none | Delay before autoplay. Must be null with a controller. | -| `duration` | `Duration?` | none (plays on) | Total play time before a self fade-out. Must be null with a controller. | -| `repeat` | `BeamRepeat?` | `BeamRepeat.forever()` | `forever()`, `once()`, or `count(n)` cycles, then a fade-out. | +| `duration` | `Duration?` | none | Total play time before the beam fades out by itself. Must be null with a controller. | +| `repeat` | `BeamRepeat?` | `forever()` | `forever()`, `once()`, or `count(n)` cycles, then a fade-out. | | `reducedMotion` | `BeamReducedMotion?` | `staticFrame` | What to do when the platform asks for reduced motion. | -| `pauseWhenOffscreen` | `bool?` | `true` | Stops the clock while the beam is scrolled out of its nearest enclosing `Scrollable`, with a 256px margin. | -| `fadeCurve` | `Curve?` | the fade spring | The easing both fade envelopes run on. | -| `debugFrozenAt` | `Duration?` | none | Pins the beam to one instant of its timeline and never starts its clock. The frozen frame is still scaled by the live strength. | - -### Palette constructors and transforms - -| Constructor / transform | Signature | What it does | -| --- | --- | --- | -| `BeamColors.custom` | `custom(List colors, {BeamColors base = BeamColors.colorful})` | Distributes your colors over `base`'s blob geometry, cycling when there are fewer colors than slots and preserving each entry's alpha. The list must not be empty. | -| `BeamColors.fromSeed` | `fromSeed(Color seed, {BeamSeedHarmony harmony = BeamSeedHarmony.analogous})` | Spreads one brand color into `analogous`, `complementary`, `triadic`, or `monochrome`. Derived colors are lifted into a readable glow band (lightness 0.55–0.70, saturation ≥ 0.55), so a black or gray seed still reads. | -| `BeamColors.fromScheme` | `fromScheme(ColorScheme scheme)` | Takes `primary`, `secondary`, `tertiary`, dropping roles that duplicate an earlier one. | -| `BeamColors.lerp` | `lerp(BeamColors a, BeamColors b, double t)` | Table-by-table `Color.lerp`. `t` is not clamped, so it extrapolates. | -| `scaleAlpha` | `scaleAlpha(double factor)` | Multiplies every table entry's alpha, preserving the relative depth of the inner / stroke / bloom layers. `factor` must not be negative. | -| `BeamColors.spec` | `spec({required List border, List? smallBorder, List? lineBlobs})` | Full per-blob control. `BeamBlob.size` holds ellipse **radii**, not diameters; omitted tables are derived by cycling the border colors. | +| `pauseWhenOffscreen` | `bool?` | `true` | Stop the clock while scrolled out of view (256px margin). | +| `fadeCurve` | `Curve?` | critically damped springs | The easing of both fades. `BeamPlayback.cssEase` is the web's `ease`. | +| `debugFrozenAt` | `Duration?` | none | Pin the beam to one instant and never start its clock. | ### Shorthands and precedence -Three fields are common enough to sit directly on the widget: `colors`, `active`, and `borderRadius` (a uniform `shape.radius`). They are shorthands, not separate settings — each folds into the matching value object, winning over the same field there. - -A field is resolved in one order, and only one: +`colors`, `active`, and `borderRadius` sit directly on the widget as shorthands for `style.colors`, `playback.active`, and a uniform `shape.radius`. A field resolves in one order: ```text -flat shorthand > value object on the widget > BorderBeamTheme > variant default +shorthand > value object on the widget > BorderBeamTheme (inner over outer) > effect default ``` -Nested `BorderBeamTheme`s merge inner over outer before the widget's own values are applied on top. - ## Accessibility -- **Reduced motion is honored by default.** With `MediaQuery.disableAnimations` set, every variant falls back to a single static frame; `hide`, `slow`, and `animate` are one field away. See the [Playback](#playback) table. -- **Beams add no semantics.** They are decoration, and decoration that announced itself would be noise. Screen readers describe your child exactly as they would without the beam. -- **Nothing is conveyed by the beam alone.** A beam marks a state that is already stated somewhere else — the button's label, the field's helper text, a status line. Treat it as emphasis, never as the only signal that something is loading, focused, or selected. -- **Pointers pass through.** No beam layer intercepts a pointer, so hit-testing, focus traversal, and gesture handling behave as if the beam were not there. -- **`BeamFocusRing` complements the platform focus ring**; it does not replace the focused widget's semantics, and it respects `FocusManager.highlightMode` so a tapped field does not sprout a keyboard-focus ring. +- **Reduced motion is honoured by default.** When the platform asks for it, every effect falls back to a single static frame; `hide`, `slow`, and `animate` are one field away. +- **Beams add no semantics.** Screen readers describe your child exactly as they would without the beam. +- **Never let the beam be the only signal.** A beam emphasizes a state that is stated elsewhere — a label, helper text, a status line. +- **Pointers pass through.** Nothing the beam paints takes part in hit-testing. +- **`BeamFocusRing` complements the focused widget's own semantics** and follows `FocusManager.highlightMode`, so a tapped field does not get a keyboard focus ring. [Full documentation →](doc/accessibility.md) ## Performance -- **One ticker per beam** — or exactly one per `BeamSync`, however many beams are in the group. -- **~30fps cap on the pulse variants**, matching the original's pulse driver. Time still accumulates at full resolution; only notifications are throttled, and a `pulse()`/`flash()` boost lifts the cap while it plays. -- **`RepaintBoundary` isolation.** The child sits in its own boundary inside the beam's, so animating the beam never re-rasterizes your content. -- **Color matrices are folded on the CPU.** Hue, brightness, and saturation are baked into gradient colors rather than carried on a `ColorFilter`, which would need a layer of its own. -- **Offscreen pause.** With `pauseWhenOffscreen` (the default), a beam scrolled out of its nearest enclosing `Scrollable` — with a 256px margin — stops its clock and resumes exactly where it left off. Play state, fades, and callbacks are untouched. +- **One shader, one draw.** Every frame of every effect is a single `drawRect` or `drawDRRect` with the beam's fragment shader. There is no `saveLayer`, no clip, no `ImageFilter` or `MaskFilter` blur, and no offscreen render target. Glows are evaluated analytically per pixel instead of blurred. A test asserts this for every effect, theme, and shape. +- **Fragment work only where light can land.** The draw covers the box grown by the furthest outward glow, minus the interior beyond the furthest inward one. +- **Little CPU per frame.** The effect samples its keyframes or oscillators and writes its layers — a few dozen colour blobs, windows, and filters — into a fixed block of uniform floats for a `FragmentShader` it reuses for the beam's lifetime. There is no path building and no gradient construction per frame. +- **Display-rate animation.** Every effect ticks on every frame the engine produces, with no frame-rate cap. To get 120Hz on ProMotion iPhones, your app's `ios/Runner/Info.plist` needs: -The `saveLayer` count per frame — `paintBehind` plus `paintAbove` — is a fixed, measured budget, not an estimate: + ```xml + CADisableMinimumFrameDurationOnPhone + + ``` -| Variant | `saveLayer`s per frame | -| --- | --- | -| `rotate` | 4 | -| `small` | 3 | -| `line` | 4 | -| `pulseInside` | 4 | -| `pulseOutside` | 3 | + Without it iOS holds Flutter apps to 60Hz. +- **`BorderBeam.precache()`** loads the shader once, ahead of the first beam. +- **One ticker per beam**, or one per `BeamSync` group, and **an offscreen pause** that stops beams scrolled out of view. +- **`RepaintBoundary` isolation.** The child sits in its own repaint boundary, so the beam animating never re-rasterizes your content. -`test/painting/save_layer_budget_test.dart` counts them through a counting canvas for every variant × brightness × palette × time sample and asserts each number **exactly**, so a regression and an improvement both fail the suite until the table is updated. +Keep the beam out from under widgets that force an offscreen pass, which costs more than the beam itself: `Opacity` / `AnimatedOpacity` / `FadeTransition` with a value between 0 and 1, `ShaderMask`, `BackdropFilter`, `ColorFiltered`, and `ImageFiltered`. To fade a beam, use `style.strength`, `strengthListenable`, or `active` instead of wrapping it in `Opacity`. [Full documentation →](doc/performance.md) -## Parity with the original - -The constants are transcribed verbatim from the upstream `src/styles.ts`, so the rendering matches. Where this package deliberately differs: - -| Area | flutter_border_beam | The original | -| --- | --- | --- | -| Fade envelope | A spring (mass 1, stiffness 180, damping 20) | CSS `ease` — available here as `fadeCurve: BeamPlayback.cssEase` | -| Reduced motion | All five variants, defaulting to a static frame | Pulse variants only (the web build hides them; iOS and React Native do the same) | -| pulse-outside defaults | Bake the tuning the original's web demo applies | The library's stock values — available here as `BeamStyle.pulseOutsideStock` | -| `BeamTheme.auto` | Follows `Theme.of(context)` | Follows the OS color scheme | -| Child radius | Passed in; no auto-detection | Read from the child | - -Flutter-only additions, with no upstream counterpart: `hueBase`, custom palettes (`custom` / `fromSeed` / `fromScheme` / `lerp` / `scaleAlpha` / `spec`) and the seven extra presets, per-corner radii, superellipse corners, stadium shapes, arbitrary contours, `BeamShape.segment`, `BeamShape.wrapCorners`, `segments`, `direction`, `cycleGap`, `beamCount`, `progress`, `follow`, `BeamSync`, `BeamDecoration`, and the `BeamFocusRing` / `BeamHover` / `BeamPress` wrappers. - -[Full documentation →](doc/parity.md) - - -## How it works - -Everything animated is a **pure function of elapsed time** — there are no `AnimationController`s anywhere. - -1. **Clock.** One `Ticker` per beam (or per `BeamSync`) accumulates `elapsedSeconds`, scaled by the playback rate and gated by the fade envelope. It mirrors the original's single shared `requestAnimationFrame` loop. -2. **Phases.** Each frame, a resolver recomputes every animated track from that one number — sweep position, hue, the line variant's breathe and spike scales, the pulse oscillator bank. Same time in, same frame out, which is what makes goldens and `debugFrozenAt` possible. -3. **Strategies.** One strategy per variant family turns those phases into geometry: the traveling window and its mask, or the breathing blob table. -4. **Layers.** A single `CustomPainter` paints the stroke ring, the inner glow, and the bloom within the budget above, on a `behind` pass (pulse-outside) or an `above` pass (everything else). - -[Full documentation →](doc/architecture.md) - - ## FAQ **The beam's corners don't match my card's.** -Pass the same radius your child uses — `borderRadius:` or `shape.radius`. The beam does not read the child's decoration, deliberately: it also wraps widgets that have no decoration to read. +Pass the same radius your child uses — `borderRadius:` or `shape.radius` — and `superellipse: true` if the child uses `RoundedSuperellipseBorder`. The beam does not read the child's decoration. **My beam is clipped.** -The beam paints outside the child's bounds. `pulseOutside` needs real room around it, and a positive `ringOffset` pushes the ring further out still. Add padding in the parent and remove any tight `ClipRRect` / `ClipPath` above the beam. +`rotate(comet: true)` and a positive `ringOffset` paint outside the child's bounds. Give the beam room — padding in the parent — and remove any tight `ClipRRect` / `ClipPath` above it. **Nothing shows up at all.** -Check reduced motion. With `reducedMotion: BeamReducedMotion.hide`, a platform request for reduced motion paints nothing — that is the behavior working. `staticFrame` (the default) always leaves a visible frame. +Check reduced motion: with `reducedMotion: BeamReducedMotion.hide`, a platform request for reduced motion paints nothing. In a widget test, `await BorderBeam.precache()` in `setUpAll` before checking pixels — the shader loads asynchronously. + +**Is it 120Hz?** +It runs at whatever rate the engine renders. On ProMotion iPhones that needs `CADisableMinimumFrameDurationOnPhone` in your `Info.plist` — see [Performance](#performance). -**The squircle option does nothing on my Flutter version.** -`superellipse` needs Flutter ≥ 3.35, where `RSuperellipse` is stable. That is the package's declared minimum, and CI tests against exactly that version. +**Does the child need to be opaque?** +No. Every effect paints in one pass over the child and nothing behind it, so a translucent child works. **Why does my segment run the wrong way?** -Segments always run clockwise from `start` to `end`, wrapping through top-center when needed. Swap the two anchors to select the complementary direction around the contour. +Segments always run clockwise from `start` to `end`, wrapping through top-centre. Swap the anchors for the other side of the border. **Does it work on web?** -Yes — the [live playground](https://simplifyjobs.github.io/flutter_border_beam/) is a web build of the example app, and CI builds it on every commit. The blur-heavy variants (`line`, `pulseOutside`) are the most expensive there, so prefer a single hero beam over a grid of them on web. +Yes — the [live demo](https://simplifyjobs.github.io/flutter_border_beam/) is a web build of the example app, and CI builds it on every commit. -**Can I animate between two beam configurations?** -With `BorderBeam`, yes — changing `cycle` retimes in place, and palettes crossfade with `BeamColors.lerp` driven by an `Animation`. With `BeamDecoration`, no: it does not interpolate, so an `AnimatedContainer` snaps. +**Can I animate between two configurations?** +With `BorderBeam`, yes: changing `cycle` retimes in place, and `BeamColors.lerp` driven by an animation crossfades palettes. `BeamDecoration` does not interpolate, so an `AnimatedContainer` snaps. ## Example app -[`example/`](example) is the full gallery — the original demo recreated, with mock chat inputs, task cards, and search bars, plus the interactive playground behind the [live playground](https://simplifyjobs.github.io/flutter_border_beam/) link, live code snippets, and shareable URLs: +[`example/`](example) is the one-screen showcase behind the [live demo](https://simplifyjobs.github.io/flutter_border_beam/): swipe between the three effects, each on the kind of widget it is made for — a task card, a chat composer, a "thinking" card — and recolour them with any preset in either theme. ```console cd example && flutter run @@ -727,23 +650,21 @@ Demo reels live in `example/lib/*.dart` and use the marker-based harness in `exa tool/record_demo.sh --target lib/showcase.dart --prefix SHOWCASE --contact ``` -Outputs land in `.demos/` (gitignored) as 60fps center-cropped mp4s with a contact sheet for review. +Outputs land in `.demos/` (gitignored). ## Contributing -Issues and pull requests are welcome — start with [CONTRIBUTING.md](CONTRIBUTING.md) for the local setup, the golden-test rules, and what a good change looks like here. Security reports go through [SECURITY.md](SECURITY.md). - -One rule worth knowing before you open an editor: **never tweak values in `lib/src/constants/`**. They are transcribed 1:1 from the upstream source and visual parity depends on them — see [doc/parity.md](doc/parity.md). +Issues and pull requests are welcome — start with [CONTRIBUTING.md](CONTRIBUTING.md) for the setup, the rendering rules, and the golden-test workflow. [doc/architecture.md](doc/architecture.md) explains how a frame is built. Security reports go through [SECURITY.md](SECURITY.md). ## Credits -This package is a port of **[border-beam](https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam)** — created and designed by **[Jakub Antalik](https://x.com/jakubantalik)** and released under the MIT license, with its own home at [Jakubantalik/border-beam](https://github.com/Jakubantalik/border-beam). All visual design — the five effects, color palettes, gradient geometry, animation timings, and the demo it ships with — is his work. If you like the effect, go star the original. +This package was originally ported from, and remains inspired by, **[border-beam](https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam)** by **[Jakub Antalik](https://x.com/jakubantalik)** ([live demo](https://beam.jakubantalik.com), [Jakubantalik/border-beam](https://github.com/Jakubantalik/border-beam)), released under the MIT license. The effects (`rotate`, `line`, `pulse`), the four original palettes, and the timings they started from are his design — if you like the look, go star the original. -The Flutter port adds the widget/controller architecture, superellipse shapes, custom palette API, and the canvas rendering engine. +Version 0.2.0 replaced the port with an independent native renderer: a single fragment shader written for Flutter, which no longer tracks the original's source. ## License -MIT. See [LICENSE](LICENSE) for details — it includes the original work's copyright notice. +MIT. See [LICENSE](LICENSE) — it includes the original work's copyright notice. diff --git a/SECURITY.md b/SECURITY.md index d8a9041..bd95a91 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -38,19 +38,21 @@ Please give us a reasonable window to ship a fix before disclosing publicly. ## Scope -This is a **rendering package**. It draws animated borders with Flutter's -canvas API: it opens no sockets, reads and writes no files, stores nothing, -and collects nothing. It has no runtime dependencies beyond the Flutter SDK. +This is a **rendering package**. It draws animated borders with one fragment +shader that ships inside the package: it opens no sockets, reads no files +other than its own bundled shader asset, writes nothing, stores nothing, and +collects nothing. It has no runtime dependencies beyond the Flutter SDK. Most of the vulnerability classes a security report usually covers simply have no surface here. In scope: -- Attacker-controllable input to the public API — colors, radii, durations, - a `BeamContour` path — that causes a crash, an unbounded allocation, a hang, - or an unrecoverable render-loop failure in a host app. +- Attacker-controllable input to the public API — colors, stops, radii, + durations, segment anchors — that causes a crash, an unbounded allocation, a + hang, or an unrecoverable render-loop failure in a host app. - A compromise of the release path: the publishing workflow, the pub.dev - automated-publishing configuration, or the published archive's contents. + automated-publishing configuration, or the published archive's contents + (including `shaders/beam.frag`). - Anything in the package that reaches the network or the filesystem. There should be nothing; if you find something, that is the report. @@ -61,5 +63,5 @@ Out of scope: - Frame-rate or battery cost of an animation configured to be expensive. - Vulnerabilities in Flutter, Dart, or a browser engine — report those to their own projects. -- The example gallery and the hosted playground, which contain no data and +- The example app and its hosted live demo, which contain no data and no accounts. diff --git a/analysis_options.yaml b/analysis_options.yaml index f5a026d..ba1dd61 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,6 +1,8 @@ include: package:flutter_lints/flutter.yaml analyzer: + exclude: + - build/** language: strict-casts: true strict-inference: true @@ -8,7 +10,25 @@ analyzer: linter: rules: + # Style the codebase already follows. - public_member_api_docs + - comment_references - prefer_single_quotes - directives_ordering - unnecessary_lambdas + # Correctness. A dropped `await` on `tester.pump()` is the classic source + # of widget tests that pass for the wrong reason; the rest guard the + # value objects' `==`, listeners, and public signatures. + - unawaited_futures + - avoid_dynamic_calls + - avoid_void_async + - cancel_subscriptions + - close_sinks + - test_types_in_equals + - throw_in_finally + - only_throw_errors + - unnecessary_statements + - always_declare_return_types + - type_annotate_public_apis + - no_adjacent_strings_in_list + - missing_whitespace_between_adjacent_strings diff --git a/assets/showcase/showcase.gif b/assets/showcase/showcase.gif index 44ff36f..733d411 100644 Binary files a/assets/showcase/showcase.gif and b/assets/showcase/showcase.gif differ diff --git a/assets/showcase/showcase.mp4 b/assets/showcase/showcase.mp4 index c6e1974..cad8c7c 100644 Binary files a/assets/showcase/showcase.mp4 and b/assets/showcase/showcase.mp4 differ diff --git a/doc/accessibility.md b/doc/accessibility.md index 25141de..a2f2c1a 100644 --- a/doc/accessibility.md +++ b/doc/accessibility.md @@ -4,13 +4,13 @@ A border beam is decoration. It should make a state easier to notice for people ## Reduced motion -When the platform asks for reduced motion — `MediaQuery.disableAnimationsOf`, which Flutter maps to *Reduce Motion* on iOS and *Remove animations* on Android — the beam obeys by default. +When the platform asks for reduced motion — `MediaQuery.disableAnimationsOf`, which Flutter maps to *Reduce Motion* on iOS and *Remove animations* on Android — every effect obeys by default. -| `BeamReducedMotion` | Behavior | Reach for it when | +| `BeamReducedMotion` | Behaviour | Reach for it when | | --- | --- | --- | | `staticFrame` | Paints one static frame and stops ticking. **The default.** | Almost always. The beam still marks the state; it just stops moving. | | `hide` | Paints nothing; the child is left bare, and no ticker runs. | The beam is pure decoration and the state is fully carried elsewhere. | -| `slow` | Keeps animating at a quarter speed. | Motion carries meaning that a still frame cannot (a progress ring). | +| `slow` | Keeps animating at a quarter speed. | Motion carries meaning that a still frame cannot. | | `animate` | Ignores the request. | Essentially never in product code. | ```dart @@ -23,24 +23,23 @@ BorderBeamTheme( ); ``` -Two details worth knowing: +Details worth knowing: -- **All five variants honor it.** The original applies reduced motion to the pulse variants only; this package applies it everywhere, which is why `staticFrame` — a frame that still communicates — is the default rather than `hide`. See [parity](parity.md). -- **A frozen beam stops ticking.** `staticFrame` and `hide` pause the clock rather than animating invisibly, so respecting the setting also saves the battery it was meant to save. - -Under a [`BeamSync`](motion.md#beamsync), reduced motion is group-owned because every beam shares one clock. Set `BeamSync.reducedMotion` to `staticFrame` (the default), `hide`, `slow`, or `animate`; per-beam settings are ignored while synchronized. - -`BeamDecoration` **cannot** observe reduced motion — a `BoxPainter` has no `BuildContext` — so `reducedMotion` is inert there. If a surface must honor the setting, use the widget. +- **The static frame is representative.** A travelling effect is shown partway through its sweep; an ambient one mid-breath; the palette in its own colours, without hue drift. A beam driven by `progress` still shows its value, so a progress ring stays a readout. +- **A still beam stops ticking.** `staticFrame` and `hide` pause the clock rather than animating invisibly, so respecting the setting also saves the battery it was meant to save. +- **Groups decide together.** Under a [`BeamSync`](motion.md#beamsync) every beam shares one clock, so reduced motion is set once on `BeamSync.reducedMotion` (`staticFrame` by default) and per-beam settings are ignored. +- **`BeamDecoration` cannot observe it.** A `BoxPainter` has no `BuildContext`, so `reducedMotion` is inert there. If a surface must honour the setting, use `BorderBeam`. ## Semantics Beams add **no** semantics. A screen reader describes your child exactly as it would without the beam, and nothing is announced when a beam starts, stops, or changes. -That is the correct default, and it puts one obligation on the caller: **never let the beam be the only signal.** A beam marks a state that is already stated somewhere a screen reader can reach — the button's label ("Generating…"), the field's helper text, a status line, a `Semantics` liveRegion. Treat the beam as emphasis on information that already exists. +That is the right default, and it puts one obligation on you: **never let the beam be the only signal.** A beam marks a state that is already stated somewhere a screen reader can reach — the button's label ("Generating…"), the field's helper text, a status line, a `Semantics` live region. Treat the beam as emphasis on information that already exists. ```dart // The beam emphasizes; the label states. -BorderBeam.pulseInside( +BorderBeam( + effect: const BeamEffect.pulse(), active: isGenerating, child: FilledButton( onPressed: isGenerating ? null : generate, @@ -53,13 +52,13 @@ If you catch yourself writing "the glowing one is selected", add a non-visual si ## Pointers and focus -No beam layer intercepts a pointer. `BorderBeam` paints through a `CustomPaint` whose layers are decorative, and `BeamDecoration.hitTest` returns false. Hit-testing, focus traversal, and gesture handling behave exactly as they would without the beam, so a beam can be dropped around an existing interactive widget without auditing its gestures. +Nothing a beam paints takes part in hit-testing. `BorderBeam` paints through a `CustomPaint` foreground painter, and `BeamDecoration.hitTest` returns false. Hit-testing, focus traversal, and gestures behave exactly as they would without the beam, so a beam can go around an existing interactive widget without auditing its gestures. -`BeamPress` is the one wrapper that touches input, and it does so through a translucent `Listener` that never enters the gesture arena — a button inside keeps its own taps, and a scrollable above keeps its drags. +`BeamPress` is the one wrapper that reads input, and it does so through a translucent `Listener` that never enters the gesture arena — a button inside keeps its own taps, and a scrollable above keeps its drags. ## Focus indication -`BeamFocusRing` is a *visual* focus indicator, complementing what the focused widget already reports rather than replacing it: +`BeamFocusRing` is a *visual* focus indicator. It complements what the focused widget already reports; it does not replace it: ```dart BeamFocusRing( @@ -68,15 +67,15 @@ BeamFocusRing( ); ``` -It follows `FocusManager.highlightMode`, the same rule `FocusableActionDetector` uses: it lights for keyboard and mouse focus and stays dark for touch, where a focus ring around a tapped field is noise. `alwaysShow: true` overrides that. +It follows `FocusManager.highlightMode`, the same rule `FocusableActionDetector` uses: it lights for keyboard and mouse focus and stays dark for touch, where a ring around a tapped field is noise. `alwaysShow: true` overrides that. -Because it only flips `BorderBeam`'s `active`, focus arrives and leaves on the beam's own fades rather than as a cut — but a fade is still a state change, so keep the underlying widget's own focus decoration if your design depends on an instant indicator. The ring does not replace the platform focus ring; it sits alongside it. +Because it only flips `BorderBeam`'s `active`, focus arrives and leaves on the beam's fades (about 0.5s in, 0.6s out) rather than as a cut. A fade is still a state change, so keep the underlying widget's own focus decoration if your design needs an instant indicator. ## Contrast and legibility -The beam paints *around* content, never over text, so it does not affect text contrast directly. Two things still deserve a look: +The beam mostly paints around content, but `BorderBeam` paints over its child, so wherever the light reaches in it changes the contrast of what lies beneath. Two things deserve a look: -- **A bright beam next to small text** raises the local luminance around it and can make a thin label feel lower-contrast than it measures. `style.strength` is the dial; 0.6–0.8 is often better on dense UI than the full 1.0. -- **`pulseOutside` changes the perceived edge of a card.** Its contract already asks for the child's own 1px border, which is what keeps the card's boundary legible when the halo is at its dimmest. +- **A bright beam next to small text** raises the luminance around it and can make a thin label feel lower-contrast than it measures. `style.strength` is the dial; 0.6–0.8 often sits better on dense UI than the full 1.0. +- **Inward glows** (the inner glow of `rotate` and `pulse`, `line`'s spikes) reach into the child. Keep important content clear of the border by the child's own padding, or turn the reach down with `style.glow`. -For anyone sensitive to flicker, the relevant settings are the same ones above: prefer longer cycles, and honor reduced motion with `staticFrame` or `hide`. Nothing in the package flashes faster than roughly one cycle per second at the default timings, but a very short `cycle` combined with `flash()` can, so treat sub-second cycles as a deliberate choice. +For anyone sensitive to flicker, the relevant settings are the same: prefer longer cycles, and honour reduced motion with `staticFrame` or `hide`. At the default timings nothing in the package repeats faster than about once a second on its own. Two things can: a very short `cycle`, and `BorderBeamController.flash()` (or `pulse()`) called in quick succession — each call starts a fresh accent, whatever the cycle. Treat sub-second cycles and repeated flashes as deliberate choices. diff --git a/doc/architecture.md b/doc/architecture.md index add6247..b440fb1 100644 --- a/doc/architecture.md +++ b/doc/architecture.md @@ -1,96 +1,186 @@ # Architecture -The one idea the whole package is built on: **everything animated is a pure function of elapsed time.** One `Ticker` produces a number; every visual value is recomputed from that number each frame. There are no `AnimationController`s anywhere, no per-track state to keep in sync, and no way for two tracks to drift apart — which mirrors the original React library's single shared `requestAnimationFrame` loop, and is what makes goldens, property tests, and `debugFrozenAt` possible. +Two ideas carry the whole package: + +1. **Everything animated is a pure function of elapsed time.** One `Ticker` produces a number of seconds; every visual value is recomputed from it each frame. There are no `AnimationController`s and no per-track state to keep in step, which is what makes goldens, property tests, and `BeamPlayback.debugFrozenAt` possible. +2. **Every frame is one shader draw.** An effect writes the layers of its look — blob tables, conic windows, masks, colour filters — into one uniform buffer; one fragment shader evaluates every layer per pixel and composites them in a single pass, with no offscreen layers, blurs, or clips. ## The frame ```text -Ticker ──► BeamClock ──► BeamPhaseResolver ──► VariantStrategy ──► BeamPainter - elapsed s every animated geometry for stroke / inner / - speed, fade track for this this variant bloom layers - pause, fps frame family +Ticker ─► BeamClock ─► BeamPhaseResolver ─► effect emitter ─► BeamFrameData ─► BeamRenderer ─► one draw + elapsed s BeamFramePhases _rotate, _line… 3 layers: blobs, uploads the floats, drawRect or + speed, fade sweep, hue, (pure functions) windows, masks, picks the bounds drawDRRect with + pause, boost travellers, cycles filters, tables of the light shaders/beam.frag ``` -1. **`BeamClock`** owns the ticker. It scales elapsed time by the playback rate, runs the fade envelope on activate/deactivate, handles pause/resume/seek, applies the optional fps cap, and carries the one-shot `pulse()`/`flash()` boosts. It is a `Listenable`; the painter repaints from it. -2. **`BeamPhaseResolver`** samples every animated track for a given time: sweep position, hue, the line variant's breathe and spike scales, the pulse oscillator bank. Pure — same time in, same phases out. -3. **A `VariantStrategy`** per variant family turns phases into geometry: the traveling window and its masks, or the breathing blob table. -4. **`BeamPainter`** is one `CustomPainter` running that pipeline into a fixed layer budget, on a `behind` pass (pulse-outside) or an `above` pass (everything else). +1. **`BeamClock`** (`lib/src/animation/beam_clock.dart`) owns the ticker. It keeps two times: the speed-scaled animation timeline every phase is sampled from, and unscaled active time — real seconds while it ticks. The fade-in and fade-out (critically damped springs, about 0.5s in and 0.6s out), the one-shot `pulse()` / `flash()` boosts, and `playback.duration` run on active time, so `speed`, seek, and retime move the animation without stretching, skipping, or replaying a fade; pause freezes both. It is a `Listenable` and notifies on every frame the engine produces — there is no frame-rate cap. Under a `BeamSync` one clock serves the whole subtree. +2. **`BeamPhaseResolver`** (`lib/src/animation/beam_phases.dart`) samples a `BeamFramePhases` for a time: the fade (including a cycle gap's envelope), the hue rotation and the time the hue track reads, the travel position of every traveller (`travellers`, spaced `1 / count` apart), whether this cycle runs mirrored, the continuous `cycles` clock the breathing runs on (the pulse, the line's spikes), and whether a `progress` / `follow` value is driving the travel. Pure — the same time in gives the same phases out. It knows nothing about what an effect looks like. +3. **The effect emitter** (`lib/src/effects/effect_emitters.dart`) is a switch over the sealed `BeamEffect`. Each effect is a function of the resolved `BeamConfig`, the phases, the `BeamOutline`, and the palette's blob tables (`BeamLook.tablesFor`), and writes its layers into a `BeamFrameData`. The time-driven design values — the line's width, height, spike, and edge-fade keyframes, the pulse's 17 oscillators — are sampled here, on the CPU, once per frame. +4. **`BeamFrameData`** (`lib/src/render/beam_frame.dart`) is the frame as the shader consumes it: the outline, the visible track, the conic coordinate, four conic tables, and three layers, each with a geometry, a window, an edge fade, an inset shadow, an overlay, a colour filter, an opacity, and a stack of blobs. It is one `Float32List` laid out exactly like the shader's uniform block, reset and rewritten in place every frame. +5. **`BeamRenderer`** (`lib/src/render/beam_renderer.dart`) owns one `FragmentShader`, one `Paint`, and one `BeamFrameData` per beam. Per frame it writes the outline and track, runs the emitter, folds each layer's colour filter into its colours, uploads the floats, works out where light can land, and issues a single `drawRect` or `drawDRRect` — or nothing, when no layer is lit. -## Module layout +`BeamPainter` (`lib/src/render/beam_painter.dart`) is the `CustomPainter` that runs this as `BorderBeam`'s foreground painter. Its repaint listenable is the clock merged with the shader-ready signal and the driven `progress` / `strength` listenables, so frames never rebuild widgets. `BeamDecoration` runs the same renderer from a `BoxPainter`. -### Public entry points +`BeamProgram` (`lib/src/render/beam_program.dart`) loads `shaders/beam.frag` once per process (`FragmentProgram.fromAsset`, trying the `packages/flutter_border_beam/` key a consuming app uses and the bare key the package's own tests use). Until it resolves, beams paint nothing; `BorderBeam.precache()` awaits it. + +## The layer model + +The look is the reference design's own construction, evaluated per pixel. A beam is up to three layers, composited bottom to top, and every effect uses the same three: layer 0 is the inner glow, layer 1 the 1px stroke, and layer 2 the bloom. + +A layer is: + +- **A stack of blobs** — soft radial ellipses, each with a centre, two radii, a straight colour, and a piecewise-linear alpha falloff (`a0` at the centre through two mid stops to 0 at the rim). They composite premultiplied source-over in painting order, each over the ones before. A blob is placed in the plane, or in **path space** (arc length along the outline × depth in), where a streak bends around a corner with the border. +- **An overlay** — a conic table drawn in white or black under the blobs: the travelling beam's head highlight, the bloom band. +- **An inset shadow** — solid to a depth inside the outline, then blurred. +- **A geometry** — the 1px **ring** just inside the outline (anti-aliased over one device pixel, which is what keeps it a hairline), the **filled** shape, a **blurred ring** clipped to the shape, or a **glow** outside the shape that fades out (the shape grown by a reach and blurred — rotate's comet). The glow is the only geometry that paints outside the outline. +- **A window** — a **conic** table (rotating with the beam: `tw = fract(angle − start)`, repeated `count` times round the turn) or a **radial** ellipse riding an edge. +- **An edge fade** — opaque at the edge, fading to transparent a short depth in (the two axes screened), or by depth in path space. `BeamStyle.glow` deepens it, capped so a small box keeps a clear middle. +- **A colour filter** — CSS `hue-rotate → brightness → saturate` as a 3 × 3 matrix. The renderer always folds it into each colour of the layer on the CPU — every blob, the overlay ink, the shadow — before compositing, which keeps overlapping colours saturated; the layer's matrix in the shader stays the identity. +- **An opacity** — the family preset × fade × strength × the mono halving × `glow` (up to 1, on the glow layers), clamped to 1. + +### The outline + +The outline is a rectangle with four independently sized corners. A corner is either a circular arc or a superellipse ("squircle") curve. The superellipse follows Flutter's own `RSuperellipse` construction (`impeller/geometry/round_superellipse_param`): each corner is two halves meeting on its diagonal, and each half is a superellipse from the middle of its edge to a joint, then a circular arc to the diagonal, with the exponent and joint looked up from the ratio of the edge's half-length to the radius. That ratio is why one shape spans cards, pills, and circles — a 56 px pill's ends come out as exact semicircles while its long edges ease in over a much longer run — and it keeps the stroke on the edge of a child clipped by `RoundedSuperellipseBorder` to within Flutter's own path approximation. The shader derives each corner's parameters from the radii and box per pixel, only near a corner. Uneven radii keep each corner to its own quarter of the box rather than Flutter's proportional split, which is exact in ordinary use and drifts by about 2% of the radius only where a half-short-side corner meets a square one across that side. + +For every pixel the shader derives the signed distance `d` to the outline (negative inside), the arc length `s` from top-centre clockwise (`u = s / length`), and the outward normal of the nearest piece. Distance in a corner is the first-order estimate `R · f / |∇f|` (exact for a circle); deep inside a superellipse corner it blends toward the circular distance. `u` is continuous on and outside a convex outline, but inside the shape the nearest piece jumps across the medial axis — so the glows that reach inside are planar blobs, or path-space blobs that stay within the edge fade, never fields of `u`. + +### Blurs, analytically + +The reference design blurs three things; each becomes closed-form maths: + +- **A blurred 1px ring** (the rotate bloom, the pulse bloom) is the ring's width times the normal density across it: `w / σ · φ(d_c / σ)` with `d_c` the distance to the ring's centre line, clipped to the shape. Its colour comes from the bloom's conic table — pre-blurred around the turn on the CPU — or from blobs sampled where the ring is, not where the light spread to. +- **A blurred blob** (the line's spikes and dot) is the energy-preserving gaussian of the blob plus the blur: the profile's mass and variance are integrated on the CPU (`σ² = r² · m₂ / 2m₀ + blur²`, peak `= mass / (σx · σy)`). Where the design cuts a blob at an edge before blurring it (the line's bloom stops at the box), the gaussian is truncated there and moment-matched, so light below the edge never spills back in. +- **A blurred glow outside the shape** (the comet) is a smooth step across the outline grown by its reach: `Φ((reach − d) / σ)`. + +### Compositing and the draw + +Layers composite source-over, premultiplied, then the visible track (the segment mask, feathered more the further light is from the stroke) multiplies the result; a layer marked dashed is cut into dashes first. A small interleaved-gradient dither on the soft tails keeps 8-bit targets from banding. + +The renderer bounds the draw to where light can land: the box grown by the furthest outward reach (the comet's reach plus three sigmas of its blur), minus the interior beyond the furthest inward reach (the edge fade, the blurred ring's three sigmas). That ring is one `drawDRRect`; when a layer fills the whole box (the line's bloom) it is one `drawRect`. + +## The design data + +`lib/src/look/` holds the tuned values the look is built from — plain data, safe to retune (the goldens will move): | File | Contents | | --- | --- | -| `lib/flutter_border_beam.dart` | The barrel. Only `BorderBeam`, `BorderBeamController`, `BorderBeamTheme`/`BorderBeamThemeData`, `BeamSync`, `BeamVariant`, `BeamColors`/`BeamSeedHarmony`, `BeamBlob`/`LineBlob`, `BeamTheme`, `BeamThemeConfig`, the four value objects, the option types, and the four widgets are exported. | -| `lib/src/border_beam.dart` | The widget: a generic constructor taking a `BeamVariant`, `BorderBeam.overlay`, five named constructors, three flat shorthands (`colors` / `active` / `borderRadius`), the driven inputs (`progress`, `follow`, `strengthListenable`, `speedListenable`), and all scheduling and lifecycle. A controller attached ⇒ it owns playback exclusively. | -| `lib/src/border_beam_controller.dart` | `BorderBeamController` — a `ChangeNotifier` over one clock. | -| `lib/src/border_beam_theme.dart` | `BorderBeamTheme` (an `InheritedWidget`) + `BorderBeamThemeData`. `of` walks every enclosing scope, depends on each, and merges them outside-in, so nested themes compose. | -| `lib/src/beam_sync.dart` | `BeamSync` and its internal scope — one clock for a whole subtree. | +| `palette_tables.dart` | `BeamLookTables` and the tables of the four original palettes: 9 border blobs, 8 + 8 compact-chip blobs, the line's 9 + 9 + 9 streak blobs, its spike colours and 5 bloom spike pairs. | +| `extra_palettes.dart` | The seven extras' colour lists, cycled over `colorful`'s tables. | +| `beam_look.dart` | `BeamLook.tablesFor(palette)`: a palette's own tables, the extras' cycled ones, or — for every other palette — `colorful`'s geometry recoloured by sampling the palette's stops where each blob sits. Memoized per palette. | +| `layer_presets.dart` | Per family (rotate, compact chip, line, pulse) and surface: the three layer opacities, the inset shadow colour, brightness, saturation. | +| `rotate_look.dart` | The rotate window, the compact window, the head highlight and bloom band tables; the inner blob alpha and scale; blurs; the 56 px compact threshold. | +| `line_look.dart` | The line's keyframes (travel x and width, edge fade, height, two spike tracks) and its window, highlight, spike, dot, ambient, and shadow geometry. | +| `pulse_tables.dart`, `pulse_look.dart` | The pulse's blob tables (ring map, inner sizes, bloom), the breathing parameters, the 17-oscillator bank, and the breath the corner opacities follow (a quicker swell than fade). | -### `lib/src/models/` — data types +## Mirrors between Dart and the shader -The four public **value objects** (`beam_style.dart`, `beam_shape.dart`, `beam_timing.dart`, `beam_playback.dart`) are all-nullable, `const`, with `copyWith` / `merge` / `==`. A null field means *inherit*. +Some of the shader's maths runs on the CPU too, and the two copies must agree exactly. -`beam_options.dart` holds the small option types those fields take: `BeamHueMode`, `BeamDirection`, `BeamEdge`, `BeamReducedMotion`, `BeamRepeat`, `BeamPulseOutsideTuning`, and the `BeamContour` / `BeamPathContour` pair — a contour is a config-cache key, so every implementer overrides `==` / `hashCode`. +**`BeamOutline`** (`lib/src/render/beam_outline.dart`) is the Dart mirror of the shader's `outline()`. `locate()` returns the same `(d, u)` the GPU computes, including the nearest-piece choice; `pointAt` / `normalAt` invert it. Emitters lay blobs along the outline with it, `BeamSegment` anchors resolve against it, and `BorderBeam.follow` maps a pointer to the border with it. The renderer packs its `radii`, its corner model (circular or superellipse), `length`, and `quadStarts` straight into the shader, so a change to the corner model goes in both places at once. A test renders the real shader at 3× and checks its distance against `locate()` pixel by pixel. -`beam_colors.dart` is the sealed `BeamColors` hierarchy (preset, custom, seed, scheme, lerp, scaled, spec) with the value-keyed LRU that memoizes resolution; `beam_palette.dart` and `beam_blob.dart` are the resolved tables and their entries; `beam_theme.dart` and `beam_theme_config.dart` are the brightness selector and the per-variant × brightness preset. +**Conic tables.** `BeamFrameData.tableAt` reads a table exactly as the shader's `TABLE_LOOKUP` does; tests read windows and overlays back through it. -`beam_config.dart` is where it all lands. `BeamConfig.resolve({variant, palette, brightness, style, shape, timing, textDirection})` flattens the value objects into the painter's config, mirroring the React component's computed values — per-variant default durations and radii, the line variant's 13° hue cap, mono forcing static colors. It carries the timing tracks (`gapSeconds`, hue periods, breathe/spike factors) and a per-corner resolved `BorderRadius`, and it is value-equal, so `BeamPainter.shouldRepaint` compares configs. +**The uniform layout.** The shader declares only `vec4`s and `vec4` arrays, so the float layout is identical on every backend (Impeller on Metal, Vulkan, and GLES, and Skia). `BeamFrameData` writes floats by index in declaration order: -### `lib/src/animation/` +| # | Uniform | Floats | +| --- | --- | --- | +| 1 | `uRect` — box left, top, width, height | 4 | +| 2 | `uRadii` — corner radii TL, TR, BR, BL | 4 | +| 3 | `uShape` — corner model (0 circular, 1 superellipse), unused, stroke width, px per device px | 4 | +| 4 | `uPerim` — perimeter length, unused, dither | 4 | +| 5 | `uQuads` — arc length at which each quadrant starts | 4 | +| 6 | `uMask` — track start, span, feather, dashes | 4 | +| 7 | `uConic` — conic centre, start angle (turns), repeats | 4 | +| 8 | `uLayer[27]` — 9 vec4s per layer: geometry, window and overlay, window parameters, blob mode and count, shadow colour, shadow and dash flags, colour matrix rows | 108 | +| 9–12 | `uWinA[8]`, `uWinB[8]`, `uOverA[8]`, `uOverB[8]` — conic tables, 16 (position, alpha) stops each | 4 × 32 | +| 13–15 | `uBlobA[42]`, `uBlobB[30]`, `uBlobC[30]` — 14, 10, and 10 blobs, three vec4s each | 408 | + +That is 672 floats, `beamUniformFloats` — inside the 896 (224 `vec4`s) GLES 3.0 guarantees. `test/render/uniform_layout_test.dart` parses `shaders/beam.frag` and checks that every uniform is a `vec4` or `vec4` array, that each array holds what `BeamFrameData` packs (`beamLayerCount`, `tableStops`, the blob slots), that the shader's loops run to the slot counts, and that the declared floats add up to `beamUniformFloats`. It also checks the *order*: it derives each uniform's offset from the shader's declarations and runs every `BeamFrameData` writer on a fresh frame, so a uniform reordered on one side only — which would otherwise shift every value after it and paint garbage rather than fail — breaks the test. Change the shader's declarations and `beam_frame.dart`'s offsets in one commit. + +## Module layout + +### Public entry points + +| File | Contents | +| --- | --- | +| `lib/flutter_border_beam.dart` | The barrel. It exports `BorderBeam`, `BorderBeamController`, `BorderBeamTheme` / `BorderBeamThemeData`, `BeamSync`, `BeamEffect` and its three subclasses (`RotateEffect`, `LineEffect`, `PulseEffect`), `BeamColors` / `BeamSeedHarmony`, the option types (`BeamDirection`, `BeamEdge`, `BeamHueMode`, `BeamReducedMotion`, `BeamRepeat`), `BeamAnchor` / `BeamCorner` / `BeamSegment`, `BeamTheme`, the four value objects, and the four widgets. Nothing under `render/` is public. | +| `lib/src/border_beam.dart` | The widget: `BorderBeam` and `BorderBeam.overlay`, the three shorthands (`colors`, `active`, `borderRadius`), the driven inputs (`progress`, `follow`, `strengthListenable`, `speedListenable`), `BorderBeam.precache()`, and all scheduling and lifecycle. A controller attached ⇒ it owns playback. | +| `lib/src/border_beam_controller.dart` | `BorderBeamController`, a `ChangeNotifier` over one clock. | +| `lib/src/border_beam_theme.dart` | `BorderBeamTheme` (an `InheritedWidget`) and `BorderBeamThemeData`, with an `effect` slot and one per value object. `of` walks every enclosing scope, depends on each, and merges them outside-in. | +| `lib/src/beam_sync.dart` | `BeamSync` and its internal scope — one clock for a subtree. | + +### `lib/src/effects/` | File | Contents | | --- | --- | -| `beam_clock.dart` | The ticker, playback rate, pause/resume/seek, spring or curve fade envelopes, the optional fps cap, and the `pulse`/`flash` boosts. | -| `spring_curve.dart` | The in-package fade spring (mass 1, stiffness 180, damping 20) — the reason the package depends on nothing but the Flutter SDK. | -| `oscillator.dart` | The ping-pong helper and the 17-oscillator pulse bank. | -| `beam_phases.dart` | `BeamPhaseResolver` — the per-frame value object and keyframe sampling. | +| `beam_effect.dart` | The sealed `BeamEffect` and its three `final` subclasses. Each knows its name, whether it travels, and its default cycle, cycle gap, hue mode, and hue period. Value-equal. | +| `effect_emitters.dart` | `emitEffect` and one private emitter per effect; `BeamFrame` (what an emitter reads); `applyTrack` / `segmentTrack` (the visible track); `conicFraction` (the conic angle of a point, shared with `follow`). | + +### `lib/src/look/` + +The design data (see above). -### `lib/src/painting/` +### `lib/src/render/` | File | Contents | | --- | --- | -| `beam_painter.dart` | The single `CustomPainter`; repaint driven by the clock, `behind` / `above` passes. | -| `variant_strategy.dart` | The strategy interface, including `preferredFps`. | -| `strategies/` | `rotate_strategy.dart`, `line_strategy.dart`, `pulse_inner_strategy.dart`, `pulse_outer_strategy.dart`, and the `pulse_common.dart` they share. | -| `ring_geometry.dart` | The rounded-rect and `RSuperellipse` ring, built as a `Path.combine` difference; contour and ring-offset handling. | -| `gradient_builders.dart` | Blob tables to `Gradient`s, and the CSS↔Flutter conventions. | -| `color_matrix.dart` | Hue, brightness, and saturation matrices, folded into colors on the CPU. | -| `layer_utils.dart` | The `saveLayer` helpers the budget is counted through. | +| `beam_renderer.dart` | `BeamRenderer`: per-beam shader, `Paint`, and frame data; the upload; the draw bounds. | +| `beam_frame.dart` | `BeamFrameData` — the uniform buffer and its writers — the layer, window, table, and blob-space enums, `beamUniformFloats`, and the slot counts. | +| `beam_outline.dart` | `BeamOutline`, the Dart mirror of the shader's outline, including the port of Flutter's `RSuperellipse` construction (`squircleReach`). | +| `beam_painter.dart` | `BeamPainter`, the `CustomPainter`. | +| `beam_program.dart` | `BeamProgram`, the shared `FragmentProgram`. | +| `color_math.dart` | `mixColor`, `samplePalette` — gamma-aware palette blending on the CPU (stops, lerps, derived blob tables). The shader never blends palette stops; blobs arrive coloured. | -### `lib/src/constants/` +### `shaders/beam.frag` -Verbatim transcriptions of the upstream `src/styles.ts` tables — `palettes.dart`, `theme_presets.dart`, `pulse_tables.dart`, `pulse_params.dart`, `pulse_constants.dart`, `line_keyframes.dart`, `line_geometry.dart`, `rotate_stops.dart` — plus `upstream.dart` (internal provenance: the tracked library and spec versions and the source repository) and `extra_palettes.dart` (the seven Flutter-only presets, which are *not* transcriptions). `tool/spec/refresh.sh` vendors upstream's machine-readable spec into `test/fixtures/`, and `test/constants/spec_parity_test.dart` asserts every table against it. See [parity](parity.md). +The layer model, per pixel. Its header describes it; its uniform block is the contract above. It is declared under `flutter: shaders:` in `pubspec.yaml` and must ship in the published archive. + +### `lib/src/models/` + +The four public value objects (`beam_style.dart`, `beam_shape.dart`, `beam_timing.dart`, `beam_playback.dart`) are all-nullable, `const`, with `copyWith` / `merge` / `==`; a null field means *inherit*. `beam_options.dart` holds the option enums and `BeamRepeat`; `beam_segment.dart` holds `BeamAnchor`, `BeamCorner`, and `BeamSegment`. + +`beam_colors.dart` is the sealed `BeamColors` hierarchy (preset, stops, solid, seed, lerp, scaled) with a value-keyed LRU memo; `beam_presets.dart` holds the 19 preset palettes; `beam_palette.dart` is the resolved ring of stops (at most `maxPaletteStops`, 8), carrying a preset's own blob tables (or the extras' table colours) and the mono flag. `beam_theme.dart` is the `dark` / `light` / `auto` selector. `model_validation.dart` repeats the constructor assertions at runtime, because assertions vanish in release builds. + +`beam_config.dart` is where it lands: `BeamConfig.resolve({effect, palette, brightness, style, shape, timing, textDirection})` settles every inherited value — the effect's default cycle, gap, hue mode, and hue period, the 16px default radius, a fixed-hue palette forcing `BeamHueMode.none` — into one value-equal config, so `BeamPainter.shouldRepaint` compares configs. + +### `lib/src/animation/` + +| File | Contents | +| --- | --- | +| `beam_clock.dart` | The ticker, playback rate, pause / resume / seek / retime, the fade envelopes, and the `pulse` / `flash` boosts — the animation on the speed-scaled timeline, the fades and boosts on unscaled active time. | +| `spring_curve.dart` | `BeamSpringCurve`: springs described as Apple's APIs describe them (damping ratio and response) — the critically damped fade-in and fade-out, and the bouncier rise of the pulse/flash accents. | +| `beam_phases.dart` | `BeamFramePhases` and `BeamPhaseResolver`. | ### `lib/src/widgets/` -`beam_decoration.dart` (the engine as a `Decoration`), `beam_focus_ring.dart`, `beam_hover.dart`, `beam_press.dart`. +`beam_decoration.dart` (the renderer as a `Decoration`), `beam_focus_ring.dart`, `beam_hover.dart`, `beam_press.dart`. + +## Invariants -## Invariants worth knowing +**One draw per lit frame, and nothing that forces an offscreen pass.** A frame issues exactly one `drawRect` or `drawDRRect` with the beam shader — or none, when the fade or a cycle gap leaves no layer lit — and no `saveLayer`, no clip, no `ImageFilter`, no `MaskFilter`, with saves and restores balanced. `test/render/frame_budget_test.dart` asserts this for every effect × theme × palette subset × shape family × several instants, plus effect options and driven progress. A blur in the design becomes analytic maths in the shader, never a layer. -**Never tweak values in `lib/src/constants/`.** They are transcribed 1:1 from the source and pinned by the constant tests. See [parity](parity.md). +**The uniform contract moves as one.** The shader's uniform block and `beam_frame.dart`'s offsets and slot counts change in the same commit (see above). -**The saveLayer budget is exact.** rotate 4, small 3, line 4, pulseInside 4, pulseOutside 3 per frame, asserted by `test/painting/save_layer_budget_test.dart` — a regression and an improvement both fail until the table moves. Never add a `saveLayer` just to carry a `ColorFilter`; a filter rides on a layer that exists anyway, and blur is the only filter allowed to justify a layer of its own. See [performance](performance.md). +**`BeamOutline` mirrors `outline()` exactly.** A change to corner geometry or to how `u` is measured is made in both, or blobs land off the stroke and segments resolve to the wrong place. -**CSS↔Flutter conventions** live in `gradient_builders.dart` and are listed in [parity](parity.md#css--flutter-mapping): conic gradients start at 12 o'clock so `SweepGradient` needs a baked −90°; CSS radial-gradient sizes are radii; `blur(Npx)` maps to sigma = N; fades go to `color.withValues(alpha: 0)`, never `Color(0x00000000)`. +**Fixed slots.** Layer 0 holds 14 blobs, layers 1 and 2 hold 10 each, and a conic table 16 stops; `addBlob` drops anything past a layer's slots. The pulse's inner glow (9 blobs + 4 corner accents) is the fullest layer. -**Layer opacity is a multiplied chain** — fade × preset × mono × hook × strength — clamped at paint time. Presets legitimately exceed 1 (line/dark's stroke is 1.14). +**Nothing inside the shape reads `u`.** Inside the shape `u` jumps across the medial axis; inner glows are planar blobs, or path-space blobs kept within the edge fade. Blobs laid along the outline (`_onOutline`) are planar ellipses whose axes follow the normal, so they stay seamless through a corner. -**The line variant does not use the mono ×0.5 multiplier.** Its mono treatment is spike attenuation inside the bloom, in `LineStrategy`. +**Emitters are pure and allocation-light.** An emitter is a function of the config, the phases, the outline, and the palette's tables; it writes into the renderer's reused `BeamFrameData` and builds no buffers per frame (table transforms use scratch lists; the oscillator banks are cached per tuning; derived tables are memoized per palette). -**Speed never reaches `BeamConfig`.** It is applied to the clock, deliberately kept out of the config cache key, so a rate change rides through without re-resolving the config or rebuilding the phase resolver. +**Speed never reaches `BeamConfig`.** It is applied to the clock and kept out of the config cache key, so a rate change does not re-resolve the config or rebuild the phase resolver. ## Tests | Directory | Covers | | --- | --- | -| `test/models/` | Value objects, `BeamConfig.resolve`, palettes, colors, variants. | -| `test/animation/` | Clock, spring curve, oscillators, phases, travel, periods, and a seeded property test over `BeamPhaseResolver.sample`. | -| `test/painting/` | Ring geometry, color matrices, surface features, the saveLayer budget, degenerate geometry, and a paint smoke sweep. | -| `test/widget/` | `BorderBeam` itself: lifecycle, updates, shorthands, theming, sync, speed, progress, motion, cycle gap. | +| `test/models/` | The value objects, `BeamConfig.resolve`, `BeamColors` and palettes, `BeamEffect`, segments. | +| `test/animation/` | The clock, the spring, phase sampling, travel, and a seeded property test over `BeamPhaseResolver.sample`. | +| `test/render/` | The frame budget, the uniform layout, `BeamOutline`, `BeamFrameData` sanity and structure per effect (`beam_frame_test.dart`), degenerate geometry, a paint smoke sweep through the real shader, and where light lands (`paint_structure_test.dart`). | +| `test/widget/` | `BorderBeam` itself: lifecycle, updates, shorthands, theming, sync, speed, progress, follow, motion, playback, cycle gap, shape. | | `test/widgets/` | The four widgets in `lib/src/widgets/`. | -| `test/golden/` | Golden families, one per axis — `beam_`, `palette_`, `motion_`, `surface_`, `widgets_`. | -| `test/constants/`, `test/fixtures/` | The transcription check against the extracted upstream fixtures. | +| `test/golden/` | Five golden families — `beam_`, `palette_`, `motion_`, `surface_`, `widgets_`. | -Golden scenes freeze the fake clock at a known time (t=1.3s — post fade-in, mid-cycle) for every variant × theme × palette, with the traveling variants captured a second time further along their sweep. Goldens are pinned to macOS rendering and to the Flutter version CI pins; regenerating on another OS or SDK produces diffs. +Golden scenes freeze the fake clock at t = 1.3s (past the fade-in, mid-cycle); travelling effects are captured a second time further along. Goldens are generated on macOS on the Flutter version `ci.yaml` pins; regenerating on another OS or SDK produces diffs. diff --git a/doc/effects.md b/doc/effects.md new file mode 100644 index 0000000..b5189c4 --- /dev/null +++ b/doc/effects.md @@ -0,0 +1,96 @@ +# Effects + +An effect decides where light sits along the border and how it moves. Pick one with `effect:` on `BorderBeam`, `BorderBeam.overlay`, `BeamDecoration`, or any of the interaction wrappers, or set a default for a subtree with `BorderBeamThemeData.effect`. With nothing set, a beam uses `BeamEffect.rotate()`. + +```dart +BorderBeam(effect: const BeamEffect.line(), child: composer); +``` + +All three are drawn by the same shader in the same single draw call, so they cost the same order of GPU time. Choose for the look and the meaning. + +## The two families + +**Travelling** — `rotate`, `line`. A position runs along the border once per `cycle`. These respond to: + +- `BeamTiming.direction` — `forward`, `reverse`, or `bounce` (alternating each cycle); +- `BeamTiming.cycleGap` — a rest after each sweep; +- `BeamTiming.phaseOffset` — where in the cycle the timeline starts; +- `BorderBeam.progress` — the position from a value instead of the clock; +- `BorderBeam.follow` — the position eased toward a point in the box. + +**Ambient** — `pulse`. Light breathes around the whole border at once. It has no direction and ignores `cycleGap`, `progress`, and `follow`; `phaseOffset` puts its breathing out of step. + +`BeamEffect.travels` answers the question in code. + +## Defaults + +| Effect | Family | `cycle` | `cycleGap` | `hueMode` | `huePeriod` | +| --- | --- | --- | --- | --- | --- | +| `rotate` | travelling | 2.4s | 0 | `pingPong` | 12s | +| `line` | travelling | 3.1s | 0 | `pingPong` | 8s | +| `pulse` | ambient | 2.3s | — | `continuous` | 16s | + +Every one of these is a fallback: `BeamTiming` and `BeamStyle` override them field by field. `BeamEffect.defaultCycle`, `defaultCycleGap`, `defaultHueMode`, and `defaultHuePeriod` expose them in code. + +Each effect is also tuned twice — once for dark surfaces and once for light ones — and `BeamStyle.theme` picks which (see [theming](theming.md)). + +## `rotate` — the default + +A beam laps the whole border, trailing a soft tail and lighting the inside edge as it passes, with a hot core just behind its head. For cards, panels, and surfaces. + +```dart +BorderBeam( + effect: const BeamEffect.rotate(length: 1.4, count: 2, comet: true), + child: card, +); +``` + +| Parameter | Default | Meaning | +| --- | --- | --- | +| `length` | 1 | Tail length multiplier, clamped to 0.25–2. Must be positive. | +| `count` | 1 | How many beams lap the border at once, evenly spaced. 1–4. | +| `comet` | false | Adds an outer glow that trails the head *outside* the border. Leave room around the widget (see [light outside the bounds](shape.md#light-outside-the-bounds)). | + +The beam sweeps around the box's centre, so it rounds the corners quickly and slows along the middle of the long edges. A box 56px or shorter (a chip, a pill button) gets the compact tuning — a wider window and a glow that fills the control; pair it with `BeamShape.stadium()`. + +With `progress`, the head sits at that fraction of the turn, clockwise from 12 o'clock — a glowing progress ring; `follow` points the head at the pointer. With a [segment](shape.md#segments), the beam appears at the segment's start and travels to its end. + +## `line` — inputs + +A streak rides one edge, its colours spread across it, with soft spikes of light rising inward from the edge, each breathing on its own beat. For text fields, search bars, and composers, where a full lap would fight the caret for attention. + +```dart +BorderBeam(effect: const BeamEffect.line(edge: BeamEdge.top), child: searchBar); +``` + +| Parameter | Default | Meaning | +| --- | --- | --- | +| `edge` | `BeamEdge.bottom` | The edge the streak rides. | + +A timed streak eases along the edge, widening through the middle of its run and fading in and out near the ends. It runs in reading order — left to right on the top and bottom edges, top to bottom on the side edges — under `BeamDirection.forward`; `reverse` mirrors it. + +With `progress`, the streak sits at that fraction of the edge and stays lit: a progress bar. With `follow`, only the coordinate along the edge counts. + +With a [segment](shape.md#segments), the streak rides the segment instead of `edge`, rounding its corners: `BeamSegment.bottomEdge` carries it around both bottom corners, `BeamSegment.bottomHalf` up both sides. + +The palette is spread across the streak rather than around the ring, so every colour of the palette shows at once. Under `pingPong` the drift runs on two tracks: the bloom swings over one `huePeriod`, a little wider than the stroke, and the stroke more slowly, over one and a half. Both swings are capped well inside the default `hueShift`, so a streak's colours never wander far. + +## `pulse` — a contained "thinking" state + +Patches of colour on the hairline and washing inward from the edges, each swelling, drifting, and ebbing on its own beat — three groups of blobs breathing in size and position and four corners breathing in strength, so neighbours never pulse in lockstep. Each corner breathes in quicker than it breathes out: its light swells over the first part of the breath and settles back over the rest, both on Apple's ease-in-out. + +```dart +BorderBeam(effect: const BeamEffect.pulse(), active: isThinking, child: card); +``` + +Its colours rotate continuously by default (a full turn every 16s). With a segment, only the patches inside it breathe. + +## Choosing at runtime + +Effects are values: two `BeamEffect.rotate(count: 2)` are equal, and `BeamEffect.values` lists all three with their default parameters. Store one in state and hand it to the widget — no switch needed: + +```dart +BorderBeam(effect: _effect, child: card); +``` + +Swapping the effect on a live beam keeps it running; the new effect picks up from the same clock. diff --git a/doc/motion.md b/doc/motion.md index b7d72ab..c14bbcb 100644 --- a/doc/motion.md +++ b/doc/motion.md @@ -1,102 +1,110 @@ # Motion -Timing, direction, rest, synchronization, and taking the sweep off the clock entirely. The [README's timing table](../README.md#timing) lists the fields and defaults; this guide is about how they interact. +Timing, direction, rest, synchronization, and taking the travel off the clock. The [README's `BeamTiming` table](../README.md#beamtiming) lists the fields and defaults; this guide is about how they interact. ## The clock -One `Ticker` accumulates elapsed seconds. Every animated value — sweep position, hue, the line variant's breathe and spike scales, the pulse oscillator bank — is recomputed from that single number each frame. There are no `AnimationController`s and no per-track state, which is what makes the whole engine a pure function of time. +One `Ticker` accumulates elapsed seconds. Every value on the timeline — the travel position, the hue, the breathing of the ambient effects — is recomputed from that one number each frame. There are no `AnimationController`s and no per-track state, so the same instant always puts the travel, the hue, and the breath in the same place. A frame also carries what sits beside the timeline: the fades and the controller's accents, which run on real time (below), and a [`follow`](#follow) easing toward its target. -`speed` scales how fast that number advances. It is applied to the clock rather than to the config, so changing it never re-resolves the beam or rebuilds the phase resolver — a rate change is free. +The clock ticks on every frame the engine produces. Nothing is capped, so a beam runs at 120Hz on a 120Hz display (on ProMotion iPhones, once the app opts in — see [performance](performance.md#120hz)). -Three things can drive the rate, in order: a `speedListenable`, then an attached `BorderBeamController`'s `speed`, then `timing.speed`. Under a `BeamSync` the group's rate owns all of them. +`speed` scales how fast the elapsed time advances. It is applied to the clock rather than to the config, so changing it never re-resolves the beam — a rate change is free. Three things can set the rate, in order: a `speedListenable`, then an attached `BorderBeamController`'s `speed`, then `timing.speed`; `BeamReducedMotion.slow` then quarters whichever wins. Under a `BeamSync` the group's `speed` owns all of them. + +`speed` moves the animation only. The fades and the controller's `pulse()` / `flash()` accents run on real time, so a beam at half speed still fades in about 0.5s, and seeking or retiming never stretches, skips, or replays a fade. Pausing — the controller's `pause()`, an offscreen pause — freezes both. ## Cycle and retiming -`cycle` is one lap for a traveling variant and one breath for a pulse variant. Changing it on a live beam **retimes in place**: every track keeps the phase it was at, so the beam smoothly speeds up or slows down instead of jumping to the new cycle's start. +`cycle` is one sweep of a travelling effect and one breath of `pulse`. Each effect has its own default — see [effects](effects.md#defaults). + +Changing `cycle` on a live beam **retimes it in place**: the travel keeps the position it was at, so the beam speeds up or slows down instead of jumping to the new cycle's start. ```dart -BorderBeam.rotate( - timing: BeamTiming(cycle: isUrgent - ? const Duration(milliseconds: 900) - : const Duration(milliseconds: 1960)), +BorderBeam( + timing: BeamTiming( + cycle: isUrgent + ? const Duration(milliseconds: 900) + : const Duration(milliseconds: 2400), + ), child: card, ); ``` -That is the mechanism to reach for when a beam should react to state. Toggling `active` fades out and back in; changing `cycle` keeps the light on and changes its urgency. +That is the tool when a beam should react to state: toggling `active` fades out and back in, while changing `cycle` keeps the light on and changes its urgency. + +The fades run on critically damped springs — Apple's `.smooth` — so the light eases in from rest and settles without overshoot: about 0.5s in, and a slightly longer, gentler 0.6s out, so it leaves softly rather than cutting off. They run in real time, whatever the `speed`, and a retime mid-fade leaves the fade alone. `BeamPlayback.fadeCurve` replaces both with your own curve (`BeamPlayback.cssEase` is the web's `ease`). ## Rest between sweeps -`cycleGap` parks the beam at the end of its travel after each lap: +`cycleGap` parks a travelling effect at the end of its travel after each sweep: ```dart -BorderBeam.rotate( +BorderBeam( timing: const BeamTiming(cycleGap: Duration(milliseconds: 1200)), child: card, ); ``` -The sweep itself still takes `cycle`; the gap is added after it. The beam's fade envelope eases out and back in over `min(0.25s, gap / 2)` at each end, so the rest reads as the beam breathing rather than blinking off. Hue, breathe, and spike are textures rather than the sweep, so they keep running through the gap — the beam is dark, not frozen. +The sweep still takes `cycle`; the gap is added after it. The beam fades out and back in over `min(0.25s, gap / 2)` at each end of the rest, so it reads as breathing rather than blinking off. The hue drift keeps running through the gap. -Changing the gap needs no retime: the current sweep keeps its position and the gap simply appears at the next cycle end. The pulse variants ignore it — their breathing has no cycle boundary to rest at. +No effect rests by default. Changing the gap needs no retime: the current sweep keeps its position and the rest appears at the next cycle end. Ambient effects ignore it — their motion has no cycle boundary to rest at. ## Direction, offset, and count ```dart -BorderBeam.rotate( +BorderBeam( + effect: const BeamEffect.rotate(count: 3), timing: const BeamTiming( direction: BeamDirection.bounce, phaseOffset: 0.25, - beamCount: 3, ), child: card, ); ``` -- **`direction`** — `forward` (clockwise; left-to-right for `line`), `reverse` (the mirror), or `bounce` (alternating each cycle). The pulse variants have no travel to direct. -- **`phaseOffset`** — a fraction of a cycle, 0–1, that the timeline starts at. Two beams on the same cycle with different offsets run out of step. -- **`beamCount`** — how many beams travel the contour at once, spaced equally along the cycle. Every beam shares one clock and one config, so the count costs geometry, not tickers. +- **`direction`** — `forward` (clockwise; reading order for `line`), `reverse` (the mirror), or `bounce` (alternating each cycle). It applies to the travelling effects; `pulse` has no direction. +- **`phaseOffset`** — the fraction of a cycle, 0–1, the timeline starts at. Two beams on the same cycle with different offsets run out of step — a travelling beam sits further along its sweep, an ambient one breathes out of phase. +- **`BeamEffect.rotate(count:)`** — how many beams lap the border at once, 1–4, spaced evenly. They share one clock and one draw, so the count costs nothing extra. -`beamCount` with `bounce` is worth trying on a wide card: the beams meet and part rather than chasing each other around. +`count` with `bounce` is worth trying on a wide card: the beams meet and part rather than chasing each other. -Segments compose with the same travel controls. The segment always names a clockwise span; `direction` controls which way a traveler crosses it, and `cycleGap` adds the normal rest after a traveling sweep. Two beams with opposite directions make a counter-sweep: +Segments compose with the same controls. A segment always names a clockwise span; `direction` decides which way a traveller crosses it, and `cycleGap` adds the usual rest. Two beams with opposite directions make a counter-sweep: ```dart Stack( children: [ - BorderBeam.rotate( + BorderBeam( shape: const BeamShape(segment: BeamSegment.bottomHalf), child: card, ), - BorderBeam.rotate( - shape: const BeamShape(segment: BeamSegment.bottomHalf), - timing: const BeamTiming(direction: BeamDirection.reverse), - child: card, + const Positioned.fill( + child: BorderBeam.overlay( + shape: BeamShape(segment: BeamSegment.bottomHalf), + timing: BeamTiming(direction: BeamDirection.reverse), + ), ), ], ); ``` -Add the same `cycleGap` to both timings when the arcs should disappear between passes. +## Hue drift -## The hue tracks +The hue is a separate track from the travel, on its own period (`huePeriod`): -The hue is a separate track from the sweep, on its own period. - -| | Traveling (`rotate`, `small`, `line`) | Pulse | +| `hueMode` | What it does | Default for | | --- | --- | --- | -| Default `hueMode` | `pingPong` — swings ±`hueRange` | `continuous` — a full 360° revolution | -| Default `huePeriod` | 12s | 16s (`pulseInside`) · 14s (`pulseOutside`) | +| `pingPong` | Swings ±`hueShift` degrees (30 by default) and back, eased at each end. | `rotate` (12s), `line` (8s) | +| `continuous` | Turns a full 360° per period, never reversing. | `pulse` (16s) | +| `none` | No drift. | — (`mono` and `gold` force it) | -`hueMode` is settable on either family, and swapping it is the cheapest way to change a palette's character: `continuous` on a traveling variant turns a subtle shimmer into a full rainbow cycle, and `pingPong` on a pulse variant calms it down. +`line` splits its `pingPong` drift in two: the bloom swings over one `huePeriod` and the stroke over one and a half, both capped narrower than the default `hueShift` (see [effects](effects.md#line--inputs)). -`line` has a second hue track for its bloom (`bloomHuePeriod`, 8s), swinging across ±(`hueRange` + 10)°, and its `hueRange` is capped at 13° regardless of what you set — see [variants](variants.md). +Any effect accepts any mode: `continuous` on `rotate` turns a subtle swing into a full rainbow, and `pingPong` on `pulse` calms it. `mono` and `gold` never drift. `hueBase` shifts the whole palette by a fixed number of degrees, independent of the drift. -`hueBase` shifts the whole palette by a fixed number of degrees, independent of the animation. It has no upstream counterpart and is the quickest way to nudge a preset toward your brand without leaving the preset. +Changing `huePeriod` mid-run re-phases the drift: the colours jump once to where the new period puts them, then continue smoothly. ## Reduced motion -Reduced motion is a *playback* concern rather than a timing one — the field lives on `BeamPlayback` and has four behaviors. See [accessibility](accessibility.md). +Reduced motion is a playback concern rather than a timing one — the field lives on `BeamPlayback` and has four behaviours. See [accessibility](accessibility.md). ## `BeamSync` @@ -108,7 +116,8 @@ BeamSync( child: Column( children: [ for (final (i, row) in rows.indexed) - BorderBeam.line( + BorderBeam( + effect: const BeamEffect.line(), timing: BeamTiming(phaseOffset: i / rows.length), child: row, ), @@ -117,28 +126,26 @@ BeamSync( ); ``` -The group owns playback: `active`, `autoPlay`, `startAfter`, `duration`, and `repeat` are ignored below it, and a `BorderBeamController` asserts rather than fighting for the clock. Everything visual stays per beam — palette, variant, shape — as does `phaseOffset`, which is what lets a synced group be evenly spaced rather than perfectly stacked. +The group owns playback: `active`, `autoPlay`, `startAfter`, `duration`, `repeat`, `fadeCurve`, `pauseWhenOffscreen`, and `timing.speed` are ignored below it, and a `BorderBeamController` asserts rather than fighting for the clock. Everything visual stays per beam — effect, palette, shape — as does `phaseOffset`, which is what spaces a synced group evenly rather than stacking it. Timing stays per beam too: a member that changes its `cycle` retimes in place without moving the rest of the group. -Reduced motion is group-owned because every beam shares one clock. Set `BeamSync.reducedMotion` to `staticFrame` (the default), `hide`, `slow`, or `animate`; per-beam settings are ignored while synchronized. +Reduced motion is group-owned too, because every beam shares one clock: set `BeamSync.reducedMotion` (`staticFrame` by default). Per-beam settings are ignored while synchronized. -## Driving the sweep yourself +## Driving the travel yourself -Two inputs take the sweep off the clock without stopping it. +Two inputs take the travel off the clock without stopping the clock. ### `progress` ```dart -BorderBeam.rotate(progress: received / total, child: card); +BorderBeam(progress: received / total, child: card); ``` -The sweep sits where the value says, turning `rotate` into a glowing progress ring and `line` into a progress bar. The clock keeps running underneath, so the fade envelope, the hue shift, and the line variant's breathe and spike tracks are all still alive — the beam reads as lit rather than frozen. Changing it repaints without re-resolving the configuration, so driving it from an `AnimationController` every frame is cheap. +The travel sits where the value says: `rotate` becomes a glowing progress ring, `line` a progress bar. A driven value maps linearly — no easing — and the travel stays lit: no rest from a `cycleGap`, and no fade at the ends of `line`'s run. The clock keeps running underneath, so the fade in and out, the hue drift, and `line`'s spikes stay alive, and `style.strength` still scales the light. Changing it repaints without re-resolving the configuration, so driving it from an `AnimationController` every frame is cheap. ### `follow` ```dart -class _Card extends StatefulWidget { /* … */ } - -// In the State: +// In a State: Offset? _follow; @override @@ -155,22 +162,28 @@ Widget build(BuildContext context) { }); }, onExit: (_) => setState(() => _follow = null), - child: BorderBeam.rotate(follow: _follow, child: card), + child: BorderBeam(follow: _follow, child: card), ); } ``` -The beam leaves its schedule and eases to the perimeter point nearest the given normalized point — critically damped, about 150ms, so a jittery pointer stream is smoothed without lag you can feel. Setting it back to null hands the sweep back to the clock from wherever it is, with no snap. +The travel leaves its schedule and eases toward the given normalized point — critically damped, about 150ms, so a jittery pointer is smoothed without a lag you can feel. `rotate` turns its head toward it, the shortest way round (on a segment, to the border point nearest it); `line` follows the coordinate along its edge. Setting it back to null hands the travel back to the clock from wherever it is, without a snap: the sweep resumes from that point, travelling the way it was — a bouncing beam keeps its direction — and never lands in the rest of a `cycleGap`. -`progress` wins over `follow`, and the pulse variants ignore both. `BeamHover` is this wired up for you. +`progress` wins over `follow`, and the ambient effects ignore both. A NaN `progress` or a non-finite `follow` counts as unset. `BeamHover` is this wired up for you. ### Live listenables -`strengthListenable` and `speedListenable` are the per-frame twins of `style.strength` and `timing.speed`: they change the beam without rebuilding the widget, which is what you want when the source is a mic level, a download rate, or a tempo. +`strengthListenable` and `speedListenable` are the per-frame twins of `style.strength` and `timing.speed`: they change the beam without rebuilding the widget, which is what you want when the source is a microphone level, a download rate, or a tempo. ```dart -BorderBeam.rotate( +BorderBeam( strengthListenable: level, // ValueListenable child: card, ); ``` + +Values of `strengthListenable` above 1 brighten the beam, saturating at full opacity. + +### Accents + +A `BorderBeamController` adds two one-shot accents on a running beam: `pulse()` lifts its brightness and lets it settle over about 0.6s, and `flash()` blinks it brighter, holds 120ms, and decays. Neither touches the timeline. diff --git a/doc/palettes.md b/doc/palettes.md index acc9dab..4266c80 100644 --- a/doc/palettes.md +++ b/doc/palettes.md @@ -1,35 +1,49 @@ # Palettes -A palette is not a list of colors — it is a set of **blob tables**. Each table entry is an ellipse with a color, a fractional position, and a pair of radii, and the beam's look comes from where those ellipses sit as much as from their hues. The [README's palette tables](../README.md#palettes) list every preset and factory; this guide is about how they work. +A palette is a **ring of colour stops around the border**. Each stop is a colour at a perimeter position in `[0, 1)`: 0 is top-centre, and positions increase clockwise by arc length. Between stops the colour blends, and past the last stop it blends back into the first across top-centre, so the ring has no seam. -## What a palette actually holds +Effects draw a palette as soft blobs of colour placed around the border — the same blob tables the original design was tuned with: -`BeamPalette` carries one table per surface the engine paints: +- The four originals (`colorful`, `mono`, `ocean`, `sunset`) carry their own hand-tuned tables; the seven extras that follow them cycle their colours over `colorful`'s tables. +- Every other palette — the presets new in 0.2 and everything you build with `BeamColors(...)`, `.solid`, `.fromSeed`, `.fromScheme`, `.lerp` — keeps `colorful`'s blob geometry and takes each blob's colour from the ring of stops at the point of the border the blob sits on (`line`'s blobs, which travel with the streak, take it from their place across the streak). `scaleAlpha` keeps a preset's own tables, dimmed, and a `.lerp` at exactly 0 or 1 is its end palette, tables and all. The tables are worked out once per palette. -| Table | Used by | -| --- | --- | -| `border` (9 blobs) | the `rotate` stroke, and as the pulse variants' color source | -| `smallBorder`, `smallInner` | `small` | -| `lineDark`, `lineLight`, `lineInner` | `line`, per brightness | -| `lineBloomDark`, `lineBloomLight`, `spike`, `spikeLt` | the `line` bloom and its spikes | +How the colours are shown depends on the effect: -Plus three modifiers: `forcesStaticColors` (pin the hue), `opacityMultiplier` (the mono ×0.5), and `monoTreatment`. - -This is why `BeamColors.custom` takes a *list of colors* and a *base*: it keeps the base's positions, radii, and per-entry alpha and substitutes only the hues, so a custom palette keeps the layered depth the original tuned. +- `rotate` and `pulse` hold the colours still and reveal them wherever their light falls — a rotating beam changes colour as it laps the border. +- `line` spreads the palette across its streak, so every colour shows at once. ## Presets -Four come from upstream (`colorful`, `mono`, `ocean`, `sunset`) and are transcribed verbatim. Seven are original to this package (`aurora`, `neon`, `candy`, `ember`, `ice`, `gold`, `holographic`) and are defined as short color lists in `lib/src/constants/extra_palettes.dart`, distributed over `colorful`'s geometry exactly the way `BeamColors.custom` does. Editing one of those lists changes how that preset looks and has no bearing on parity with the source. - -Two presets pin the hue, for different reasons: - -- **`mono`** carries the source's full mono treatment: static colors *and* halved layer opacity, which stops a grayscale beam blowing out. -- **`gold`** pins the hue but keeps full opacity. A hue sweep over a single-hue metal reads as the metal changing material; halving a warm amber only makes it muddy. - -`holographic` is the opposite bet — deliberately low-contrast pastels that come alive when paired with a fast continuous hue drift: +| Preset | Colours | Notes | +| --- | --- | --- | +| `colorful` | orange, magenta, violet, blue, green, hot pink | the default | +| `mono` | whites and greys | the hue never drifts | +| `ocean` | blues and violets | | +| `sunset` | reds, oranges, amber | | +| `aurora` | teal, violet, green | | +| `neon` | magenta, lime, cyan | the loudest | +| `candy` | pastel pink, lavender, peach | | +| `ember` | deep red, orange, gold | | +| `ice` | pale blue, white, cyan | | +| `gold` | amber, gold, bronze | the hue never drifts | +| `holographic` | desaturated pastels | built for a fast continuous hue drift | +| `lagoon` | teal, aqua, mint | | +| `dusk` | indigo, violet, rose | | +| `forest` | emerald, lime, teal | | +| `rose` | pink, coral, mauve | | +| `cosmic` | deep violet, electric blue, magenta | | +| `citrus` | lime, yellow, tangerine | | +| `sky` | cerulean, periwinkle, white-blue | | +| `lavender` | lilac, lavender, soft pink | | + +`BeamColors.presets` is a `Map` of all 19, in this order — handy for a picker. The presets' stops live in `lib/src/models/beam_presets.dart` and their blob tables in `lib/src/look/`; every one is meant to read on both dark and light surfaces. + +Two presets pin the hue: `mono` and `gold` set `BeamHueMode.none` whatever the style says, because a hue sweep over greys or a single-hue metal reads as the material changing. `mono` is also painted with its layers at half strength (the line softens its spikes instead), since white light reads brighter than coloured light at the same opacity. + +`holographic` is the opposite bet — low-contrast pastels that come alive under a fast continuous drift: ```dart -BorderBeam.rotate( +BorderBeam( colors: BeamColors.holographic, style: const BeamStyle(hueMode: BeamHueMode.continuous), timing: const BeamTiming(huePeriod: Duration(seconds: 3)), @@ -37,75 +51,74 @@ BorderBeam.rotate( ); ``` -## Deriving from a brand color +## Your own colours + +```dart +// Evenly spaced clockwise from top-centre: 0, 1/3, 2/3. +const BeamColors([Colors.pink, Colors.cyan, Colors.amber]); + +// At chosen positions. +const BeamColors( + [Color(0xFF6B2BFF), Color(0xFFF02BD9), Color(0xFF33A1FF)], + stops: [0.1, 0.45, 0.8], +); + +// One colour all the way round. +const BeamColors.solid(Color(0xFF18A8F0)); +``` + +`BeamColors(colors, {stops})` takes 1–8 colours. `stops`, when given, has one entry per colour, ascending, each in `[0, 1)`; two equal neighbours make a hard edge. Alpha is honoured: a translucent stop glows more faintly. The lists are checked when the palette first resolves — in release builds too — and a malformed one throws an `ArgumentError`. + +Colours blend **gamma-aware**: squared channels (close to linear light) are interpolated and the square root taken, so the midpoint between two saturated colours stays bright instead of turning muddy. The blending runs on the CPU when a palette resolves, and the results are memoized, so a palette that stays the same is never blended again. One that changes every frame — a `BeamColors.lerp` on a running animation — is blended anew for each value. -`BeamColors.fromSeed` spreads one color into a palette using one of four harmonies: +## From a brand colour + +`BeamColors.fromSeed` spreads one colour into a palette with one of four harmonies, spaced evenly round the border: | `BeamSeedHarmony` | Hue offsets | Feel | | --- | --- | --- | -| `analogous` (default) | 0°, +25°, −25°, +50° | calmest; still reads as one color | -| `complementary` | 0°, +15°, +180°, +195° | maximum contrast across the beam | +| `analogous` (default) | 0°, +25°, −25°, +50° | calmest; still reads as one colour | +| `complementary` | 0°, +15°, +180°, +195° | maximum contrast between the two halves | | `triadic` | 0°, +120°, +240° | three-way, evenly spaced | -| `monochrome` | one hue, four lightness steps | single-hue brand look | +| `monochrome` | one hue, four lightness steps | a single-hue brand look | -Every derived color is lifted into a band a glow reads well in — lightness 0.55–0.70, saturation at least 0.55 — so a black, white, or gray seed still yields visible, distinguishable blobs rather than a smudge. That clamping is deliberate and is why `fromSeed` cannot reproduce a very dark or very desaturated brand color exactly; when you need the exact color, use `custom`. +The derived colours are lifted into a band a glow reads well in (lightness 0.55–0.70, with a saturation floor), so a black, white, or grey seed still yields a visible palette. That is also why `fromSeed` cannot reproduce a very dark or very desaturated brand colour exactly — use `BeamColors([...])` when you need the exact colour. ```dart -BorderBeam.rotate( - colors: const BeamColors.fromSeed( - Color(0xFF18A8F0), - harmony: BeamSeedHarmony.complementary, - ), - child: card, -); +const BeamColors.fromSeed(Color(0xFF18A8F0), harmony: BeamSeedHarmony.complementary); ``` -`BeamColors.fromScheme` is the Material shortcut over the same machinery: it takes `primary`, `secondary`, and `tertiary`, dropping any role that is within a small RGB distance of one already kept — so a scheme whose secondary matches its primary yields a two-color palette rather than a doubled one. +`BeamColors.fromScheme(colorScheme)` takes the scheme's `primary`, `secondary`, and `tertiary`, dropping any role that is nearly the same colour as one already kept — so a scheme whose secondary matches its primary gives two colours rather than a doubled one. It is not `const`. ## Transforming a palette -`lerp` and `scaleAlpha` produce new palettes from existing ones and are themselves values, so they can live in a `const` expression or be rebuilt per frame. - ```dart // Crossfade two palettes from an animation. -BorderBeam.rotate( +BorderBeam( colors: BeamColors.lerp(BeamColors.ocean, BeamColors.ember, animation.value), child: card, ); -// Dim without touching layer opacity. -BorderBeam.rotate(colors: BeamColors.neon.scaleAlpha(0.5), child: card); +// Dim the palette itself. +BorderBeam(colors: BeamColors.neon.scaleAlpha(0.5), child: card); ``` -`lerp` interpolates table-by-table, keeping `a`'s geometry and cycling `b`'s colors where its table is shorter. `t` is not clamped, so values outside 0–1 extrapolate. The mono modifiers come from whichever end is nearer, and the opacity multiplier is interpolated. +`BeamColors.lerp(a, b, t)` samples both palettes at eight evenly spaced positions and mixes each pair gamma-aware at `t`, which is clamped to 0–1. At exactly 0 or 1 it returns `a` or `b` unchanged. The result pins its hue when the nearer end does. -`scaleAlpha` dims the *palette* rather than the layer opacities, so the relative depth of the inner, stroke, and bloom tables survives. `style.strength` is the other lever: it scales the composited layers instead. Reach for `scaleAlpha` when a palette is too hot, and `strength` when the whole effect is. +`scaleAlpha(factor)` multiplies every stop's alpha, clamped to 0–1; `factor` must not be negative. It dims the palette rather than the beam, so stops that were already fainter stay relatively fainter. `BeamStyle.strength` is the other lever: it scales the whole beam's opacity. Reach for `scaleAlpha` when a palette is too hot and `strength` when the whole effect is. -## Per-blob control +## Hue drift -`BeamColors.spec` replaces the border table outright. Sizes are **radii**, not diameters — they map straight onto CSS `radial-gradient(ellipse W H …)`, whose sizes are radii too — and positions are fractions of the painted box, so values outside 0–1 legitimately sit on or beyond the edge. +On top of its stops, a palette can drift in hue over time (`BeamStyle.hueMode`): -```dart -const palette = BeamColors.spec( - border: [ - BeamBlob( - color: Color(0xFFFF4D8D), - position: Offset(0.33, -0.074), - size: Size(70, 40), - ), - BeamBlob( - color: Color(0xFF18A8F0), - position: Offset(0.72, 1.05), - size: Size(90, 50), - ), - ], -); -``` +- `pingPong` swings the hue ±`hueShift` degrees (30 by default) and back over one `huePeriod`; +- `continuous` turns it a full 360° per `huePeriod`; +- `none` paints the palette as given. -Tables you do not supply (`smallBorder`, `lineBlobs`) are derived by cycling your border colors over the default geometry, so a `spec` palette still works on every variant. +`hueBase` adds a fixed rotation in degrees on top, which is the quickest way to nudge a preset toward a brand colour. Each effect picks its own default mode and period — see [effects](effects.md#defaults). The rotation is folded into each blob's colour on the CPU every frame, so drifting costs nothing on the GPU. ## Values, equality, and the memo -Every `BeamColors` is a value type: two instances built from equal inputs are `==`. Resolution to concrete tables is memoized by that value through a bounded LRU (32 entries), so building a palette inline in `build` is free after the first frame, and an evicted palette is simply rebuilt and compares equal to the one it replaced. The four upstream presets bypass the LRU entirely — they are canonical const instances, memoized by identity for the life of the isolate. +Every `BeamColors` is a value type: two instances built from equal inputs are `==`. Resolution to a concrete `BeamPalette` is memoized by value through a bounded LRU (32 entries), so building `BeamColors([...])` inline in `build` is free after the first frame, and an evicted palette is rebuilt and compares equal to the one it replaced. Presets skip the memo entirely: each is a canonical constant. -The practical consequence: **never** put a palette behind a factory that returns a fresh non-equal object each build (a `Color` list built with `List.generate` is fine — it compares by element; a closure is not). If a beam re-resolves its config every frame, an unequal palette is the first thing to check. +The practical consequence: do not hand the beam a palette that compares unequal on every build. A beam whose palette changes re-resolves its config and rebuilds its phase resolver, every frame if the palette changes every frame. diff --git a/doc/parity.md b/doc/parity.md deleted file mode 100644 index a043e13..0000000 --- a/doc/parity.md +++ /dev/null @@ -1,124 +0,0 @@ -# Parity with the original - -This package is a port, not an interpretation. The visual constants come from the source, and the deviations are deliberate, few, and listed here. - -Tracked upstream: **[border-beam](https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam) 1.4.0**, MIT, by [Jakub Antalik](https://x.com/jakubantalik). That npm release is visually identical to 1.3.0, and its machine-readable spec still declares `1.3.0` as the visual baseline — which is the number `upstreamLibraryVersion` records, because it is the one the tables are audited against. - -## Where the constants come from - -Everything in `lib/src/constants/` is a **verbatim transcription** of the tables in the source's `src/styles.ts`: - -| File | Upstream content | -| --- | --- | -| `palettes.dart` | the four preset blob tables (`colorful`, `mono`, `ocean`, `sunset`) | -| `theme_presets.dart` | `sizeThemePresets` — layer opacities, inset shadows, filter multipliers per variant × brightness | -| `pulse_params.dart` | `pulseParams` — breathing parameters per variant, theme, and cycle length | -| `pulse_tables.dart` | the pulse blob tables and their oscillator/quadrant assignments | -| `pulse_constants.dart` | the pulse engine's fixed scalars | -| `line_keyframes.dart` | the line variant's keyframe tracks | -| `line_geometry.dart` | the line variant's blob geometry | -| `rotate_stops.dart` | the rotate/small gradient stops | - -`extra_palettes.dart` is the one file in that directory that is **not** a transcription: it holds the seven Flutter-only presets, defined as short color lists distributed over `colorful`'s geometry. Editing it changes how those presets look and has no bearing on parity. - -`upstream.dart` records the provenance of the whole directory — `upstreamLibraryVersion`, `upstreamSpecVersion`, and `upstreamRepository`. It is internal (the barrel does not export it) and is the single place those strings live, so the parity test reads them rather than restating them. - -**Never tweak a value in `lib/src/constants/`.** Visual parity depends on them, and a value that looks wrong is far more likely to be a transcription that is right for a reason. Verify against the source before changing anything: - -```console -git clone https://github.com/Jakubantalik/Libraries /tmp/border-beam-upstream -``` - -## How the transcription is verified - -Transcription is exactly the kind of work a human does badly and a test does well, so it is not left to review. - -The upstream library ships a machine-readable `spec/beam-spec.json` generated from its `src/styles.ts`. That file is vendored, byte for byte, at `test/fixtures/beam-spec.json`, with its provenance (commit, versions, and a SHA-256 of the `src/styles.ts` it was generated from) alongside it in `test/fixtures/UPSTREAM`. `test/constants/spec_parity_test.dart` reads the fixture and asserts every table in `lib/src/constants/` against it, entry by entry — handling the conventions that differ between the two worlds along the way: CSS `rgb()`/`rgba()` colors, `"33% -7.4%"` positions as fractional offsets, `"70px 40px"` sizes as **radii**, and percent stops against fractional ones. - -Refreshing the fixture is one command: - -```console -tool/spec/refresh.sh # from upstream main -tool/spec/refresh.sh # from a specific ref -``` - -It is idempotent, so re-running against an unchanged upstream leaves the tree untouched. Afterwards, re-read `upstream.dart` — its version strings are hand-maintained — and run `flutter test test/constants/spec_parity_test.dart`. - -`.github/workflows/upstream_drift.yaml` watches the hash: a change to upstream's `src/styles.ts` that never reached the spec generator still raises the alarm. - -A drifted constant therefore fails a unit test rather than a golden, which means it *names* the value instead of showing a diff of blurry pixels. And when the test does fail, the fix is to re-audit against `src/styles.ts` and report the divergence — **never** to change a constant until the test passes. - -The goldens are the second layer. `test/golden/` freezes the fake clock at a known time and captures every variant × theme × palette, with the traveling variants captured a second time further along their sweep. They catch changes in how the values are *used*, where the constant test catches changes in the values themselves. - - -## Deliberate deviations - -### Fade envelope: a spring, not CSS `ease` - -Activation and deactivation fade over 0.6s and 0.5s. The original eases them with CSS `ease`; this package eases them with a spring (mass 1, stiffness 180, damping 20), which settles more naturally under interruption — a beam toggled off mid-fade-in carries its velocity instead of restarting a curve. - -For an exact match, `BeamPlayback.cssEase` is `cubic-bezier(0.25, 0.1, 0.25, 1)`: - -```dart -BorderBeam.rotate( - playback: const BeamPlayback(fadeCurve: BeamPlayback.cssEase), - child: card, -); -``` - -`fadeCurve` accepts any `Curve`, so the envelope is fully yours. - -### Reduced motion: all five variants - -The original applies reduced motion to the pulse variants only, and its web build hides them; the iOS and React Native ports do the same. This package applies it to all five and defaults to a **static frame** rather than hiding — a beam that vanishes takes its meaning with it, while a still frame keeps marking the state. `BeamReducedMotion.hide` restores the upstream web behavior. See [accessibility](accessibility.md). - -### pulse-outside defaults - -The original's demo page applies its own tuning on top of the library's pulse-outside defaults — insets and blurs scaled by the element's size, melting the separate blobs into one continuous edge-hugging glow, plus a prominence boost and a glow multiplier. That tuned look is what people recognize as "the pulse-outside effect", so it is what `BorderBeam.pulseOutside` ships. - -`BeamStyle.pulseOutsideStock` rolls all of it back — the boost and multiplier through the hooks that carry them (`glowBoost`, the three opacity factors, `glowBrightness`/`glowSaturation`) and the geometry through `pulseOutsideTuning` — leaving the library's own defaults: a tighter, dimmer halo sitting closer to the child. - -```dart -BorderBeam.pulseOutside(style: BeamStyle.pulseOutsideStock, child: card); -``` - -Layer your own fields over it with `copyWith` or `merge`; anything you set wins. `BeamPulseOutsideTuning` on its own switches only the glow geometry (`demo`, the default, or `stock`). - -Both sets are the source's numbers; they differ only in which is the default. - -### `BeamTheme.auto` follows the app, not the OS - -Upstream, `auto` follows the OS color scheme. Here it follows `Theme.of(context).brightness`, because in Flutter the app's own theme is what a widget actually sits on: a card in a dark sheet inside a light app should get the dark tuning, and asking the OS would get it wrong. `BeamTheme.dark` and `BeamTheme.light` pin it explicitly. - -### No child-radius auto-detection - -The original reads its child's radius. This package asks you to pass it, because it also wraps widgets with no decoration to read — a `Text`, a `Row`, a third-party card — and a wrong guess is worse than a required argument. See [shape](shape.md#match-the-child-yourself). - -## Flutter-only additions - -None of these exist upstream: - -**Color** — `hueBase`; `BeamColors.custom`, `fromSeed` (four harmonies), `fromScheme`, `lerp`, `scaleAlpha`, `spec`; and the seven extra presets (`aurora`, `neon`, `candy`, `ember`, `ice`, `gold`, `holographic`). - -**Shape** — per-corner direction-aware radii, `BeamShape.stadium`, superellipse corners, `ringOffset`, `edge`, arbitrary `BeamContour` paths, `BeamShape.segment`, and `BeamShape.wrapCorners`. - -**Motion** — `cycleGap`, `direction`, `phaseOffset`, `beamCount`, `segments`, `tailLength`, `glowSpread`, `comet`, `sparkle`, `renderScale`, `innerSizeScale`, driven `progress`, pointer `follow`, `strengthListenable`, `speedListenable`, and `BeamSync`. - -**Playback & API** — the value-object API itself, `BorderBeamTheme`, `BorderBeamController` (including `pulse()` and `flash()`), `BeamRepeat`, `pauseWhenOffscreen`, `debugFrozenAt`, `fadeCurve`, and `pulseOutsideTuning` as a selectable field. - -**Surfaces** — `BorderBeam.overlay`, `BeamDecoration`, `BeamFocusRing`, `BeamHover`, `BeamPress`. - -The React original has no segment API. `BeamSegment` is a Flutter extension that masks the unchanged full-contour animation in perimeter space. The original author's SwiftUI showcase composes the half-phone look with a screen-space gradient mask over a full beam; this package expresses that composition as `shape.segment` and keeps it correct for arbitrary sizes, radii, offsets, and contours. - -## CSS ↔ Flutter mapping - -Four conventions account for most of the translation, and getting one wrong produces a subtly-off effect rather than an obvious break: - -| CSS | Flutter | -| --- | --- | -| `conic-gradient` starts at 12 o'clock | `SweepGradient` starts at 3 o'clock — the −90° rotation is baked in | -| `radial-gradient(ellipse W H …)` sizes are **radii** | passed straight through as `radiusX` / `radiusY` | -| `filter: blur(Npx)` | `MaskFilter.blur` with **sigma = N** | -| a gradient fading out | `color.withValues(alpha: 0)`, never `Color(0x00000000)` — transparent black lerps through black | - -Layer opacity is a multiplied chain — fade × preset × mono × hook × strength — clamped at paint time, which is why presets may legitimately exceed 1 (line/dark's stroke is 1.14 in the source). diff --git a/doc/performance.md b/doc/performance.md index 7e4dfa1..ac60926 100644 --- a/doc/performance.md +++ b/doc/performance.md @@ -1,74 +1,88 @@ # Performance -A beam is an animated blur — the most expensive thing a phone GPU does per pixel. The engine is built around keeping that cost fixed and small, and around never paying it for a beam nobody can see. +A beam is meant to be something you can leave running on a card while the user scrolls, at the display's full rate, without the phone warming up. The renderer is built around one rule: **one shader, one draw, no offscreen work.** -## What the engine does for you +## What a frame costs -**One ticker per beam.** Not per layer, not per track. Every animated value is recomputed from one elapsed-seconds number each frame, so there is no per-track state to advance and no controller graph to walk. Under a [`BeamSync`](motion.md#beamsync) the whole subtree shares a single ticker. +**One draw call.** Every frame of every effect is a single `drawRect` or `drawDRRect` whose paint carries the beam's fragment shader. There is no `saveLayer` (no offscreen render target to allocate, fill, and composite back), no clip, and no `ImageFilter` or `MaskFilter` (no blur pass). The design is built from layers — an inner glow, a hairline stroke, a bloom — and several of them are blurred in the reference look; here the shader evaluates every layer per pixel and replaces each blur with its closed form: a blurred hairline is a gaussian across the distance to the ring, a blurred colour blob is a gaussian blob with the same energy, a blurred glow outside the box is a smooth step across its edge. -**A ~30fps cap on the pulse variants**, matching the original's pulse driver. Time still accumulates at full resolution — only notifications are throttled — so the animation is not slowed, just sampled less often. A `pulse()` or `flash()` boost lifts the cap while it plays, because a brightness accent at 30fps reads as a step. +`test/render/frame_budget_test.dart` asserts this for every effect, on both surface tunings, across a palette subset, every shape family (rounded, per-corner, superellipse, stadium, segment, dashes, inward and outward ring offset, a thick border), the effect options, driven progress, and several instants: exactly one draw with the beam shader, zero `saveLayer`s, zero clips, no image or mask filter, and balanced saves and restores. A frame the fade or a cycle gap has blacked out draws nothing at all. -**`RepaintBoundary` isolation, twice.** The beam sits in its own boundary, and the child sits in another one inside it. The consequence is the one that matters: **your child never re-rasterizes** when the beam animates, however complex the child is. +**Pixels only where light can land.** The draw covers the box grown by the furthest outward glow, minus the interior beyond the furthest inward one — a ring, not the whole box. The inner glows fade out a short way in, so a card's beam shades a band around its edge; the line's bloom rises through the box, and a comet reaches outside it. -**Color matrices folded on the CPU.** Hue, brightness, and saturation are baked into the gradient colors before painting rather than carried on a `ColorFilter`. A filter needs a layer to ride on; folding it costs a few multiplications per frame instead. +**Cheap pixels.** Per pixel the shader computes the distance to the outline once, reads its four conic tables (an unused one stops at a single comparison), and then, layer by layer, skips everything a mask has already zeroed: the 1px stroke evaluates its blobs only on the ring itself, a windowed layer only inside its window. A layer holds at most 14 blobs (most hold 7–10), each a handful of multiply-adds and one square root or exponential. -**An offscreen pause.** With `playback.pauseWhenOffscreen` (the default), a beam watches its nearest enclosing `Scrollable` and stops its clock once it is more than 256px outside the viewport, resuming exactly where it left off — play state, fade, and callbacks untouched. A long list of beamed cards therefore costs the beams you can see, not the beams you have. With no enclosing `Scrollable` it does nothing. +**Little CPU per frame.** Per frame the beam samples its phases from one elapsed-seconds number, samples the effect's keyframes or oscillators, writes a few dozen blobs and a fixed block of 672 uniform floats into a buffer it reuses, folds each layer's colour filter into its colours, and uploads the floats to a `FragmentShader` it keeps for its lifetime. There is no path building, no gradient construction, and no per-frame buffer allocation; a palette's blob tables are resolved once and remembered, and the outline's Dart mirror is cached until the box or radius changes. -## The saveLayer budget +**Every effect costs about the same.** They share the shader and the single draw; what differs is how many pixels the draw covers — `line` covers its whole box, since its bloom rises through it, and `rotate(comet: true)` reaches furthest outside. -`saveLayer` is the expensive call: it allocates an offscreen surface, paints into it, and composites it back. The per-frame count — `paintBehind` plus `paintAbove` — is fixed per variant and **measured**, not estimated: +## 120Hz -| Variant | `saveLayer`s per frame | -| --- | --- | -| `rotate` | 4 | -| `small` | 3 | -| `line` | 4 | -| `pulseInside` | 4 | -| `pulseOutside` | 3 | +The beam's clock ticks on every frame the engine produces; there is no frame-rate cap on any effect. On a 120Hz display the beam animates at 120Hz. -Each entry is a layer the variant genuinely composites: the inner glow, the stroke, the bloom, the mask sub-layer where two masks intersect (`rotate`, `line`, `pulseInside`), and pulse-outside's two behind-child glows. +On ProMotion iPhones, iOS holds an app to 60Hz unless the app opts in. Add this to your app's `ios/Runner/Info.plist`: -A segment adds two `dstIn` gradient draws per painted layer and zero `saveLayer`s; the budget test includes segment rows to pin that invariant. - -`test/painting/save_layer_budget_test.dart` measures the count through a counting canvas for every variant × brightness × palette × time sample and asserts it **exactly**, along with save/restore balance. A regression and an improvement both fail the suite until the table is updated in both the test and this document — which is the point: the number is a contract, not a high-water mark. +```xml +CADisableMinimumFrameDurationOnPhone + +``` -The rule the engine follows: never add a `saveLayer` to carry a `ColorFilter`. A filter rides on a layer that exists anyway, and blur is the only filter allowed to justify a layer of its own. +The example app sets it. iPads with ProMotion need no key. -## Measuring your own scene +## Loading the shader -**Count the layers a widget paints.** The same technique the budget test uses works on any widget: +The shader is a package asset, compiled by the Flutter tool and loaded once per process with `FragmentProgram.fromAsset`. A beam starts the load itself and paints nothing until it resolves — a few milliseconds that the fade-in hides. To have the very first frame ready, load it at startup: ```dart -import 'dart:ui' as ui; - -final recorder = ui.PictureRecorder(); -final canvas = Canvas(recorder); -// Paint your beam's painter into `canvas`, then inspect the recorded picture. +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await BorderBeam.precache(); + runApp(const App()); +} ``` -For a scene rather than a painter, the simplest reliable count is DevTools: open the **Performance** view, enable **Track widget builds**, and use the *Raster* timeline — `saveLayer` calls show up as separate raster work in the frame's layer tree. +In widget tests that read pixels, `await BorderBeam.precache()` in `setUpAll`. -**Check the raster thread, not the UI thread.** A beam does almost nothing on the UI thread; its cost is entirely raster. A frame budget blown by beams shows up as a tall raster bar with a short UI bar. +## What the widget does for you -**Toggle the two DevTools flags that matter here:** +**One ticker per beam** — or exactly one per `BeamSync`, however many beams are in the group. -- *Highlight repaints* — every beam should show its own boundary changing color while the child inside it does not. If the child flashes too, something above the beam is invalidating it. -- *Render Surface Layers* (`debugRepaintRainbowEnabled` / the raster overlay) — confirms the beam is compositing on its own surface rather than forcing the page to. +**`RepaintBoundary` isolation, twice.** The beam sits in its own repaint boundary and the child in another inside it, so **your child never re-rasterizes** when the beam animates, however complex it is. -**Profile in profile mode, on a device.** Blur cost in debug mode on a simulator tells you nothing. +**An offscreen pause.** With `playback.pauseWhenOffscreen` (the default), a beam watches its nearest enclosing `Scrollable` and stops its clock once it is more than 256px outside the viewport, resuming exactly where it left off — play state, fade, and callbacks untouched. A long list of beamed cards costs the beams you can see. With no enclosing `Scrollable` it does nothing. -## Getting a scene cheaper +**Repaints without rebuilds.** The clock, `strengthListenable`, and `speedListenable` drive the painter directly; none of them rebuilds a widget per frame. `progress` is a plain value, so a new one arrives with a rebuild of the beam, but it reaches the painter through a listenable and repaints without re-resolving the configuration. + +## Impeller: keep the beam off offscreen ancestors + +The beam itself never asks for an offscreen pass, but an ancestor can force one around it, and then the beam's pixels are rendered into a texture and composited back every frame. Keep a beam out from under: + +- **`Opacity`, `AnimatedOpacity`, and `FadeTransition`** with a value strictly between 0 and 1; +- **`ShaderMask`**; +- **`BackdropFilter`**; +- **`ColorFiltered`** and **`ImageFiltered`**; +- a clip with `Clip.antiAliasWithSaveLayer`. -In rough order of how much they buy: +To fade a beam, use `style.strength` (static), `strengthListenable` (per frame, no rebuild), or `active` (the beam's own fade) instead of wrapping it in `Opacity`. To dim only the colours, use `BeamColors.scaleAlpha`. + +## Measuring your own scene + +**Check the raster thread.** A beam does very little on the UI thread; its cost is a single draw on the raster thread. In DevTools' Performance view, a frame budget blown by beams shows up as a tall raster bar with a short UI bar. + +**Look for offscreen passes above the beam.** If raster time is high, check the layer tree for an `OpacityLayer`, `ShaderMaskLayer`, `BackdropFilterLayer`, or `ColorFilterLayer` above the beam — that is the ancestor problem above, not the beam. + +**Use the repaint overlay.** With *Highlight repaints* on, each beam's boundary should change colour every frame while the child inside it does not. If the child flashes too, something above the beam is invalidating it. + +**Profile in profile mode, on a device.** Debug builds and simulators tell you little about GPU cost. + +## Getting a scene cheaper -1. **Use fewer beams.** A beam is emphasis; a screen where everything is emphasized has none. One hero beam almost always looks better than six. -2. **Put a group on a `BeamSync`.** Ten beams become one ticker and one timeline, and the group reads as deliberate rather than noisy. -3. **Prefer `small` and `pulseOutside`** where the design allows — they are the two three-layer variants. -4. **Drop `sparkle` and `comet`** on a scene that is already tight; both add geometry to the traveling head. -5. **Lower `renderScale`** on very large boxes. It paints the beam smaller and scales up, which cuts blur cost as well as making a card-sized palette read at screen size. -6. **Keep `pauseWhenOffscreen` on.** Turn it off only when a beam must stay phase-locked to something visible while it is itself out of view. -7. **Keep palettes value-equal.** A palette that compares unequal each build re-resolves the config and rebuilds the phase resolver every frame. See [palettes](palettes.md#values-equality-and-the-memo). +1. **Use fewer beams.** A beam is emphasis; a screen where everything is emphasized has none. One hero beam usually looks better than six. +2. **Put a group on a `BeamSync`.** Many beams become one ticker and one timeline, and the group reads as deliberate. +3. **Keep glows proportionate.** `style.glow` scales how far light reaches; a larger reach means more pixels shaded. `rotate(comet: true)` reaches furthest outward. +4. **Keep `pauseWhenOffscreen` on.** Turn it off only when a beam must stay in step with something visible while it is itself out of view. +5. **Keep palettes value-equal.** A palette that compares unequal on every build re-resolves the config each time. See [palettes](palettes.md#values-equality-and-the-memo). ## Web -The package compiles and runs on web — the [playground](https://simplifyjobs.github.io/flutter_border_beam/) is a web build of the example app, and CI builds it on every commit. Blur is the expensive part on every web renderer, so `line` and `pulseOutside` cost the most there. A single hero beam is a safe bet; a grid of them is not. +The package compiles and runs on web — the [live demo](https://simplifyjobs.github.io/flutter_border_beam/) is a web build of the example app, and CI builds it on every commit. The renderer is the same single shader draw there. diff --git a/doc/shape.md b/doc/shape.md index fc315ca..a823be8 100644 --- a/doc/shape.md +++ b/doc/shape.md @@ -1,6 +1,6 @@ # Shape -`BeamShape` describes the geometry the beam travels: corner radii, ring thickness, the corner family, how far the ring sits from the child, an optional partial segment or line corner wrap, and — when a rounded rectangle is not enough — an arbitrary path. The [README's shape table](../README.md#shape) lists the fields and defaults; this guide covers the parts with sharp edges. +`BeamShape` describes the outline the light follows: its corner radii and corner family, the stroke width, how far the outline sits from the child, which part of it is lit, and whether it is broken into dashes. Every field is nullable and means *inherit*; with nothing set, the outline is a 16px rounded rectangle on the child's bounds with a 1px stroke. ## Three constructors, one shape @@ -8,19 +8,19 @@ const BeamShape.all(24); // const — stores the number BeamShape.circular(24); // not const — builds a BorderRadius const BeamShape.stadium(); // a pill; a circle on a square box -const BeamShape(radius: someGeometry) // per-corner +const BeamShape(radius: someGeometry); // per-corner ``` -`BeamShape.all` and `BeamShape.circular` describe the same shape and **compare equal** for the same number. The split exists because building a `BorderRadius` from a parameter is a runtime construction, so `circular` cannot be `const`; `all` stores the double and grows it into a `BorderRadius` where `radius` is read. Use `all` in a `const` widget or a `const BorderBeamThemeData`, and `circular` when you already have a radius in `BorderRadius` terms. +`BeamShape.all` and `BeamShape.circular` describe the same shape and **compare equal** for the same number. The split exists because building a `BorderRadius` from a parameter is a runtime construction, so `circular` cannot be `const`; `all` stores the number and grows it into a `BorderRadius` where `radius` is read. Use `all` in a `const` widget or a `const BorderBeamThemeData`, and `circular` when you already think in `BorderRadius` terms. -`stadium` sets an infinite radius and lets the ring geometry clamp it per corner, which is what makes it track the box as it resizes — no rebuild needed when the chip's label changes length. +`stadium` sets an infinite radius and lets the outline clamp it per corner, which is what makes it track the box as it resizes — no rebuild when a chip's label changes length. ## Per-corner radii and direction `radius` is a `BorderRadiusGeometry`, so `BorderRadiusDirectional` works and resolves against the ambient `Directionality`: ```dart -BorderBeam.rotate( +BorderBeam( shape: const BeamShape( radius: BorderRadiusDirectional.only( topStart: Radius.circular(28), @@ -33,16 +33,16 @@ BorderBeam.rotate( In an RTL subtree the same shape mirrors, exactly as the child's own decoration does. -Radii are clamped the way `RRect.scaleRadii` clamps: when two radii on one side exceed that side's length, **all four** scale down by the smallest offending ratio — so an over-large radius shrinks the whole shape proportionally instead of deforming one corner. +Radii are clamped the way `RRect.scaleRadii` clamps: when two radii on one side add up to more than that side, **all four** scale down by the smallest offending ratio, so an over-large radius shrinks the whole shape proportionally instead of deforming one corner. An elliptical radius (`Radius.elliptical`) is drawn as a circular corner with the mean of its two axes. ## Match the child yourself -The beam does not read the child's decoration. That is deliberate: it wraps widgets that have no decoration to read (a `Text`, a `Row`, a third-party card), and guessing wrong is worse than asking. Pass the same number: +The beam does not read the child's decoration. It wraps widgets that have none to read (a `Text`, a `Row`, a third-party card), and guessing wrong is worse than asking. Pass the same number: ```dart const radius = 16.0; -BorderBeam.rotate( +BorderBeam( borderRadius: radius, child: Card( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(radius)), @@ -51,96 +51,50 @@ BorderBeam.rotate( ); ``` -A mismatch is the single most common visual complaint, and it always looks like the beam is "wrong" rather than the radius being out of sync. +A mismatch is the most common visual complaint, and it always looks like the beam is wrong rather than the radius being out of step. ## Superellipse corners -`superellipse: true` swaps circular corner arcs for a rounded superellipse — the Apple-style squircle, whose curvature is continuous where it meets the straight edge instead of stepping. It needs Flutter ≥ 3.35, the package's declared minimum, where `RSuperellipse` is stable. +`superellipse: true` swaps circular corner arcs for a superellipse — the Apple-style squircle, whose curvature eases into the straight edge instead of stepping. The curve follows Flutter's own `RSuperellipse` construction at every aspect ratio — cards, pills, and circles alike — so the stroke sits on the edge of a child shaped by `RoundedSuperellipseBorder` with the same radius. ```dart -BorderBeam.rotate( +BorderBeam( shape: const BeamShape.all(28, superellipse: true), - child: card, + child: DecoratedBox( + decoration: ShapeDecoration( + color: surface, + shape: RoundedSuperellipseBorder(borderRadius: BorderRadius.circular(28)), + ), + child: content, + ), ); ``` -It is a Flutter-only addition — the original's CSS `border-radius` produces circular arcs — so use it when your child is a squircle too, and leave it off when you want the source's exact contour. +The outline is computed in the shader, so the option costs no path building and no extra draw. + +## Border width + +`borderWidth` is the stroke's thickness in logical px, 1 by default. The stroke is drawn just inside the outline (from the outline inward by `borderWidth`), anti-aliased over one device pixel. It is independent of your child's border: on a hairline-bordered card, keeping both at 1 makes the beam read as the border lighting up rather than as a second ring. ## Ring offset -`ringOffset` moves the beam's ring outward (positive) or inward (negative) from the child's bounds: +`ringOffset` moves the outline outward (positive) or inward (negative) from the child's bounds: ```dart // The beam orbits 8px clear of the card. -BorderBeam.rotate( - shape: const BeamShape.all(24, ringOffset: 8), - child: card, -); +BorderBeam(shape: const BeamShape.all(32, ringOffset: 8), child: card); // Tucked inside a padded surface. -BorderBeam.rotate( - shape: const BeamShape.all(12, ringOffset: -12), - child: paddedSurface, -); -``` - -A positive offset paints further outside the widget's box, so it needs the same clip-free room `pulseOutside` does — add padding in the parent, and check for a `ClipRRect` above the beam. Corner radii are not adjusted for you; an offset ring around a rounded child usually wants its radius moved by the same amount to stay concentric. - -## Arbitrary contours - -When the shape is not a rounded rectangle at all, hand the beam a path. `BeamContour.build(Rect)` is called with the beam's bounds — already grown or shrunk by `ringOffset` — and returns a closed path in the same coordinate space. `radius` and `superellipse` are ignored while a contour is set. - -`BeamPathContour` is the ready-made implementation: - -```dart -BorderBeam.rotate( - shape: BeamShape( - contour: BeamPathContour((rect) => Path()..addOval(rect), key: 'oval'), - ), - child: card, -); -``` - -The `key` is not optional garnish. **A contour is a config-cache key**, so every implementer must override `==` and `hashCode`; a contour that compares by identity re-resolves the whole beam configuration on every rebuild. Dart closures compare by identity, so an inline builder would be a new value each time — the key is what makes two contours drawing the same path equal. Any value-equal object works: a string, an enum, or a record of the parameters the builder closes over. - -For a shape parameterized at runtime, put the parameters in the key: - -```dart -class NotchedContour extends BeamContour { - const NotchedContour(this.notch); - - final double notch; - - @override - Path build(Rect rect) { - return Path() - ..moveTo(rect.left, rect.top) - ..lineTo(rect.center.dx - notch, rect.top) - ..lineTo(rect.center.dx, rect.top + notch) - ..lineTo(rect.center.dx + notch, rect.top) - ..lineTo(rect.right, rect.top) - ..lineTo(rect.right, rect.bottom) - ..lineTo(rect.left, rect.bottom) - ..close(); - } - - @override - bool operator ==(Object other) => - identical(this, other) || - other is NotchedContour && other.notch == notch; - - @override - int get hashCode => notch.hashCode; -} +BorderBeam(shape: const BeamShape.all(12, ringOffset: -12), child: paddedSurface); ``` -The traveling variants walk the path's perimeter, so a contour with a very uneven perimeter distribution (a long thin spur, say) will pass through it quickly — that is arc-length behavior, not a bug. +A positive offset paints further outside the widget's box, so leave room for it. Corner radii are not adjusted for you: an offset outline around a rounded child usually wants its radius moved by the same amount to stay concentric (24 + 8 = 32 above). ## Segments -`BeamShape.segment` restricts visibility to part of the contour. It is a mask over the unchanged full-ring animation: the variant's constants, timing, and blob positions stay in full-contour space. The mask adds no compositing layers. +`BeamShape.segment` limits the light to part of the border. It is a mask over the unchanged animation: the effect still runs on the whole border, and the segment shows the part inside it. -Public perimeter positions are arc-length fractions measured clockwise from top-center: +Perimeter positions are arc-length fractions measured clockwise from top-centre: ```text 0 / 1 @@ -153,22 +107,19 @@ Public perimeter positions are arc-length fractions measured clockwise from top- 0.5 ``` -On a square, `0.25`, `0.5`, and `0.75` are approximately right-center, bottom-center, and left-center. Rounded corners change the exact fractions of edge landmarks because every coordinate is measured by path length, not by angle or box position. - -### Anchors and direction +On a square, `0.25`, `0.5`, and `0.75` are right-centre, bottom-centre, and left-centre. On other boxes, and with rounded corners, landmarks sit at other fractions, because every position is measured along the outline, not by angle. -Three anchor constructors cover raw and semantic positions: +### Anchors -- `BeamAnchor.fraction(t)` is an arc-length fraction; values resolve modulo one. -- `BeamAnchor.edge(edge, t)` follows the named straight run in clockwise travel: left-to-right on top, top-to-bottom on right, right-to-left on bottom, and bottom-to-top on left. `t` defaults to `0.5`. -- `BeamAnchor.corner(corner, t)` follows the named corner arc clockwise. `t` defaults to `0.5`; corners are named by `BeamCorner.topLeft`, `topRight`, `bottomRight`, and `bottomLeft`. +- `BeamAnchor.fraction(t)` — an arc-length fraction, taken modulo one. +- `BeamAnchor.edge(edge, t)` — `t` of the way along an edge's straight run, clockwise: left to right on top, top to bottom on the right, right to left on the bottom, bottom to top on the left. `t` defaults to 0.5. +- `BeamAnchor.corner(corner, t)` — `t` of the way through a corner curve, clockwise. `t` defaults to 0.5; corners are `BeamCorner.topLeft`, `topRight`, `bottomRight`, `bottomLeft`. +- `BeamAnchor.topCenter`, `rightCenter`, `bottomCenter`, `leftCenter` name the four common landmarks. -The static anchors `topCenter`, `rightCenter`, `bottomCenter`, and `leftCenter` name the four common landmarks. - -`BeamSegment(start: ..., end: ..., feather: 32)` covers the clockwise span from `start` to `end`. When the end fraction is smaller than the start fraction, the span wraps through the `0` / top-center origin. Swapping the endpoints selects the complementary span. `feather` is the distance in logical pixels along the perimeter over which each end fades; `0` produces a hard cut. +`BeamSegment(start: …, end: …, feather: 32)` covers the clockwise span from `start` to `end`, wrapping through top-centre when the end comes before the start. Swapping the two selects the rest of the border. `feather` is the distance in logical px along the border over which each end fades; `0` is a hard cut. A glow fades out toward the end of the track rather than stopping at a hard line across it. ```dart -BorderBeam.rotate( +BorderBeam( shape: const BeamShape( radius: BorderRadius.all(Radius.circular(24)), segment: BeamSegment.bottomHalf, @@ -181,44 +132,36 @@ BorderBeam.rotate( | Preset | Clockwise coverage | | --- | --- | -| `bottomHalf` | right-center → bottom-center → left-center | -| `topHalf` | left-center → top-center → right-center | -| `leftHalf` | bottom-center → left-center → top-center | -| `rightHalf` | top-center → right-center → bottom-center | -| `bottomEdge` | bottom-right arc + bottom straight run + bottom-left arc | -| `topEdge` | top-left arc + top straight run + top-right arc | -| `leftEdge` | bottom-left arc + left straight run + top-left arc | -| `rightEdge` | top-right arc + right straight run + bottom-right arc | - -`bottomHalf` produces the half-phone composition: both bottom corners, the bottom edge, and the lower halves of both sides. +| `bottomHalf` | right-centre → bottom-centre → left-centre | +| `topHalf` | left-centre → top-centre → right-centre | +| `leftHalf` | bottom-centre → left-centre → top-centre | +| `rightHalf` | top-centre → right-centre → bottom-centre | +| `bottomEdge` | bottom-right corner + bottom straight run + bottom-left corner | +| `topEdge` | top-left corner + top straight run + top-right corner | +| `leftEdge` | bottom-left corner + left straight run + top-left corner | +| `rightEdge` | top-right corner + right straight run + bottom-right corner | -### Variant behavior +### How each effect reads a segment -- **`rotate` and `small`:** the conic window keeps its full sweep. In forward travel the beam appears at the segment start, moves clockwise to its end, and is invisible for the rest of the cycle. -- **`line`:** the streak travels the segment in border-path space. For `bottomHalf` it descends the right edge, rounds the bottom-right corner, crosses the bottom, rounds the bottom-left corner, and climbs the left edge to the endpoint, with the usual fade at both ends of travel. `BeamShape.edge` is ignored when a segment is set. -- **`pulseInside` and `pulseOutside`:** blobs outside the segment are hidden and blobs near an endpoint fade. `bottomHalf` therefore leaves only the lower blobs breathing. +- **`rotate`** travels the segment: in forward travel it appears at the start and moves clockwise to the end, then begins again. +- **`line`** rides the segment instead of its `edge`, in border space — `bottomEdge` carries the streak around both bottom corners; `bottomHalf` takes it down the right side, along the bottom, and up the left. +- **`pulse`** lights only the part of the border inside the segment, and its glows fade near its ends. -`BeamTiming.direction` changes travel direction without changing which clockwise span the segment selects. Stack a forward beam and a second beam with `direction: BeamDirection.reverse` for two counter-sweeping arcs. `beamCount` places multiple travelers on the same unchanged full-contour timeline, and the segment reveals each only while it crosses the selected span. Pulse variants ignore both travel settings. `cycleGap` adds the usual invisible rest to traveling variants. +`BeamTiming.direction` changes which way a traveller crosses the segment, not which span the segment selects. Stack a forward beam and a `reverse` one on the same segment for two arcs sweeping toward each other. `ringOffset` moves the outline before positions are measured, so a segment follows an offset ring. -`ringOffset` moves the path before its perimeter is measured, so the segment and its feather follow the offset ring. A custom `BeamContour` works too: top-center is the point on its path nearest the box's top-center, and fractions advance by measured path length. Semantic edge and corner anchors resolve against the corresponding regions of that measured perimeter. +## Dashes -## Corner wrap - -`BeamShape.wrapCorners` applies to `line` when no segment is set. The default line geometry runs along the selected `edge`; with `wrapCorners: true`, the streak is placed in border-path space and bends around the two corner arcs adjacent to that edge instead of continuing straight past them. +`dashes` breaks the border into that many evenly spaced dashes. 2 or more paints dashes; null, 0, and 1 keep the border solid. A dash's ends are crisp on the stroke and soften the further its glow reaches from it, the way a blur would. ```dart -BorderBeam.line( - shape: const BeamShape.all( - 24, - edge: BeamEdge.bottom, - wrapCorners: true, - ), - child: card, +BorderBeam( + shape: const BeamShape.all(16, dashes: 12), + child: badge, ); ``` -A segment already places the line in border-path space and defines its endpoints, so it takes precedence over both `edge` and `wrapCorners`. +Dashes combine with segments and with every effect. -## Border width +## Light outside the bounds -`borderWidth` is the stroke ring's thickness, 1px by default and in the source. It is independent of your child's border: the beam's ring is a painted glow, not a border you can lay out against. On a hairline-bordered card, keeping both at 1 makes the beam read as the border lighting up rather than as a second ring around it. +Most light stays on the border and inside it. Two things paint outside the child's box: `BeamEffect.rotate(comet: true)` and a positive `ringOffset`. Give those room — padding in the parent — and check for a `ClipRRect`, `ClipPath`, or a scroll view's clip above the beam. diff --git a/doc/theming.md b/doc/theming.md index e351875..42ea664 100644 --- a/doc/theming.md +++ b/doc/theming.md @@ -2,50 +2,31 @@ Two different things are called "theme" here, and keeping them apart is most of the work: -- **`BeamTheme`** (`dark` / `light` / `auto`) is how one beam adapts to the background it sits on. It selects a preset. -- **`BorderBeamTheme`** is an `InheritedWidget` supplying default field values to every beam below it. +- **`BeamTheme`** (`dark` / `light` / `auto`) is how one beam adapts to the surface it sits on. +- **`BorderBeamTheme`** is an `InheritedWidget` supplying defaults — including the effect — to every beam below it. -## Background adaptation — `BeamTheme` +## Surface adaptation — `BeamTheme` -Each variant has one tuned config per brightness: layer opacities, an inset shadow color, and default brightness/saturation multipliers. `style.theme` picks which: +Light reads differently on a dark surface and on a light one, so every effect is tuned twice, layer by layer — each layer's strength, the inset shadow, and the colour filter's brightness and saturation. On a dark surface the highlights (a rotating beam's head, the line's travelling spot, the pulse's corners) and, on `rotate` and `line`, the inset shadow along the edge are white, so the light glows (`pulse` has no inset shadow); on a light surface they turn to dark ink and the hairline is quieter, so the light reads as a tint rather than a smudge. `style.theme` picks which tuning a beam uses: ```dart -// Always the dark-background tuning, whatever the app theme says. -BorderBeam.rotate( +// The dark-surface tuning, whatever the app theme says. +BorderBeam( style: const BeamStyle(theme: BeamTheme.dark), child: card, ); ``` -`BeamTheme.auto` — the default — follows `Theme.of(context).brightness`. That is a deliberate deviation from the original, which follows the OS color scheme: in Flutter the app's own theme is the thing a widget sits on, and a card in a dark sheet inside a light app should get the dark tuning. Force `dark` or `light` when a surface's brightness differs from the ambient theme's. - -### Replacing a preset - -`BeamThemeConfig` is public, so the whole preset can be replaced through `style.themeConfig`. Start from a preset and move the one field you want: - -```dart -BorderBeam.rotate( - style: BeamStyle( - themeConfig: BeamThemeConfig.presetFor( - BeamVariant.rotate, - Brightness.dark, - ).copyWith(bloomOpacity: 0.4, innerShadow: const Color(0x00000000)), - ), - child: card, -); -``` - -Its fields are `strokeOpacity`, `innerOpacity`, `bloomOpacity`, `innerShadow`, `saturation`, `brightness`, and `hairlineOpacity` (pulse-outside's static 1px edge, preset to 0 so the child's own border provides it). Opacities may legitimately exceed 1 — the source overdrives line/dark's stroke to 1.14 — and the painted product is clamped. - -`style.brightness` and `style.saturation` still apply **on top of** a replaced config, so a `themeConfig` sets the baseline rather than the last word. +`BeamTheme.auto` — the default — follows `Theme.of(context).brightness`, read from [`material_ui`](https://pub.dev/packages/material_ui). Under an app still on `package:flutter/material.dart` there is no `material_ui` theme to read, so `auto` tunes for a light surface until the app migrates or sets the theme explicitly. Force `dark` or `light` when a surface's brightness differs from the app's: a dark card inside a light app wants `BeamTheme.dark`. ## Defaults for a subtree — `BorderBeamTheme` -`BorderBeamThemeData` has one slot per value object, and each slot's fields are nullable, so a theme fills in only what it names: +`BorderBeamThemeData` has a slot for the effect and one per value object. Each value object's fields are nullable, so a theme fills in only what it names: ```dart BorderBeamTheme( data: const BorderBeamThemeData( + effect: BeamEffect.pulse(), style: BeamStyle(colors: BeamColors.ocean, strength: 0.85), shape: BeamShape.all(20, superellipse: true), timing: BeamTiming(cycle: Duration(seconds: 3)), @@ -54,11 +35,11 @@ BorderBeamTheme( ); ``` -Every beam below now defaults to the ocean palette at 85% strength, a 20px squircle, and a 3s cycle — and each can still override any single field. +Every beam below now defaults to `pulse` in the ocean palette at 85% strength, on a 20px squircle with a 3s cycle — and each can still override any single field. A beam that sets `effect:` replaces the theme's effect whole; effects do not merge. ### Nesting and merge -`BorderBeamTheme.of` walks **every** enclosing scope, registers the context as a dependent of each, and merges them outside-in. An inner theme therefore overrides only the fields it sets, and a change to an *outer* theme rebuilds the beam just as an inner one does. +`BorderBeamTheme.of` walks **every** enclosing theme, registers the context as a dependent of each, and merges them outside-in. An inner theme therefore overrides only the fields it sets, and a change to an *outer* theme rebuilds the beam just as an inner one does. ```dart BorderBeamTheme( @@ -73,23 +54,23 @@ BorderBeamTheme( ); ``` -That is the point of the all-nullable value objects: `merge` is field-by-field, so themes compose instead of replacing each other wholesale. +That is the point of the all-nullable value objects: `merge` is field by field, so themes compose instead of replacing each other. ### Where a theme sits in the order ```text -flat shorthand > value object on the widget > BorderBeamTheme (inner→outer) > variant default +shorthand > value object on the widget > BorderBeamTheme (inner over outer) > effect default ``` -`colors`, `active`, and `borderRadius` on the widget are shorthands that fold into `style.colors`, `playback.active`, and `shape.radius` respectively, and win over the same field set in the object next to them. +`colors`, `active`, and `borderRadius` on the widget are shorthands that fold into `style.colors`, `playback.active`, and `shape.radius`, and win over the same field set in the object next to them. The effect follows the same order: the widget's `effect:`, then the nearest theme's, then `BeamEffect.rotate()`. ### Const-friendly by design -`BeamShape.all` exists so a `BorderBeamThemeData` can be `const` — `BeamShape.circular` builds a `BorderRadius` at runtime and cannot be. `const BorderBeamThemeData(shape: BeamShape.all(20))` therefore costs nothing per rebuild, and `updateShouldNotify` compares by value, so a rebuilt-but-equal theme notifies nobody. +`BeamShape.all` exists so a `BorderBeamThemeData` can be `const` — `BeamShape.circular` builds a `BorderRadius` at runtime and cannot be. Effects are `const` too. `const BorderBeamThemeData(shape: BeamShape.all(20))` costs nothing per rebuild, and `updateShouldNotify` compares by value, so a rebuilt-but-equal theme notifies nobody. -### Themeing playback +### Theming playback -The playback slot is a genuine default, not an override: putting `startAfter` or `duration` in a theme applies them to every beam below, including beams that also take a `BorderBeamController`. The controller asserts in that case — it owns playback exclusively — so keep scheduling out of app-wide themes and set `reducedMotion` there instead, which is the field that genuinely benefits from being set once: +The playback slot is a genuine default, not an override: putting `startAfter` or `duration` in a theme applies them to every beam below, including beams that take a `BorderBeamController`. The controller asserts in that case — it owns playback exclusively — so keep scheduling out of app-wide themes and set `reducedMotion` there instead, which is the field that genuinely benefits from being set once: ```dart BorderBeamTheme( @@ -102,14 +83,14 @@ BorderBeamTheme( ## `BeamDecoration` and themes -A `BoxPainter` has no `BuildContext`, so a `BeamDecoration` inherits nothing on its own. Pass the theme in explicitly: +A `BoxPainter` has no `BuildContext`, so a `BeamDecoration` inherits nothing by itself. Pass the brightness and the theme in: ```dart BeamDecoration( - variant: BeamVariant.rotate, + effect: const BeamEffect.rotate(), brightness: Theme.of(context).brightness, theme: BorderBeamTheme.of(context), ); ``` -Without `theme:` the decoration resolves against variant presets only. +`effect:` falls back to the passed theme's effect, then to `BeamEffect.rotate()`. Without `theme:` the decoration resolves against the effect's defaults only. diff --git a/doc/variants.md b/doc/variants.md deleted file mode 100644 index 15878b5..0000000 --- a/doc/variants.md +++ /dev/null @@ -1,104 +0,0 @@ -# Variants - -Five effects, two engines. The [README's variant table](../README.md#variants) lists the defaults; this guide is about which one to reach for and how each behaves. - -## The two families - -**Traveling** (`rotate`, `small`, `line`) sweeps a window around the beam's contour once per `cycle`. Everything about travel applies: `direction`, `cycleGap`, `beamCount`, `phaseOffset`, `progress`, `follow`, `segments`, `tailLength`. - -**Pulse** (`pulseInside`, `pulseOutside`) breathes. A bank of independent oscillators scales, drifts, and fades the palette's blobs so that neighbouring blobs never move in lockstep; there is no sweep, so the travel fields above do nothing. Their hue advances continuously rather than swinging, and their clock is capped at ~30fps. - -`BeamVariant.isPulse` answers the question in code, and is what the widget uses to pick an engine. - -## `rotate` — the default - -A beam travels the full border of the box. Tuned for cards, panels, and any surface big enough that a full lap reads as motion rather than a flicker. - -```dart -BorderBeam.rotate(borderRadius: 16, child: card); -``` - -It is the variant most affected by the traveling-only style fields — `comet` trails a soft halo outside the ring behind the head, and `sparkle` scatters twinkles at it: - -```dart -BorderBeam.rotate( - style: const BeamStyle(comet: true, sparkle: 0.5, tailLength: 1.3), - child: card, -); -``` - -## `small` — buttons and chips - -The same traveling engine at a compact scale, with a 32px default radius. Reach for it on anything the size of a button, an icon, or a chip, where `rotate`'s geometry would overwhelm the element. It is the cheapest variant on the [saveLayer budget](performance.md). - -```dart -BorderBeam.small(shape: const BeamShape.stadium(), child: chip); -``` - -## `line` — inputs - -A beam that rides one edge rather than lapping the box, with a bloom that spikes and breathes underneath it. Built for text fields and search bars, where a full border lap fights the caret for attention. - -```dart -BorderBeam.line(child: searchBar); -``` - -Three things are specific to it: - -- **Its hue range is capped at 13°**, however large a `hueRange` you set. That cap is in the original, and a wider swing on a single bright edge reads as a color bug rather than an animation. -- **It has a second hue track** for the bloom, on its own `bloomHuePeriod` (8s). -- **It has breathe and spike tracks**, whose periods are given as multiples of `cycle`: `breatheFactor` (1.3), `spikeFactor` (1.33), `spike2Factor` (1.7). They are deliberately incommensurate with the cycle, so the beam never repeats exactly. - -`BeamShape.edge` moves it to any side of the box: - -```dart -BorderBeam.line(shape: const BeamShape(edge: BeamEdge.top), child: banner); -``` - -The `mono` palette does **not** get the ×0.5 opacity treatment here; the line variant expresses mono as attenuated spikes inside the bloom instead. - -## `pulseInside` — a contained working state - -A breathing glow held inside the child's bounds. It is the safe pulse: nothing paints outside the box, so it drops into a list, a grid, or a clipped surface without any layout accommodation. Good for "this row is working", a pressed state (`BeamPress` defaults to it), or a subscribe button that wants attention without a sweep. - -```dart -BorderBeam.pulseInside(active: isWorking, child: card); -``` - -`innerSizeScale` sets how much of the surface the glow fills — below 1 it tightens toward the border, above 1 it reaches further in — and `glowBoost` sets how prominent it is. - -## `pulseOutside` — a halo - -The same breathing, blooming *behind and outside* the child. It is the most striking variant and the only one with requirements attached: - -> The child must be **opaque**, so only the outward spill shows. It should carry its **own 1px border**, which is the edge you see when the glow is at its dimmest. And it needs **clip-free room** — padding in the parent, no tight `ClipRRect` — because a halo with nowhere to bloom is invisible. - -```dart -Padding( - padding: const EdgeInsets.all(32), - child: BorderBeam.pulseOutside( - child: DecoratedBox( - decoration: BoxDecoration( - color: surface, - border: Border.all(color: hairline), - borderRadius: BorderRadius.circular(16), - ), - child: content, - ), - ), -); -``` - -It is the only variant that paints on the **behind** pass, which is why it is the only one that goes in a `Container`'s `decoration:` rather than `foregroundDecoration:` when used as a [`BeamDecoration`](../README.md#beamdecoration). - -Its four glow overrides — `coreBlur`, `bloomBlur`, `glowBrightness`, `glowSaturation` — port the original's consumer tuning hooks and apply to nothing else. This package's defaults bake the tuning the original's web demo applies; `BeamStyle.pulseOutsideStock` is the library's stock look. See [parity](parity.md). - -## Choosing at runtime - -The generic constructor takes a `BeamVariant`, so a variant that comes from state, a theme, or a settings screen needs no switch: - -```dart -BorderBeam(variant: variant, colors: BeamColors.aurora, child: card); -``` - -Swapping the variant on a live beam is supported: the widget rebuilds its clock and its strategy, and the old ticker is disposed. diff --git a/example/README.md b/example/README.md index 694b843..73474cc 100644 --- a/example/README.md +++ b/example/README.md @@ -1,120 +1,70 @@ # flutter_border_beam example -The gallery app for the [`flutter_border_beam`](../) package — a Flutter -recreation of the original [border-beam demo](https://beam.jakubantalik.com). +A one-screen showcase for the [`flutter_border_beam`](../) package: each of the +three effects on the kind of widget it is made for, big enough to see. ```bash flutter run # phone / desktop flutter run -d chrome ``` -## What's in it - -- **Rotate** and **Pulse** example tabs, wrapping mock chat inputs, task cards, - and search bars — the same surfaces the original demo uses. -- **Themed** — three variants under a single `BorderBeamTheme`. Each card sets - nothing but its variant, so colors, shape, and cycle all come from the theme. -- **Rest between sweeps** — a `cycleGap` beam that parks at the end of its - travel and fades away before the next sweep. -- **Partial contours** — the half-phone composition on rotate, line, and - pulse-inside, plus a full line bending through adjacent corners. -- **Palettes** — a card per preset: colorful, mono, ocean, sunset, aurora, neon, - candy, ember, ice, gold, holographic. -- **Surfaces** — the beam reached without the wrapper: a `BeamDecoration` in a - `Container`'s `foregroundDecoration`, a `BeamFocusRing` around a focusable - field, and `BeamHover` / `BeamPress` cards. -- **Motion** — one card each for `direction: reverse`, `direction: bounce`, - `beamCount: 3`, `segments: 8`, and the comet tail. -- **Driven progress** — a rotate ring whose sweep is parked by a looping - `AnimationController` value instead of the clock. -- **Sync** — four cards on one `BeamSync` clock, spaced by `phaseOffset`. -- **Playground** — every meaningful field of the API, live (below). -- A dark/light theme toggle. Styling comes from the demo's own design tokens - (`lib/src/demo_theme.dart`), not Material defaults. - -## Playground - -`lib/src/playground/` holds the state bag every control drives -(`playground_state.dart`), the shareable-link codec (`share_codec.dart`), the -snippet generator (`snippet.dart`), the control widgets (`controls.dart`), and -the section itself (`playground_section.dart`). - -An install line sits above it: `flutter pub add flutter_border_beam` with a -Copy chip, beside a chip that copies the repository link. - -Controls are grouped into collapsible sections: - -| Section | Controls | +`main()` awaits `BorderBeam.precache()` after +`WidgetsFlutterBinding.ensureInitialized()`, so the shader is loaded before the +first frame. + +## What it shows + +Swipe the stage, or tap the selector under it, to move between the effects: + +| Effect | Surface | | --- | --- | -| Variant & colors | variant; palette — the eleven presets plus three assembled modes: **Custom** (2–4 swatches over a base preset, fed to `BeamColors.custom`), **Seed** (one swatch + a `BeamSeedHarmony`, fed to `BeamColors.fromSeed`), and **Lerp** (two presets and a blend slider, fed to `BeamColors.lerp`); an alpha-scale slider over any of them (`BeamColors.scaleAlpha`) | -| Shape | stadium, per-corner, squircle, and star-contour toggles; a corner-radius slider (or four, in per-corner mode); border width; ring offset; segment presets or custom edge anchors with feathering; the travelled edge and corner wrap on a segment-free line | -| Timing | cycle, cycle gap, speed, hue period; direction, phase offset, and beam count on the traveling variants; breathe / spike / spike 2 on the line variant; a static-colors toggle | -| Style | strength, brightness, saturation, hue range, hue mode, hue base, the three layer-opacity factors, glow spread, render scale; tail length and the comet tail on rotate and small; sparkle on the traveling variants; ring segments off the line variant; `glowBoost` and inner size on the pulse variants; the stock recipe, core blur, bloom blur, glow brightness, and glow saturation on pulse-outside | -| Playback | active toggle; controller mode with start / pause / resume / stop / pulse / flash and its own speed; `startAfter` and `duration` outside controller mode; repeat (forever / once / 3 cycles); reduced motion, with a toggle that simulates it; offscreen pause; the fade curve (spring or `BeamPlayback.cssEase`) | -| Drive | `progress:` with a position slider, `follow:` fed by the pointer over the preview, and `strengthListenable:` fed by a sine wave | -| Theme | wraps the preview in a `BorderBeamTheme` carrying ocean colors and a squircle-20 shape, and swaps it for three `BeamSync` beams a third of a cycle apart | - -A few conventions worth knowing: - -- **The preview and the snippet come from the same rule.** Both emit only what - differs from the package default, so a fresh playground prints the one-liner, - and with the theme toggle on, a control left at its default inherits from the - `BorderBeamTheme` while anything you set wins. -- **`auto` means "let the package decide".** Fields whose default depends on the - variant or a theme preset (cycle, hue period, brightness, saturation, and the - pulse-outside glow overrides) carry an `auto` chip that clears the override. -- **Controller mode owns playback.** With a controller attached, `startAfter`, - `duration`, `active`, and `timing.speed` belong to it, so those controls are - disabled and drop out of the snippet. -- **Two previews.** When the window is wide enough the configuration renders on - a dark and a light backdrop at once. `BeamTheme.auto` reads the ambient - brightness, so neither preview sets `theme:` — the snippet stays faithful. -- **Per-variant controls.** A field only appears where it reaches the painter: - the travelled edge on the line variant, tail length and comet on rotate and - small, sparkle on the traveling variants, inner size on pulse-inside. The - snippet drops the same fields on the same variants. -- **Segments own line travel.** Selecting one hides the line edge and corner - wrap controls because `segment` defines the path-space endpoints. Custom - segments expose start/end edge anchors and a 0–120px feather. -- **What the snippet cannot write, it names.** A `BeamPathContour` takes a - builder, so the star contour prints as a commented placeholder; the pointer - and the strength signal print as the variables the surrounding widget would - hold (`follow: pointer`, `strengthListenable: level`). -- **Static frame is the reduced-motion default**, so that chip sets no field. - **Simulate reduced motion** is a preview concern — it wraps the preview in a - `MediaQuery` asking for reduced motion and changes nothing in the snippet. -- The **Copy** button beside the snippet puts it on the clipboard. - -### Share links - -The playground encodes itself into a compact `key=value&key=value` string -holding only the non-default fields, so the default configuration is the empty -string. On the web that string is written to the address bar, and reloading — -or opening someone's link — restores the configuration. **Copy share link** -copies the current URL on the web, and off the web a link into the published -example: +| `BeamEffect.rotate()` | an agent's task card | +| `BeamEffect.line()` | a chat composer, the streak on its bottom edge | +| `BeamEffect.pulse()` | an assistant's "thinking" card | + +- **Palettes** — the row of swatches is `BeamColors.presets`, all nineteen; + each swatch is drawn from the preset's own colour stops. +- **Fade** — tap the stage, or the play/pause button, to toggle `active` and + watch the beam fade out and back in. +- **Theme** — the sun/moon button flips the app between dark (the default) and + light. The beam's `BeamStyle.theme` follows, so it uses its light-surface + tuning on the light theme. +- Under the caption, the effect and palette on screen are written as code + (`BeamEffect.line() · BeamColors.ocean`). + +On wide windows the screen stays centred at phone-like width. Every card and +chip uses continuous (superellipse) corners, and each beam is given the same +corners, so the light sits exactly on the edge. + +For captures, three `--dart-define`s set the opening state: +```bash +flutter run --dart-define=START=pulse --dart-define=PALETTE=ocean --dart-define=THEME=light ``` -https://simplifyjobs.github.io/flutter_border_beam/#v=line&str=0.6 -``` -Unknown keys, malformed pairs, and out-of-range values are ignored on the way -in, so a truncated or hand-edited link still opens a usable playground. +## Layout + +| File | What it holds | +| --- | --- | +| `lib/main.dart` | `main()` and the app: theme state, `MaterialApp` | +| `lib/src/home.dart` | the screen: header, swipeable stage, caption, controls | +| `lib/src/surfaces.dart` | the three mock surfaces the beams wrap | +| `lib/src/controls.dart` | the effect selector, palette swatches, round toggles | +| `lib/src/tokens.dart` | dark and light colour tokens, as a `ThemeExtension` | ## Demo reels -Entry points other than `lib/main.dart` are recording reels driven by -`lib/demo_harness.dart`: a reel is a map of scene name → widget, and the -harness mounts each scene centered on the demo backdrop, printing the markers -the recorder keys off (`::START/END`, then `:DONE`). -`lib/showcase.dart` is the README reel; `lib/pulse_outside_demo.dart` is a -single long take of the pulse-outside halo. Record with the repo's -`tool/record_demo.sh`: +The other entry points are recording reels driven by `lib/demo_harness.dart`: +a reel is a map of scene name → widget, and the harness precaches the shader, +then mounts each scene centred on the dark backdrop, printing the markers the +recorder keys off (`::START/END`, then `:DONE`). +`lib/showcase.dart` is the README reel — the three effects, palettes, and a +squircle. Record it with the repo's `tool/record_demo.sh`: ```bash # from the package root, with a booted iOS simulator and ffmpeg installed tool/record_demo.sh --target lib/showcase.dart --prefix SHOWCASE --contact ``` -Output mp4s land in `.demos/` (gitignored), center-cropped at 60fps, with an +Output mp4s land in `.demos/` (gitignored), centre-cropped at 60fps, with an optional contact-sheet PNG for review. diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml index 0d29021..d48d334 100644 --- a/example/analysis_options.yaml +++ b/example/analysis_options.yaml @@ -7,6 +7,13 @@ # The following line activates a set of recommended lints for Flutter apps, # packages, and plugins designed to encourage good coding practices. +analyzer: + exclude: + - build/** + - android/** + - ios/** + - web/** + - macos/** include: package:flutter_lints/flutter.yaml linter: diff --git a/example/lib/demo_harness.dart b/example/lib/demo_harness.dart index 74b974e..cdd9a8d 100644 --- a/example/lib/demo_harness.dart +++ b/example/lib/demo_harness.dart @@ -1,5 +1,6 @@ -import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:material_ui/material_ui.dart'; /// A single named scene in a demo reel: the widget (usually a `BorderBeam` /// around a mock surface) that should be shown centered on the stage while @@ -21,15 +22,19 @@ typedef DemoScene = Widget Function(); /// clean), starts recording, hot-restarts to replay, and stops at the second /// `:DONE`. Keeping the marker contract here means new demos need /// zero recorder changes. -void runDemoReel({ +/// +/// The beam shader is loaded before the reel starts, so the first frame of +/// every scene is already lit. +Future runDemoReel({ required String prefix, required Map scenes, Duration hold = const Duration(seconds: 6), Color backdrop = const Color(0xFF070707), Duration settle = const Duration(seconds: 2), Duration gap = const Duration(milliseconds: 1800), -}) { +}) async { WidgetsFlutterBinding.ensureInitialized(); + await BorderBeam.precache(); SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light); runApp( diff --git a/example/lib/main.dart b/example/lib/main.dart index 788ebe7..166b8ea 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,1022 +1,45 @@ -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter/material.dart'; - -import 'src/demo_theme.dart'; -import 'src/mocks.dart'; -import 'src/playground.dart'; - -void main() => runApp(const BorderBeamDemoApp()); - -/// The flutter_border_beam gallery — a Flutter recreation of the original React -/// demo (https://beam.jakubantalik.com): hero, Rotate/Pulse example tabs, -/// and an interactive playground, styled with the demo's own tokens instead -/// of Material defaults. -class BorderBeamDemoApp extends StatefulWidget { - /// Const constructor. - const BorderBeamDemoApp({super.key}); - - @override - State createState() => _BorderBeamDemoAppState(); -} - -class _BorderBeamDemoAppState extends State { - bool _dark = true; - - @override - Widget build(BuildContext context) { - final tokens = _dark ? DemoTokens.dark : DemoTokens.light; - return DemoTheme( - tokens: tokens, - isDark: _dark, - toggle: () => setState(() => _dark = !_dark), - child: MaterialApp( - debugShowCheckedModeBanner: false, - theme: ThemeData( - brightness: _dark ? Brightness.dark : Brightness.light, - scaffoldBackgroundColor: tokens.bg, - ), - home: const _DemoPage(), - ), - ); - } -} - -class _DemoPage extends StatefulWidget { - const _DemoPage(); - - @override - State<_DemoPage> createState() => _DemoPageState(); -} - -class _DemoPageState extends State<_DemoPage> { - bool _pulseTab = false; - - @override - Widget build(BuildContext context) { - final theme = DemoTheme.of(context); - final t = theme.tokens; - return ColoredBox( - color: t.bg, - child: SafeArea( - child: ScrollConfiguration( - behavior: ScrollConfiguration.of( - context, - ).copyWith(scrollbars: false, overscroll: false), - child: SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 40), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _CenteredColumn( - maxWidth: 560, - children: [ - _Header(onToggleTheme: theme.toggle, isDark: theme.isDark), - const SizedBox(height: 36), - Center( - child: PillTabBar( - tabs: const ['Rotate', 'Pulse'], - index: _pulseTab ? 1 : 0, - onChanged: (i) => setState(() => _pulseTab = i == 1), - ), - ), - const SizedBox(height: 28), - AnimatedSwitcher( - duration: const Duration(milliseconds: 200), - child: _pulseTab - ? const _PulseExamples(key: ValueKey('pulse')) - : const _RotateExamples(key: ValueKey('rotate')), - ), - const SizedBox(height: 56), - const _SectionTitle('Themed'), - const _SectionCaption( - 'One BorderBeamTheme above all three — each card sets ' - 'only its variant and inherits ocean + squircle 20.', - ), - const SizedBox(height: 16), - const _ThemedExamples(), - const SizedBox(height: 40), - const _SectionTitle('Rest between sweeps'), - const _SectionCaption( - 'cycleGap parks the beam at the end of its travel and ' - 'fades it away before the next sweep starts.', - ), - const SizedBox(height: 16), - const _CycleGapExample(), - const SizedBox(height: 40), - const _SectionTitle('Partial contours'), - const _SectionCaption( - 'One segment across rotate, line, and pulse, plus a ' - 'full line that bends around its adjacent corners.', - ), - const SizedBox(height: 16), - const _PartialContourExamples(), - const SizedBox(height: 40), - const _SectionTitle('Palettes'), - const _SectionCaption( - 'The eleven presets, each on the same card. Custom, ' - 'seeded, and blended palettes live in the playground.', - ), - const SizedBox(height: 16), - const _PaletteExamples(), - const SizedBox(height: 40), - const _SectionTitle('Surfaces'), - const _SectionCaption( - 'The beam without the wrapper: a decoration in a ' - 'Container, and the focus, hover, and press wrappers ' - 'that light one on an interaction.', - ), - const SizedBox(height: 16), - const _SurfaceExamples(), - const SizedBox(height: 40), - const _SectionTitle('Motion'), - const _SectionCaption( - 'Direction, beam count, ring segments, and the comet ' - 'tail — one card each.', - ), - const SizedBox(height: 16), - const _MotionExamples(), - const SizedBox(height: 40), - const _SectionTitle('Driven progress'), - const _SectionCaption( - 'progress: parks the sweep where a value says, turning ' - 'the ring into a readout. The clock keeps running, so ' - 'the beam stays lit rather than frozen.', - ), - const SizedBox(height: 16), - const _ProgressExample(), - const SizedBox(height: 40), - const _SectionTitle('Sync'), - const _SectionCaption( - 'One clock for four beams: BeamSync spaces them with ' - 'phaseOffset instead of letting four tickers drift.', - ), - const SizedBox(height: 16), - const _SyncExamples(), - ], - ), - const SizedBox(height: 56), - const _CenteredColumn( - maxWidth: 1040, - children: [ - _SectionTitle('Playground'), - SizedBox(height: 16), - PlaygroundSection(), - ], - ), - const SizedBox(height: 56), - const _CenteredColumn( - maxWidth: 560, - children: [_Footer(), SizedBox(height: 24)], - ), - ], - ), - ), - ), - ), - ); - } -} - -class _Header extends StatelessWidget { - const _Header({required this.onToggleTheme, required this.isDark}); - - final VoidCallback onToggleTheme; - final bool isDark; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Column( - children: [ - Align( - alignment: Alignment.centerRight, - child: DemoIconButton( - icon: isDark ? Icons.light_mode_outlined : Icons.dark_mode_outlined, - onTap: onToggleTheme, - ), - ), - const SizedBox(height: 8), - Text( - 'Border beam', - textAlign: TextAlign.center, - style: TextStyle( - fontSize: 32, - fontWeight: FontWeight.w600, - letterSpacing: -0.5, - color: t.heading, - decoration: TextDecoration.none, - ), - ), - const SizedBox(height: 8), - Text( - 'Animated border beam widgets for Flutter', - textAlign: TextAlign.center, - style: TextStyle( - fontSize: 14, - color: t.subtitle, - decoration: TextDecoration.none, - ), - ), - ], - ); - } -} - -/// A page section held to [maxWidth] and centered — the gallery reads at -/// 560, the playground needs room for two previews beside its controls. -class _CenteredColumn extends StatelessWidget { - const _CenteredColumn({required this.maxWidth, required this.children}); - - final double maxWidth; - final List children; - - @override - Widget build(BuildContext context) => Center( - child: ConstrainedBox( - constraints: BoxConstraints(maxWidth: maxWidth), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: children, - ), - ), - ); -} - -class _SectionTitle extends StatelessWidget { - const _SectionTitle(this.text); - - final String text; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Text( - text, - style: TextStyle( - fontSize: 15, - fontWeight: FontWeight.w600, - color: t.heading, - decoration: TextDecoration.none, - ), - ); - } -} - -class _SectionCaption extends StatelessWidget { - const _SectionCaption(this.text); - - final String text; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Padding( - padding: const EdgeInsets.only(top: 6), - child: Text( - text, - style: TextStyle( - fontSize: 12, - height: 1.5, - color: t.muted, - decoration: TextDecoration.none, - ), - ), - ); - } -} - -/// A frame around each example, matching the demo's `.example-cell`. -class ExampleFrame extends StatelessWidget { - /// Creates a frame. - const ExampleFrame({ - super.key, - required this.child, - this.height = 220, - this.clip = true, - }); - - /// Framed content, centered. - final Widget child; - - /// Frame height. - final double height; - - /// Whether to clip (pulse-outside frames must NOT clip the halo). - final bool clip; - - @override - Widget build(BuildContext context) { - final theme = DemoTheme.of(context); - final t = theme.tokens; - return Container( - height: height, - decoration: BoxDecoration( - color: theme.isDark ? t.surface : const Color(0xFFF7F7F7), - borderRadius: BorderRadius.circular(24), - ), - clipBehavior: clip ? Clip.antiAlias : Clip.none, - child: Center(child: child), - ); - } -} - -class _RotateExamples extends StatelessWidget { - const _RotateExamples({super.key}); - - @override - Widget build(BuildContext context) { - final theme = DemoTheme.of(context); - final beamTheme = theme.isDark ? BeamTheme.dark : BeamTheme.light; - return Column( - children: [ - ExampleFrame( - child: BorderBeam.rotate( - style: BeamStyle(theme: beamTheme), - borderRadius: 20, - child: const MockChatInput(), - ), - ), - const SizedBox(height: 16), - Row( - children: [ - Expanded( - child: ExampleFrame( - height: 140, - child: BorderBeam.small( - style: BeamStyle(theme: beamTheme), - borderRadius: 20, - child: const MockIconButton(), - ), - ), - ), - const SizedBox(width: 16), - Expanded( - flex: 2, - child: ExampleFrame( - height: 140, - child: BorderBeam.line( - style: BeamStyle(theme: beamTheme), - borderRadius: 20, - child: const MockSearchBar(), - ), - ), - ), - ], - ), - ], - ); - } -} - -class _PulseExamples extends StatelessWidget { - const _PulseExamples({super.key}); - - @override - Widget build(BuildContext context) { - final theme = DemoTheme.of(context); - final beamTheme = theme.isDark ? BeamTheme.dark : BeamTheme.light; - return Column( - children: [ - ExampleFrame( - height: 300, - clip: false, - child: BorderBeam.pulseInside( - style: BeamStyle(theme: beamTheme), - borderRadius: 20, - child: const MockWorkingCard(), - ), - ), - const SizedBox(height: 16), - Row( - children: [ - Expanded( - child: ExampleFrame( - height: 160, - clip: false, - child: BorderBeam.pulseInside( - style: BeamStyle(theme: beamTheme), - borderRadius: 20, - child: const MockSubscribeButton(), - ), - ), - ), - const SizedBox(width: 16), - Expanded( - flex: 2, - child: ExampleFrame( - height: 220, - clip: false, - child: BorderBeam.pulseOutside( - style: BeamStyle(theme: beamTheme), - borderRadius: 20, - child: const MockChatInput(), - ), - ), - ), - ], - ), - ], - ); - } -} - -// Defaults handed to the Themed section's three cards. Not const: building a -// BorderRadius from a number is a runtime construction, so BeamShape.circular -// cannot be const either. -final BorderBeamThemeData _galleryThemeData = BorderBeamThemeData( - style: const BeamStyle(colors: BeamColors.ocean), - shape: BeamShape.circular(20, superellipse: true), - timing: const BeamTiming(cycle: Duration(milliseconds: 2600)), -); - -/// Three variants under one [BorderBeamTheme]: each beam sets nothing but -/// its own variant, so colors, shape, and cycle all come from the theme. -class _ThemedExamples extends StatelessWidget { - const _ThemedExamples(); - - @override - Widget build(BuildContext context) { - return BorderBeamTheme( - data: _galleryThemeData, - child: Row( - children: [ - for (final entry in const [ - (label: 'rotate', variant: BeamVariant.rotate), - (label: 'small', variant: BeamVariant.small), - (label: 'pulseInside', variant: BeamVariant.pulseInside), - ]) ...[ - if (entry.label != 'rotate') const SizedBox(width: 16), - Expanded( - child: ExampleFrame( - height: 150, - clip: false, - child: SizedBox( - height: 84, - child: BorderBeam( - variant: entry.variant, - child: _ThemedCard(label: entry.label), - ), - ), - ), - ), - ], - ], - ), - ); - } -} - -/// The surface the themed cards wrap — squircle 20, matching the theme's -/// shape, since a beam never reads its child's decoration. -class _ThemedCard extends StatelessWidget { - const _ThemedCard({required this.label, this.radius = 20}); - - final String label; - final double radius; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Container( - decoration: ShapeDecoration( - color: t.mockBg, - shape: RoundedSuperellipseBorder( - borderRadius: BorderRadius.circular(radius), - side: BorderSide(color: t.mockBorder), - ), - ), - alignment: Alignment.center, - child: Text( - label, - style: TextStyle( - fontSize: 12, - color: t.mockText, - fontFamily: 'Menlo', - fontFamilyFallback: const ['Courier New', 'monospace'], - decoration: TextDecoration.none, - ), - ), - ); - } -} - -/// A beam that rests between sweeps instead of running one straight into the -/// next. -class _CycleGapExample extends StatelessWidget { - const _CycleGapExample(); - - @override - Widget build(BuildContext context) { - final theme = DemoTheme.of(context); - return ExampleFrame( - child: BorderBeam.rotate( - style: BeamStyle( - theme: theme.isDark ? BeamTheme.dark : BeamTheme.light, - ), - borderRadius: 20, - timing: const BeamTiming(cycleGap: Duration(milliseconds: 900)), - child: const MockChatInput(), - ), - ); - } -} - -/// A half-phone segment across the three painting families, beside a -/// segment-free line using border-path corner wrapping. -class _PartialContourExamples extends StatelessWidget { - const _PartialContourExamples(); - - static const BeamShape _halfShape = BeamShape.all( - 36, - segment: BeamSegment.bottomHalf, - ); - - @override - Widget build(BuildContext context) => ExampleFrame( - height: 370, - clip: false, - child: Padding( - padding: const EdgeInsets.all(18), - child: Row( - children: [ - const SizedBox( - width: 180, - height: 320, - child: BorderBeam.rotate( - colors: BeamColors.aurora, - shape: _halfShape, - child: _ThemedCard(label: 'Half phone', radius: 36), - ), - ), - const SizedBox(width: 14), - Expanded( - child: Column( - children: [ - Expanded( - child: BorderBeam.line( - colors: BeamColors.ocean, - shape: _halfShape, - child: const _ThemedCard( - label: 'Half phone · line', - radius: 36, - ), - ), - ), - const SizedBox(height: 12), - Expanded( - child: BorderBeam.pulseInside( - colors: BeamColors.sunset, - shape: _halfShape, - child: const _ThemedCard( - label: 'Half phone · pulse', - radius: 36, - ), - ), - ), - const SizedBox(height: 12), - const Expanded( - child: BorderBeam.line( - colors: BeamColors.neon, - shape: BeamShape.all( - 28, - edge: BeamEdge.bottom, - wrapCorners: true, - ), - child: _ThemedCard(label: 'Corner wrap', radius: 28), - ), - ), - ], - ), - ), - ], - ), - ), - ); -} - -/// The eleven palette presets, one small card each. -class _PaletteExamples extends StatelessWidget { - const _PaletteExamples(); +import 'dart:ui' show PointerDeviceKind; - static const List<(String, BeamColors)> _presets = [ - ('colorful', BeamColors.colorful), - ('mono', BeamColors.mono), - ('ocean', BeamColors.ocean), - ('sunset', BeamColors.sunset), - ('aurora', BeamColors.aurora), - ('neon', BeamColors.neon), - ('candy', BeamColors.candy), - ('ember', BeamColors.ember), - ('ice', BeamColors.ice), - ('gold', BeamColors.gold), - ('holographic', BeamColors.holographic), - ]; - - @override - Widget build(BuildContext context) => LayoutBuilder( - builder: (context, constraints) { - // Three cards a row on the gallery column, two on a phone. - final columns = constraints.maxWidth >= 420 ? 3 : 2; - final width = (constraints.maxWidth - (columns - 1) * 12) / columns; - return Wrap( - spacing: 12, - runSpacing: 12, - children: [ - for (final (label, colors) in _presets) - SizedBox( - width: width, - height: 64, - child: BorderBeam.rotate( - colors: colors, - shape: const BeamShape.all(14, superellipse: true), - child: _ThemedCard(label: label, radius: 14), - ), - ), - ], - ); - }, - ); -} - -/// The beam reached through something other than the `BorderBeam` wrapper: -/// a decoration, and the three interaction wrappers. -class _SurfaceExamples extends StatelessWidget { - const _SurfaceExamples(); - - @override - Widget build(BuildContext context) { - final theme = DemoTheme.of(context); - final t = theme.tokens; - final brightness = theme.isDark ? Brightness.dark : Brightness.light; - return Column( - children: [ - Row( - children: [ - Expanded( - child: ExampleFrame( - height: 150, - child: Container( - width: 190, - height: 72, - foregroundDecoration: BeamDecoration( - variant: BeamVariant.rotate, - brightness: brightness, - colors: BeamColors.ocean, - borderRadius: 16, - ), - decoration: ShapeDecoration( - color: t.mockBg, - shape: RoundedSuperellipseBorder( - borderRadius: BorderRadius.circular(16), - side: BorderSide(color: t.mockBorder), - ), - ), - alignment: Alignment.center, - child: _CardLabel('BeamDecoration'), - ), - ), - ), - const SizedBox(width: 16), - Expanded( - child: ExampleFrame( - height: 150, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const BeamFocusRing( - borderRadius: 12, - alwaysShow: true, - child: MockFocusField(), - ), - const SizedBox(height: 10), - _CardLabel('BeamFocusRing'), - ], - ), - ), - ), - ], - ), - const SizedBox(height: 16), - Row( - children: [ - Expanded( - child: ExampleFrame( - height: 150, - child: BeamHover( - borderRadius: 16, - colors: BeamColors.aurora, - child: SizedBox( - width: 190, - height: 72, - child: _ThemedCard(label: 'BeamHover', radius: 16), - ), - ), - ), - ), - const SizedBox(width: 16), - Expanded( - child: ExampleFrame( - height: 150, - child: BeamPress( - borderRadius: 16, - colors: BeamColors.ember, - child: SizedBox( - width: 190, - height: 72, - child: _ThemedCard(label: 'BeamPress', radius: 16), - ), - ), - ), - ), - ], - ), - ], - ); - } -} +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:material_ui/material_ui.dart'; -/// Direction, multi-beam, segments, and comet, one card each. -class _MotionExamples extends StatelessWidget { - const _MotionExamples(); +import 'src/home.dart'; +import 'src/tokens.dart'; - @override - Widget build(BuildContext context) => LayoutBuilder( - builder: (context, constraints) { - final columns = constraints.maxWidth >= 420 ? 3 : 2; - final width = (constraints.maxWidth - (columns - 1) * 12) / columns; - Widget cell(String label, Widget beam) => - SizedBox(width: width, height: 72, child: beam); - return Wrap( - spacing: 12, - runSpacing: 12, - children: [ - cell( - 'reverse', - const BorderBeam.rotate( - colors: BeamColors.ocean, - shape: BeamShape.all(16, superellipse: true), - timing: BeamTiming(direction: BeamDirection.reverse), - child: _ThemedCard(label: 'reverse', radius: 16), - ), - ), - cell( - 'bounce', - const BorderBeam.rotate( - colors: BeamColors.sunset, - shape: BeamShape.all(16, superellipse: true), - timing: BeamTiming(direction: BeamDirection.bounce), - child: _ThemedCard(label: 'bounce', radius: 16), - ), - ), - cell( - 'beams 3', - const BorderBeam.rotate( - colors: BeamColors.neon, - shape: BeamShape.all(16, superellipse: true), - timing: BeamTiming(beamCount: 3), - child: _ThemedCard(label: 'beamCount 3', radius: 16), - ), - ), - cell( - 'segments 8', - const BorderBeam.rotate( - colors: BeamColors.ice, - shape: BeamShape.all(16, superellipse: true), - style: BeamStyle(segments: 8), - child: _ThemedCard(label: 'segments 8', radius: 16), - ), - ), - cell( - 'comet', - const BorderBeam.rotate( - colors: BeamColors.aurora, - shape: BeamShape.all(16, superellipse: true), - style: BeamStyle(comet: true, sparkle: 0.4), - child: _ThemedCard(label: 'comet', radius: 16), - ), - ), - ], - ); - }, - ); +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + // Load the beam shader before the first frame, so the first beam is lit. + await BorderBeam.precache(); + runApp(const ExampleApp()); } -/// A rotate ring parked by a value instead of the clock: the controller -/// loops 0→1, and the beam sits wherever it says. -class _ProgressExample extends StatefulWidget { - const _ProgressExample(); +/// The flutter_border_beam example: one screen showing each effect on the +/// surface it is made for. Dark by default. +class ExampleApp extends StatefulWidget { + /// Creates the app. + const ExampleApp({super.key}); @override - State<_ProgressExample> createState() => _ProgressExampleState(); + State createState() => _ExampleAppState(); } -class _ProgressExampleState extends State<_ProgressExample> - with SingleTickerProviderStateMixin { - late final AnimationController _controller = AnimationController( - vsync: this, - duration: const Duration(seconds: 6), - )..repeat(); +class _ExampleAppState extends State { + bool _dark = const String.fromEnvironment('THEME') != 'light'; @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) => ExampleFrame( - height: 170, - child: AnimatedBuilder( - animation: _controller, - builder: (context, _) => SizedBox( - width: 250, - height: 84, - child: BorderBeam.rotate( - colors: BeamColors.aurora, - shape: const BeamShape.all(16, superellipse: true), - progress: _controller.value, - child: _ThemedCard( - label: 'progress ${_controller.value.toStringAsFixed(2)}', - radius: 16, - ), - ), - ), + Widget build(BuildContext context) => MaterialApp( + title: 'Border Beam', + debugShowCheckedModeBanner: false, + theme: buildTheme(_dark ? Brightness.dark : Brightness.light), + themeAnimationCurve: Curves.easeOut, + // Let a mouse drag the stage and the palette row too, on web and desktop. + scrollBehavior: const MaterialScrollBehavior().copyWith( + dragDevices: PointerDeviceKind.values.toSet(), + scrollbars: false, ), - ); -} - -/// Four cards on one shared clock, a quarter of a cycle apart. -class _SyncExamples extends StatelessWidget { - const _SyncExamples(); - - static const int _count = 4; - - @override - Widget build(BuildContext context) => ExampleFrame( - height: 150, - child: BeamSync( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: Row( - children: [ - for (var i = 0; i < _count; i++) ...[ - if (i > 0) const SizedBox(width: 10), - Expanded( - child: SizedBox( - height: 76, - child: BorderBeam.rotate( - colors: BeamColors.ocean, - shape: const BeamShape.all(14, superellipse: true), - timing: BeamTiming(phaseOffset: i / _count), - child: _ThemedCard(label: '${i + 1}', radius: 14), - ), - ), - ), - ], - ], - ), - ), + home: Home( + dark: _dark, + onToggleTheme: () => setState(() => _dark = !_dark), ), ); } - -/// A caption under a surface example. -class _CardLabel extends StatelessWidget { - const _CardLabel(this.text); - - final String text; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Text( - text, - style: TextStyle( - fontSize: 12, - color: t.mockText, - fontFamily: 'Menlo', - fontFamilyFallback: const ['Courier New', 'monospace'], - decoration: TextDecoration.none, - ), - ); - } -} - -class _Footer extends StatelessWidget { - const _Footer(); - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - final muted = TextStyle( - fontSize: 13, - color: t.muted, - decoration: TextDecoration.none, - ); - return Column( - children: [ - Text( - 'Original border-beam by Jakub Antalik', - textAlign: TextAlign.center, - style: muted, - ), - const SizedBox(height: 4), - Text( - 'Flutter port · flutter_border_beam package', - textAlign: TextAlign.center, - style: muted.copyWith(color: t.muted.withValues(alpha: 0.5)), - ), - ], - ); - } -} - -/// The animated pill tab bar of the demo (`.tab-nav`). -class PillTabBar extends StatelessWidget { - /// Creates the tab bar. - const PillTabBar({ - super.key, - required this.tabs, - required this.index, - required this.onChanged, - }); - - /// Tab labels. - final List tabs; - - /// Selected index. - final int index; - - /// Selection callback. - final ValueChanged onChanged; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Container( - height: 36, - padding: const EdgeInsets.all(3), - decoration: BoxDecoration( - color: t.tabsBarBg, - borderRadius: BorderRadius.circular(18), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - for (final (i, label) in tabs.indexed) - GestureDetector( - onTap: () => onChanged(i), - child: AnimatedContainer( - duration: const Duration(milliseconds: 200), - curve: const Cubic(0.22, 1, 0.36, 1), - padding: const EdgeInsets.symmetric(horizontal: 18), - alignment: Alignment.center, - decoration: BoxDecoration( - color: i == index ? t.tabsPillBg : null, - borderRadius: BorderRadius.circular(15), - ), - child: Text( - label, - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w500, - color: i == index ? t.tabsTextActive : t.tabsTextMuted, - decoration: TextDecoration.none, - ), - ), - ), - ), - ], - ), - ); - } -} - -/// A minimal icon button matching the demo's `.icon-btn`. -class DemoIconButton extends StatelessWidget { - /// Creates the button. - const DemoIconButton({super.key, required this.icon, required this.onTap}); - - /// Glyph. - final IconData icon; - - /// Tap callback. - final VoidCallback onTap; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return GestureDetector( - onTap: onTap, - child: Container( - width: 32, - height: 32, - decoration: BoxDecoration( - color: t.btnBg, - borderRadius: BorderRadius.circular(16), - ), - child: Icon(icon, size: 16, color: t.btnText), - ), - ); - } -} diff --git a/example/lib/pulse_outside_demo.dart b/example/lib/pulse_outside_demo.dart deleted file mode 100644 index 49a86af..0000000 --- a/example/lib/pulse_outside_demo.dart +++ /dev/null @@ -1,44 +0,0 @@ -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter/material.dart'; - -import 'demo_harness.dart'; - -/// Focused reel for the pulse-outside effect. Record with: -/// -/// tool/record_demo.sh --target lib/pulse_outside_demo.dart \ -/// --prefix PULSEOUT --contact -void main() { - runDemoReel( - prefix: 'PULSEOUT', - hold: const Duration(seconds: 10), - scenes: { - 'pulse-outside': () => const SizedBox( - width: 350, - height: 140, - child: BorderBeam.pulseOutside(child: _Surface()), - ), - }, - ); -} - -class _Surface extends StatelessWidget { - const _Surface(); - - @override - Widget build(BuildContext context) => Container( - decoration: BoxDecoration( - color: const Color(0xFF1D1D1D), - borderRadius: BorderRadius.circular(16), - border: Border.all(color: const Color(0x852C2F36)), - ), - alignment: Alignment.center, - child: const Text( - 'Build anything...', - style: TextStyle( - fontSize: 13, - color: Color(0xFF4E4E4E), - decoration: TextDecoration.none, - ), - ), - ); -} diff --git a/example/lib/showcase.dart b/example/lib/showcase.dart index 5ee5a82..c9ed9d5 100644 --- a/example/lib/showcase.dart +++ b/example/lib/showcase.dart @@ -1,5 +1,5 @@ import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter/material.dart'; +import 'package:material_ui/material_ui.dart'; import 'demo_harness.dart'; @@ -7,69 +7,51 @@ import 'demo_harness.dart'; /// /// tool/record_demo.sh --target lib/showcase.dart --prefix SHOWCASE --contact /// -/// Each scene holds for ~2 full animation cycles on the dark demo backdrop. -void main() { - runDemoReel( - prefix: 'SHOWCASE', - hold: const Duration(seconds: 7), - scenes: { - 'rotate': () => _card(const BorderBeam.rotate(child: _Surface())), - 'small': () => BorderBeam.small( - borderRadius: 20, - child: Container( - width: 36, - height: 36, - decoration: _surfaceDecoration(20), - alignment: Alignment.center, - child: Container( - width: 12, - height: 12, - decoration: BoxDecoration( - color: const Color(0xCCD9D9D9), - borderRadius: BorderRadius.circular(2), - ), - ), - ), - ), - 'line': () => BorderBeam.line( - borderRadius: 21, - child: Container( - width: 366, - height: 42, - decoration: _surfaceDecoration(21), - padding: const EdgeInsets.symmetric(horizontal: 13), - child: const Row( - children: [ - Icon(Icons.search, size: 20, color: Color(0x66565656)), - SizedBox(width: 10), - Text( - 'Search', - style: TextStyle( - fontSize: 15, - color: Color(0xFF565656), - decoration: TextDecoration.none, - ), +/// Each scene holds for ~2 full animation cycles on the dark demo backdrop: +/// the three effects, then palettes and a squircle. +Future main() => runDemoReel( + prefix: 'SHOWCASE', + hold: const Duration(seconds: 7), + scenes: { + 'rotate': () => + _card(const BorderBeam(effect: BeamEffect.rotate(), child: _Surface())), + 'line': () => BorderBeam( + effect: const BeamEffect.line(), + borderRadius: 21, + child: Container( + width: 366, + height: 42, + decoration: _surfaceDecoration(21), + padding: const EdgeInsets.symmetric(horizontal: 13), + child: const Row( + children: [ + Icon(Icons.search, size: 20, color: Color(0x66565656)), + SizedBox(width: 10), + Text( + 'Search', + style: TextStyle( + fontSize: 15, + color: Color(0xFF565656), + decoration: TextDecoration.none, ), - ], - ), + ), + ], ), ), - 'pulse-inside': () => - _card(const BorderBeam.pulseInside(child: _Surface())), - 'pulse-outside': () => - _card(const BorderBeam.pulseOutside(child: _Surface())), - 'palettes': () => const _PaletteSweep(), - 'squircle': () => _card( - const BorderBeam.rotate( - colors: BeamColors.ocean, - shape: BeamShape(superellipse: true), - borderRadius: 28, - child: _Surface(radius: 28), - ), + ), + 'pulse': () => + _card(const BorderBeam(effect: BeamEffect.pulse(), child: _Surface())), + 'palettes': () => const _PaletteSweep(), + 'squircle': () => _card( + const BorderBeam( + effect: BeamEffect.rotate(), + colors: BeamColors.ocean, + shape: BeamShape.all(28, superellipse: true), + child: _Surface(radius: 28), ), - }, - ); -} + ), + }, +); Widget _card(Widget beam) => SizedBox(width: 350, height: 140, child: beam); @@ -79,6 +61,12 @@ BoxDecoration _surfaceDecoration(double radius) => BoxDecoration( border: Border.all(color: const Color(0x852C2F36)), ); +const TextStyle _labelStyle = TextStyle( + fontSize: 13, + color: Color(0xFF4E4E4E), + decoration: TextDecoration.none, +); + class _Surface extends StatelessWidget { const _Surface({this.radius = 16}); @@ -88,18 +76,11 @@ class _Surface extends StatelessWidget { Widget build(BuildContext context) => Container( decoration: _surfaceDecoration(radius), alignment: Alignment.center, - child: const Text( - 'Build anything...', - style: TextStyle( - fontSize: 13, - color: Color(0xFF4E4E4E), - decoration: TextDecoration.none, - ), - ), + child: const Text('Build anything...', style: _labelStyle), ); } -/// Three stacked cards cycling ocean / sunset / custom palettes. +/// Three stacked cards: two of the newer presets and a custom ring. class _PaletteSweep extends StatelessWidget { const _PaletteSweep(); @@ -108,14 +89,18 @@ class _PaletteSweep extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ for (final colors in const [ - BeamColors.ocean, - BeamColors.sunset, - BeamColors.custom([Color(0xFFFF0080), Color(0xFF00E5FF)]), + BeamColors.lagoon, + BeamColors.cosmic, + BeamColors([Color(0xFFFF0080), Color(0xFF00E5FF)]), ]) ...[ SizedBox( width: 320, height: 88, - child: BorderBeam.rotate(colors: colors, child: const _Surface()), + child: BorderBeam( + effect: const BeamEffect.rotate(), + colors: colors, + child: const _Surface(), + ), ), const SizedBox(height: 20), ], diff --git a/example/lib/src/controls.dart b/example/lib/src/controls.dart new file mode 100644 index 0000000..3921fc2 --- /dev/null +++ b/example/lib/src/controls.dart @@ -0,0 +1,297 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:material_ui/material_ui.dart'; + +import 'surfaces.dart' show squircle; +import 'tokens.dart'; + +/// Scales its child down a touch while pressed, and clicks on tap. +class Pressable extends StatefulWidget { + /// Creates the wrapper. + const Pressable({ + super.key, + required this.onTap, + required this.child, + this.semanticLabel, + this.selected = false, + }); + + /// Called on tap. + final VoidCallback onTap; + + /// The pressable content. + final Widget child; + + /// What a screen reader announces. + final String? semanticLabel; + + /// Whether a screen reader should announce this as selected. + final bool selected; + + @override + State createState() => _PressableState(); +} + +class _PressableState extends State { + bool _down = false; + + void _set(bool down) { + if (_down != down) setState(() => _down = down); + } + + @override + Widget build(BuildContext context) => Semantics( + button: true, + selected: widget.selected, + label: widget.semanticLabel, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTapDown: (_) => _set(true), + onTapCancel: () => _set(false), + onTapUp: (_) => _set(false), + onTap: () { + HapticFeedback.selectionClick(); + widget.onTap(); + }, + child: AnimatedScale( + scale: _down ? 0.94 : 1, + duration: const Duration(milliseconds: 140), + curve: easeOut, + child: widget.child, + ), + ), + ); +} + +/// A segmented control over the effects whose thumb tracks [page] — the +/// stage's live scroll position — so it slides with a swipe as well as a +/// tap. +class EffectSelector extends StatelessWidget { + /// Creates the selector. + const EffectSelector({ + super.key, + required this.labels, + required this.page, + required this.onSelect, + }); + + /// One label per effect. + final List labels; + + /// The stage's page, fractional mid-swipe. + final ValueListenable page; + + /// Called with the tapped index. + final ValueChanged onSelect; + + @override + Widget build(BuildContext context) { + final t = Tokens.of(context); + return Container( + height: 40, + padding: const EdgeInsets.all(3), + decoration: ShapeDecoration(color: t.track, shape: squircle(20)), + child: LayoutBuilder( + builder: (context, box) { + final segment = box.maxWidth / labels.length; + return ValueListenableBuilder( + valueListenable: page, + builder: (context, page, _) => Stack( + children: [ + Positioned( + left: page * segment, + width: segment, + top: 0, + bottom: 0, + child: DecoratedBox( + decoration: ShapeDecoration( + color: t.thumb, + shape: squircle(17), + shadows: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.08), + blurRadius: 6, + offset: const Offset(0, 1), + ), + ], + ), + ), + ), + Row( + children: [ + for (final (i, label) in labels.indexed) + Expanded( + child: Pressable( + onTap: () => onSelect(i), + selected: page.round() == i, + child: Center( + child: Text( + label, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w500, + letterSpacing: -0.1, + // Brightens as the thumb arrives. + color: Color.lerp( + t.text, + t.muted, + (page - i).abs().clamp(0, 1), + ), + ), + ), + ), + ), + ), + ], + ), + ], + ), + ); + }, + ), + ); + } +} + +/// One round swatch per entry of [BeamColors.presets], drawn from the +/// palette's own stops, in a row that scrolls under faded edges. +class PaletteRow extends StatelessWidget { + /// Creates the row. + const PaletteRow({super.key, required this.selected, required this.onSelect}); + + /// The selected preset's name. + final String selected; + + /// Called with the tapped preset's name. + final ValueChanged onSelect; + + static const double _size = 30; + static const double _ring = 3; + + @override + Widget build(BuildContext context) { + final t = Tokens.of(context); + final names = BeamColors.presets.keys.toList(); + return ShaderMask( + blendMode: BlendMode.dstIn, + shaderCallback: (bounds) => const LinearGradient( + colors: [ + Color(0x00000000), + Color(0xFF000000), + Color(0xFF000000), + Color(0x00000000), + ], + stops: [0, 0.06, 0.94, 1], + ).createShader(bounds), + child: SizedBox( + height: _size + 4 * _ring, + child: ListView.separated( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 20), + itemCount: names.length, + separatorBuilder: (_, _) => const SizedBox(width: 8), + itemBuilder: (context, i) { + final name = names[i]; + final on = name == selected; + return Pressable( + key: ValueKey('swatch-$name'), + onTap: () => onSelect(name), + semanticLabel: '$name palette', + selected: on, + child: AnimatedContainer( + duration: const Duration(milliseconds: 180), + curve: easeOut, + padding: const EdgeInsets.all(_ring), + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: on ? t.text : t.text.withValues(alpha: 0), + width: 1.5, + ), + ), + child: Container( + width: _size, + height: _size, + decoration: BoxDecoration( + shape: BoxShape.circle, + gradient: _ringGradient(BeamColors.presets[name]!), + ), + ), + ), + ); + }, + ), + ), + ); + } + + // The palette's ring as a sweep from 12 o'clock, clockwise — where the + // beam itself places the stops. The ring wraps: past the last stop it + // blends back into the first across 12 o'clock, so both ends of the sweep + // carry the palette's own colour there. + static Gradient _ringGradient(BeamColors colors) { + final palette = colors.resolve(); + final stops = palette.stops; + final opaque = [for (final c in palette.colors) c.withValues(alpha: 1)]; + if (opaque.length == 1) { + return SweepGradient(colors: [opaque.first, opaque.first]); + } + final wrap = palette.sample(0).withValues(alpha: 1); + return SweepGradient( + transform: const GradientRotation(-math.pi / 2), + colors: [wrap, ...opaque, wrap], + stops: [0, ...stops, 1], + ); + } +} + +/// A small round icon button whose glyph turns as it changes — the +/// header's play/pause and theme toggles. +class RoundToggle extends StatelessWidget { + /// Creates the button. + const RoundToggle({ + super.key, + required this.icon, + required this.label, + required this.onTap, + }); + + /// The current glyph; a new one rotates in. + final IconData icon; + + /// What a screen reader announces. + final String label; + + /// Called on tap. + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final t = Tokens.of(context); + return Pressable( + onTap: onTap, + semanticLabel: label, + child: Container( + width: 36, + height: 36, + decoration: BoxDecoration(color: t.track, shape: BoxShape.circle), + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 200), + switchInCurve: easeOut, + switchOutCurve: easeOut, + transitionBuilder: (child, animation) => FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: Tween(begin: 0.6, end: 1.0).animate(animation), + child: child, + ), + ), + child: Icon(icon, key: ValueKey(icon), size: 18, color: t.muted), + ), + ), + ); + } +} diff --git a/example/lib/src/demo_theme.dart b/example/lib/src/demo_theme.dart deleted file mode 100644 index 4185bb6..0000000 --- a/example/lib/src/demo_theme.dart +++ /dev/null @@ -1,226 +0,0 @@ -import 'package:flutter/widgets.dart'; - -/// Design tokens transcribed from the original border-beam demo -/// (demo/src/styles.css of the React package) so the Flutter gallery looks -/// identical — no Material defaults anywhere. -class DemoTokens { - const DemoTokens._({ - required this.bg, - required this.text, - required this.heading, - required this.subtitle, - required this.muted, - required this.panel, - required this.surface, - required this.tabsBarBg, - required this.tabsPillBg, - required this.tabsTextMuted, - required this.tabsTextActive, - required this.btnBg, - required this.btnBgActive, - required this.btnText, - required this.btnTextActive, - required this.trackBg, - required this.trackFill, - required this.mockBg, - required this.mockBorder, - required this.mockChipBg, - required this.mockChipLine, - required this.mockText, - required this.mockTextStrong, - required this.mockPlaceholder, - required this.mockTagText, - required this.mockSearchText, - required this.mockSquare, - required this.mockIcon, - required this.shimmerBase, - required this.codeText, - }); - - /// Dark theme tokens (`:root` in the demo CSS). - static const dark = DemoTokens._( - bg: Color(0xFF070707), - text: Color(0xFFFBFBFB), - heading: Color(0xFFFFFFFF), - subtitle: Color(0xFFCACACA), - muted: Color(0x99FBFBFB), - panel: Color(0xFF121212), - surface: Color(0x0DD9D9D9), - tabsBarBg: Color(0xFF1C1C1C), - tabsPillBg: Color(0xFF494949), - tabsTextMuted: Color(0x80EFEFEF), - tabsTextActive: Color(0xFFEFEFEF), - btnBg: Color(0x08FFFFFF), - btnBgActive: Color(0x1AFFFFFF), - btnText: Color(0x80FBFBFB), - btnTextActive: Color(0xFFFBFBFB), - trackBg: Color(0x12FFFFFF), - trackFill: Color(0x1AFFFFFF), - mockBg: Color(0xFF1D1D1D), - mockBorder: Color(0x852C2F36), - mockChipBg: Color(0x0AFFFFFF), - mockChipLine: Color(0x05FFFFFF), - mockText: Color(0xFFC0C0C0), - mockTextStrong: Color(0xFFFFFFFF), - mockPlaceholder: Color(0xFF4E4E4E), - mockTagText: Color(0xFFCACCD2), - mockSearchText: Color(0xFF565656), - mockSquare: Color(0xCCD9D9D9), - mockIcon: Color(0xFF808388), - shimmerBase: Color(0xFF6F6C6C), - codeText: Color(0xFFFFFFFF), - ); - - /// Light theme tokens (`html[data-theme='light']`). - static const light = DemoTokens._( - bg: Color(0xFFFDFDFD), - text: Color(0xFF1A1A22), - heading: Color(0xFF111111), - subtitle: Color(0xFF5C5C6E), - muted: Color(0xFF5C5C6E), - panel: Color(0xFFF4F4F7), - surface: Color(0xFFF6F6F8), - tabsBarBg: Color(0xFFF5F5F5), - tabsPillBg: Color(0xFFFFFFFF), - tabsTextMuted: Color(0x99333333), - tabsTextActive: Color(0xFF2B2B2B), - btnBg: Color(0x08111111), - btnBgActive: Color(0xFFFFFFFF), - btnText: Color(0xFF5C5C6E), - btnTextActive: Color(0xFF111111), - trackBg: Color(0x0F111111), - trackFill: Color(0x24111111), - mockBg: Color(0xFFFFFFFF), - mockBorder: Color(0xD9C8C8D4), - mockChipBg: Color(0x0A111111), - mockChipLine: Color(0x0D000000), - mockText: Color(0xFF3A3A48), - mockTextStrong: Color(0xFF111111), - mockPlaceholder: Color(0xFF9A9AA4), - mockTagText: Color(0xFF3A3A48), - mockSearchText: Color(0xFF8A8A94), - mockSquare: Color(0xBF282834), - mockIcon: Color(0xFF6B6E76), - shimmerBase: Color(0xFF9A9AA4), - codeText: Color(0xFF1A1A22), - ); - - /// Page background (`--c-bg`). - final Color bg; - - /// Body text (`--c-text`). - final Color text; - - /// Headings (`--c-heading`). - final Color heading; - - /// Subtitle text (`--c-subtitle`). - final Color subtitle; - - /// Muted body text (`--c-muted`). - final Color muted; - - /// Code/panel background (`--c-panel`). - final Color panel; - - /// Example frame background (`--c-surface`). - final Color surface; - - /// Tab bar background (`--tabs-bar-bg`). - final Color tabsBarBg; - - /// Active tab pill background (`--tabs-pill-bg`). - final Color tabsPillBg; - - /// Inactive tab text (`--tabs-text-muted`). - final Color tabsTextMuted; - - /// Active tab text (`--tabs-text-active`). - final Color tabsTextActive; - - /// Control button background (`--c-btn-bg`). - final Color btnBg; - - /// Active control button background (`--c-btn-bg-active`). - final Color btnBgActive; - - /// Control button text (`--c-btn-text`). - final Color btnText; - - /// Active control button text (`--c-btn-text-active`). - final Color btnTextActive; - - /// Slider track background (`--c-track-bg`). - final Color trackBg; - - /// Slider track fill (`--c-track-fill`). - final Color trackFill; - - /// Mock surface background (`--c-mock-bg`). - final Color mockBg; - - /// Mock surface 1px ring (`--c-mock-border`). - final Color mockBorder; - - /// Mock chip background (`--c-mock-chip-bg`). - final Color mockChipBg; - - /// Mock chip hairline (`--c-mock-chip-line`). - final Color mockChipLine; - - /// Mock body text (`--c-mock-text`). - final Color mockText; - - /// Mock strong text (`--c-mock-text-strong`). - final Color mockTextStrong; - - /// Mock placeholder text (`--c-mock-placeholder`). - final Color mockPlaceholder; - - /// Mock tag text (`--c-mock-tag-text`). - final Color mockTagText; - - /// Mock search text (`--c-mock-search-text`). - final Color mockSearchText; - - /// Mock icon-button square (`--c-mock-square`). - final Color mockSquare; - - /// Mock icon stroke color. - final Color mockIcon; - - /// Shimmer base text color (`--shimmer-base`). - final Color shimmerBase; - - /// Code block text (`--c-code-text`). - final Color codeText; -} - -/// Inherited access to the active token set + theme toggling. -class DemoTheme extends InheritedWidget { - /// Creates the theme scope. - const DemoTheme({ - super.key, - required this.tokens, - required this.isDark, - required this.toggle, - required super.child, - }); - - /// Active tokens. - final DemoTokens tokens; - - /// Whether the dark set is active. - final bool isDark; - - /// Switches dark/light. - final VoidCallback toggle; - - /// Lookup. - static DemoTheme of(BuildContext context) => - context.dependOnInheritedWidgetOfExactType()!; - - @override - bool updateShouldNotify(DemoTheme oldWidget) => - oldWidget.tokens != tokens || oldWidget.isDark != isDark; -} diff --git a/example/lib/src/home.dart b/example/lib/src/home.dart new file mode 100644 index 0000000..195c2c6 --- /dev/null +++ b/example/lib/src/home.dart @@ -0,0 +1,276 @@ +import 'dart:math' as math; + +import 'package:flutter/services.dart'; +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:material_ui/material_ui.dart'; + +import 'controls.dart'; +import 'surfaces.dart'; +import 'tokens.dart'; + +/// The one screen: a stage you swipe between the three effects, each on the +/// surface it is made for, with a caption, an effect selector, and the +/// palettes underneath. Tapping the stage fades the beam out and back in. +class Home extends StatefulWidget { + /// Creates the screen. + const Home({super.key, required this.dark, required this.onToggleTheme}); + + /// Whether the dark theme is on; the beams are tuned to match. + final bool dark; + + /// Flips the app theme. + final VoidCallback onToggleTheme; + + @override + State createState() => _HomeState(); +} + +class _HomeState extends State { + static const _effects = BeamEffect.values; + + // Launch flags, for captures and recordings: + // --dart-define=START=pulse --dart-define=PALETTE=ocean (and THEME=light, + // read in main.dart). + static final int _start = math.max( + 0, + _effects.indexWhere((e) => e.name == const String.fromEnvironment('START')), + ); + + late final PageController _pages = PageController(initialPage: _start); + late final ValueNotifier _page = ValueNotifier( + _start.toDouble(), + ); + late int _index = _start; + // An unknown PALETTE falls back to colorful, so the caption never names a + // palette the beam is not drawing. + static const _paletteFlag = String.fromEnvironment('PALETTE'); + String _palette = BeamColors.presets.containsKey(_paletteFlag) + ? _paletteFlag + : 'colorful'; + bool _active = true; + + @override + void initState() { + super.initState(); + _pages.addListener(() { + final page = _pages.page ?? 0; + _page.value = page; + if (page.round() != _index) setState(() => _index = page.round()); + }); + } + + @override + void dispose() { + _pages.dispose(); + _page.dispose(); + super.dispose(); + } + + void _select(int index) => _pages.animateToPage( + index, + duration: const Duration(milliseconds: 420), + curve: easeOut, + ); + + @override + Widget build(BuildContext context) { + final t = Tokens.of(context); + return AnnotatedRegion( + value: widget.dark + ? SystemUiOverlayStyle.light + : SystemUiOverlayStyle.dark, + child: Material( + color: t.bg, + child: SafeArea( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 560), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(24, 10, 16, 0), + child: Row( + children: [ + Text( + 'Border Beam', + style: TextStyle( + color: t.text, + fontSize: 16, + fontWeight: FontWeight.w600, + letterSpacing: -0.3, + ), + ), + const Spacer(), + RoundToggle( + key: const ValueKey('active-toggle'), + icon: _active + ? Icons.pause_rounded + : Icons.play_arrow_rounded, + label: _active ? 'Fade the beam out' : 'Fade it in', + onTap: _toggleActive, + ), + const SizedBox(width: 8), + RoundToggle( + key: const ValueKey('theme-toggle'), + icon: widget.dark + ? Icons.dark_mode_outlined + : Icons.light_mode_outlined, + label: widget.dark ? 'Light theme' : 'Dark theme', + onTap: widget.onToggleTheme, + ), + ], + ), + ), + Expanded(child: _stage(t)), + _caption(t), + const SizedBox(height: 20), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: EffectSelector( + labels: [for (final e in _effects) _title(e)], + page: _page, + onSelect: _select, + ), + ), + const SizedBox(height: 14), + PaletteRow( + selected: _palette, + onSelect: (name) => setState(() => _palette = name), + ), + const SizedBox(height: 12), + ], + ), + ), + ), + ), + ), + ); + } + + void _toggleActive() => setState(() => _active = !_active); + + // The swipeable stage; a tap fades the beam out and back in. Neighbouring + // pages dim and shrink a little as they leave, so a swipe reads as moving + // between exhibits. + Widget _stage(Tokens t) => GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: _toggleActive, + child: DecoratedBox( + // A faint spotlight, so the exhibit sits on a stage rather than a void. + decoration: BoxDecoration( + gradient: RadialGradient(colors: [t.spot, t.bg], radius: 0.5), + ), + child: LayoutBuilder( + builder: (context, box) => PageView.builder( + controller: _pages, + itemCount: _effects.length, + itemBuilder: (context, i) => ValueListenableBuilder( + valueListenable: _page, + builder: (context, page, child) { + final away = (page - i).abs().clamp(0.0, 1.0); + return Opacity( + opacity: 1 - away * 0.6, + child: Transform.scale(scale: 1 - away * 0.08, child: child), + ); + }, + // Scales down only when the stage is short (a phone on its side). + child: Padding( + padding: const EdgeInsets.all(16), + child: FittedBox( + fit: BoxFit.scaleDown, + child: _exhibit(_effects[i], box.maxWidth), + ), + ), + ), + ), + ), + ), + ); + + // The surfaces' continuous corners, so each beam sits on its edge. + static const _cardShape = BeamShape.all(surfaceRadius, superellipse: true); + + // One effect on the surface it is made for. + Widget _exhibit(BeamEffect effect, double stageWidth) { + final width = math.min(340.0, stageWidth - 48); + final (Widget surface, BeamShape shape) = switch (effect) { + RotateEffect() => (TaskCard(width: width), _cardShape), + LineEffect() => (Composer(width: width), _cardShape), + PulseEffect() => (ThinkingCard(width: width), _cardShape), + }; + return BorderBeam( + effect: effect, + colors: BeamColors.presets[_palette], + active: _active, + shape: shape, + style: BeamStyle(theme: widget.dark ? BeamTheme.dark : BeamTheme.light), + child: surface, + ); + } + + Widget _caption(Tokens t) { + final effect = _effects[_index]; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Column( + children: [ + AnimatedSwitcher( + duration: const Duration(milliseconds: 220), + switchInCurve: easeOut, + switchOutCurve: easeOut, + transitionBuilder: (child, animation) => FadeTransition( + opacity: animation, + child: SlideTransition( + position: Tween( + begin: const Offset(0, 0.12), + end: Offset.zero, + ).animate(animation), + child: child, + ), + ), + child: Column( + key: ValueKey(_index), + children: [ + Text( + _title(effect), + style: TextStyle( + color: t.text, + fontSize: 26, + fontWeight: FontWeight.w600, + letterSpacing: -0.6, + ), + ), + const SizedBox(height: 6), + Text( + _blurb(effect), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.muted, fontSize: 14, height: 1.4), + ), + ], + ), + ), + const SizedBox(height: 10), + Text( + 'BeamEffect.${effect.name}() · BeamColors.$_palette', + style: TextStyle( + color: t.faint, + fontSize: 12, + fontFamily: 'Menlo', + fontFamilyFallback: const ['monospace', 'Consolas'], + ), + ), + ], + ), + ); + } +} + +String _title(BeamEffect effect) => + effect.name[0].toUpperCase() + effect.name.substring(1); + +String _blurb(BeamEffect effect) => switch (effect) { + RotateEffect() => 'A beam laps the border of a card.', + LineEffect() => 'A streak rides the edge of an input.', + PulseEffect() => 'Colour breathes in while it thinks.', +}; diff --git a/example/lib/src/mocks.dart b/example/lib/src/mocks.dart deleted file mode 100644 index 4dd52aa..0000000 --- a/example/lib/src/mocks.dart +++ /dev/null @@ -1,380 +0,0 @@ -import 'package:flutter/material.dart'; - -import 'demo_theme.dart'; - -/// Mock UI surfaces mirroring the original border-beam demo (`mocks.tsx` + -/// `styles.css`): a chat input, an agent working card, a subscribe pill, an -/// icon button, and a search bar. Purely presentational. - -BoxDecoration _mockBox(DemoTokens t, double radius) => BoxDecoration( - color: t.mockBg, - borderRadius: BorderRadius.circular(radius), - border: Border.all(color: t.mockBorder), -); - -TextStyle _mockStyle( - Color color, { - double size = 13, - FontWeight weight = FontWeight.w400, -}) => TextStyle( - fontSize: size, - height: 16 / 13, - fontWeight: weight, - color: color, - decoration: TextDecoration.none, - fontFamily: '.SF Pro Text', - fontFamilyFallback: const ['Inter', 'Roboto'], -); - -/// The 348×137 chat input ("Build anything...") — the hero example. -class MockChatInput extends StatelessWidget { - /// Const constructor. - const MockChatInput({super.key}); - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - Widget chip({required Widget child, EdgeInsets? padding}) => Container( - height: 24, - padding: padding ?? const EdgeInsets.symmetric(horizontal: 6), - decoration: BoxDecoration( - color: t.mockChipBg, - borderRadius: BorderRadius.circular(36), - border: Border.all(color: t.mockChipLine), - ), - child: Row(mainAxisSize: MainAxisSize.min, children: [child]), - ); - - return Container( - width: 348, - height: 137, - decoration: _mockBox(t, 20), - padding: const EdgeInsets.fromLTRB(7, 7, 7, 8), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - chip( - padding: const EdgeInsets.symmetric(horizontal: 4), - child: Icon(Icons.alternate_email, size: 16, color: t.mockIcon), - ), - Padding( - padding: const EdgeInsets.fromLTRB(4, 16, 4, 0), - child: Text( - 'Build anything...', - style: _mockStyle(t.mockPlaceholder), - ), - ), - const Spacer(), - Row( - children: [ - for (final label in ['Agent', 'Auto']) ...[ - chip( - padding: const EdgeInsets.only(left: 8, right: 6), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text(label, style: _mockStyle(t.mockTagText, size: 12)), - Icon( - Icons.keyboard_arrow_down, - size: 16, - color: t.mockIcon.withValues(alpha: 0.6), - ), - ], - ), - ), - const SizedBox(width: 8), - ], - const Spacer(), - Container( - width: 28, - height: 28, - decoration: BoxDecoration( - color: t.mockChipBg, - shape: BoxShape.circle, - border: Border.all(color: t.mockChipLine), - ), - child: Icon( - Icons.arrow_upward, - size: 16, - color: t.mockIcon.withValues(alpha: 0.5), - ), - ), - ], - ), - ], - ), - ); - } -} - -/// The agent task list card with the shimmering "Working..." header. -class MockWorkingCard extends StatelessWidget { - /// Const constructor. - const MockWorkingCard({super.key}); - - static const _tasks = [ - 'Generate color palettes', - 'Recommend font pairings', - 'Create layout templates', - 'Build section engine', - 'Generate hero variants', - ]; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Container( - width: 295, - decoration: _mockBox(t, 20), - padding: const EdgeInsets.fromLTRB(20, 18, 20, 20), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - _ShimmerText('Working...', base: t.shimmerBase), - const SizedBox(height: 24), - for (final (i, task) in _tasks.indexed) ...[ - if (i > 0) const SizedBox(height: 20), - Row( - children: [ - _DashedCircle(color: t.mockIcon), - const SizedBox(width: 12), - Expanded( - child: Text( - task, - style: _mockStyle(t.mockText), - softWrap: false, - overflow: TextOverflow.clip, - ), - ), - ], - ), - ], - ], - ), - ); - } -} - -/// The "Subscribe" pill button. -class MockSubscribeButton extends StatelessWidget { - /// Const constructor. - const MockSubscribeButton({super.key}); - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Container( - height: 40, - padding: const EdgeInsets.symmetric(horizontal: 20), - decoration: _mockBox(t, 48), - alignment: Alignment.center, - child: Text( - 'Subscribe', - style: _mockStyle(t.mockTextStrong, weight: FontWeight.w500), - ), - ); - } -} - -/// The 36×36 icon button with a small square glyph. -class MockIconButton extends StatelessWidget { - /// Const constructor. - const MockIconButton({super.key}); - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Container( - width: 36, - height: 36, - decoration: _mockBox(t, 20), - alignment: Alignment.center, - child: Container( - width: 12, - height: 12, - decoration: BoxDecoration( - color: t.mockSquare, - borderRadius: BorderRadius.circular(2), - ), - ), - ); - } -} - -/// The 366×42 pill search bar. -class MockSearchBar extends StatelessWidget { - /// Const constructor. - const MockSearchBar({super.key}); - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Container( - width: 366, - height: 42, - decoration: _mockBox(t, 21), - padding: const EdgeInsets.symmetric(horizontal: 13), - child: Row( - children: [ - Icon( - Icons.search, - size: 20, - color: t.mockSearchText.withValues(alpha: 0.4), - ), - const SizedBox(width: 10), - Text('Search', style: _mockStyle(t.mockSearchText, size: 15)), - ], - ), - ); - } -} - -/// A focusable field with no Material ancestor: a [Focus] around a painted -/// box, so the gallery can show `BeamFocusRing` lighting on focus without -/// pulling in Material's own input decoration. -class MockFocusField extends StatefulWidget { - /// Creates the field. - const MockFocusField({ - super.key, - this.label = 'Tap to focus', - this.width = 210, - }); - - /// Placeholder text. - final String label; - - /// Field width. - final double width; - - @override - State createState() => _MockFocusFieldState(); -} - -class _MockFocusFieldState extends State { - late final FocusNode _node = FocusNode(debugLabel: 'mock-focus-field'); - - @override - void dispose() { - _node.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Focus( - focusNode: _node, - child: GestureDetector( - onTap: _node.requestFocus, - child: AnimatedBuilder( - animation: _node, - builder: (context, _) => Container( - width: widget.width, - height: 40, - decoration: _mockBox(t, 12), - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Row( - children: [ - Container( - width: 1.5, - height: 16, - color: _node.hasFocus ? t.mockTextStrong : t.mockPlaceholder, - ), - const SizedBox(width: 8), - Text( - widget.label, - style: _mockStyle( - _node.hasFocus ? t.mockText : t.mockPlaceholder, - ), - ), - ], - ), - ), - ), - ), - ); - } -} - -class _DashedCircle extends StatelessWidget { - const _DashedCircle({required this.color}); - - final Color color; - - @override - Widget build(BuildContext context) => CustomPaint( - size: const Size(16, 16), - painter: _DashedCirclePainter(color), - ); -} - -class _DashedCirclePainter extends CustomPainter { - const _DashedCirclePainter(this.color); - - final Color color; - - @override - void paint(Canvas canvas, Size size) { - final paint = Paint() - ..color = color - ..style = PaintingStyle.stroke - ..strokeWidth = 1.5 - ..strokeCap = StrokeCap.round; - final rect = (Offset.zero & size).deflate(1); - // 8 dashes around the circle, matching the SVG's `stroke-dasharray 3 3`. - const dashes = 8; - const sweep = 3.14159 * 2 / dashes; - for (var i = 0; i < dashes; i++) { - canvas.drawArc(rect, i * sweep, sweep * 0.55, false, paint); - } - } - - @override - bool shouldRepaint(_DashedCirclePainter oldDelegate) => - oldDelegate.color != color; -} - -/// A shimmering loading label (port of the demo's `t-shimmer`). -class _ShimmerText extends StatefulWidget { - const _ShimmerText(this.text, {required this.base}); - - final String text; - final Color base; - - @override - State<_ShimmerText> createState() => _ShimmerTextState(); -} - -class _ShimmerTextState extends State<_ShimmerText> - with SingleTickerProviderStateMixin { - late final AnimationController _controller = AnimationController( - vsync: this, - duration: const Duration(milliseconds: 2000), - )..repeat(); - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return AnimatedBuilder( - animation: _controller, - builder: (context, _) { - final x = 1 - _controller.value * 2; // 1 → −1 sweep - return ShaderMask( - shaderCallback: (bounds) => LinearGradient( - begin: Alignment(x - 1, 0), - end: Alignment(x + 1, 0), - colors: [widget.base, t.text, widget.base], - ).createShader(bounds), - child: Text(widget.text, style: _mockStyle(widget.base)), - ); - }, - ); - } -} diff --git a/example/lib/src/playground.dart b/example/lib/src/playground.dart deleted file mode 100644 index be0d3ac..0000000 --- a/example/lib/src/playground.dart +++ /dev/null @@ -1,9 +0,0 @@ -/// The gallery's interactive playground. -/// -/// The pieces live in `playground/`: the state bag every control drives -/// (`playground_state.dart`), the shareable-link codec (`share_codec.dart`), -/// the snippet generator (`snippet.dart`), the control widgets -/// (`controls.dart`), and the section itself (`playground_section.dart`). -library; - -export 'playground/playground_section.dart' show PlaygroundSection; diff --git a/example/lib/src/playground/controls.dart b/example/lib/src/playground/controls.dart deleted file mode 100644 index 04a06b9..0000000 --- a/example/lib/src/playground/controls.dart +++ /dev/null @@ -1,650 +0,0 @@ -import 'package:flutter/material.dart'; - -import '../demo_theme.dart'; - -/// A collapsible group of playground controls, headed by a tappable title -/// row in the demo's own typography. -class ControlSection extends StatefulWidget { - /// Creates a section, open when [initiallyExpanded]. - const ControlSection({ - super.key, - required this.title, - required this.children, - this.initiallyExpanded = false, - }); - - /// Header label. - final String title; - - /// Rows revealed while the section is open. - final List children; - - /// Whether the section starts open. - final bool initiallyExpanded; - - @override - State createState() => _ControlSectionState(); -} - -class _ControlSectionState extends State { - late bool _expanded = widget.initiallyExpanded; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Container( - margin: const EdgeInsets.only(bottom: 8), - decoration: BoxDecoration( - color: t.panel, - borderRadius: BorderRadius.circular(16), - ), - clipBehavior: Clip.antiAlias, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () => setState(() => _expanded = !_expanded), - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 14, 14, 14), - child: Row( - children: [ - Expanded( - child: Text( - widget.title, - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w600, - color: t.heading, - decoration: TextDecoration.none, - ), - ), - ), - AnimatedRotation( - turns: _expanded ? 0.5 : 0, - duration: const Duration(milliseconds: 180), - curve: const Cubic(0.22, 1, 0.36, 1), - child: Icon( - Icons.keyboard_arrow_down, - size: 18, - color: t.muted, - ), - ), - ], - ), - ), - ), - AnimatedSize( - duration: const Duration(milliseconds: 180), - curve: const Cubic(0.22, 1, 0.36, 1), - alignment: Alignment.topCenter, - child: _expanded - ? Padding( - padding: const EdgeInsets.fromLTRB(16, 0, 16, 14), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: widget.children, - ), - ) - : const SizedBox(width: double.infinity), - ), - ], - ), - ); - } -} - -/// A labelled control row: a fixed-width label and the control beside it, -/// stacking the two on narrow layouts. -class ControlRow extends StatelessWidget { - /// Creates a row. - const ControlRow({ - super.key, - required this.label, - required this.child, - this.enabled = true, - }); - - /// Left-hand label. - final String label; - - /// The control. - final Widget child; - - /// Whether the control accepts input; a disabled row dims and ignores - /// pointers. - final bool enabled; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Padding( - padding: const EdgeInsets.symmetric(vertical: 4), - child: Opacity( - opacity: enabled ? 1 : 0.4, - child: IgnorePointer( - ignoring: !enabled, - child: LayoutBuilder( - builder: (context, constraints) { - final labelWidget = Text( - label, - style: TextStyle( - fontSize: 12, - color: t.muted, - decoration: TextDecoration.none, - ), - ); - if (constraints.maxWidth < 300) { - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Align(alignment: Alignment.centerLeft, child: labelWidget), - const SizedBox(height: 2), - child, - ], - ); - } - return Row( - children: [ - SizedBox(width: 104, child: labelWidget), - Expanded(child: child), - ], - ); - }, - ), - ), - ), - ); - } -} - -/// The demo's pill control button, used for every toggle and choice. -class DemoChip extends StatelessWidget { - /// Creates a chip. - const DemoChip({ - super.key, - required this.label, - required this.selected, - required this.onTap, - this.leading, - this.enabled = true, - }); - - /// Chip text. - final String label; - - /// Whether the chip reads as on. - final bool selected; - - /// Tap callback. - final VoidCallback onTap; - - /// Whether the chip accepts input. - final bool enabled; - - /// Optional widget ahead of the label (a color dot, for instance). - final Widget? leading; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return IgnorePointer( - ignoring: !enabled, - child: Opacity( - opacity: enabled ? 1 : 0.4, - child: GestureDetector( - onTap: onTap, - child: AnimatedContainer( - duration: const Duration(milliseconds: 150), - curve: const Cubic(0.22, 1, 0.36, 1), - height: 28, - padding: const EdgeInsets.symmetric(horizontal: 12), - alignment: Alignment.center, - decoration: BoxDecoration( - color: selected ? t.btnBgActive : t.btnBg, - borderRadius: BorderRadius.circular(14), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (leading case final Widget widget) ...[ - widget, - const SizedBox(width: 6), - ], - Flexible( - child: Text( - label, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w500, - color: selected ? t.btnTextActive : t.btnText, - decoration: TextDecoration.none, - ), - ), - ), - ], - ), - ), - ), - ), - ); - } -} - -/// A row of chips laid out as a wrap, one of which is selected. -class ChipGroup extends StatelessWidget { - /// Creates a chip group. - const ChipGroup({super.key, required this.children}); - - /// The chips. - final List children; - - @override - Widget build(BuildContext context) => - Wrap(spacing: 6, runSpacing: 6, children: children); -} - -/// The demo's minimal drag track, mapped over an arbitrary range. -class MinimalSlider extends StatelessWidget { - /// Creates a slider. - const MinimalSlider({ - super.key, - required this.value, - required this.min, - required this.max, - required this.onChanged, - }); - - /// Current value, clamped into [min]–[max] for display. - final double value; - - /// Range start. - final double min; - - /// Range end. - final double max; - - /// Called with the new value on tap or drag. - final ValueChanged onChanged; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - final fraction = ((value - min) / (max - min)).clamp(0.0, 1.0); - return LayoutBuilder( - builder: (context, constraints) { - void update(Offset local) { - final f = (local.dx / constraints.maxWidth).clamp(0.0, 1.0); - // Two decimals is the resolution the share codec round-trips. - onChanged(double.parse((min + f * (max - min)).toStringAsFixed(2))); - } - - return GestureDetector( - behavior: HitTestBehavior.opaque, - onTapDown: (d) => update(d.localPosition), - onHorizontalDragUpdate: (d) => update(d.localPosition), - child: SizedBox( - width: double.infinity, - height: 28, - child: Center( - child: Stack( - children: [ - Container( - height: 6, - decoration: BoxDecoration( - color: t.trackBg, - borderRadius: BorderRadius.circular(3), - ), - ), - FractionallySizedBox( - widthFactor: fraction, - child: Container( - height: 6, - decoration: BoxDecoration( - color: t.trackFill, - borderRadius: BorderRadius.circular(3), - ), - ), - ), - ], - ), - ), - ), - ); - }, - ); - } -} - -/// A slider row that always carries a value, with the number shown beside -/// the track. -class SliderRow extends StatelessWidget { - /// Creates the row. - const SliderRow({ - super.key, - required this.label, - required this.value, - required this.min, - required this.max, - required this.onChanged, - this.suffix = '', - this.enabled = true, - }); - - /// Row label. - final String label; - - /// Current value. - final double value; - - /// Range start. - final double min; - - /// Range end. - final double max; - - /// Change callback. - final ValueChanged onChanged; - - /// Unit appended to the readout (`s`, `px`, `°`, `×`). - final String suffix; - - /// Whether the row accepts input. - final bool enabled; - - @override - Widget build(BuildContext context) => ControlRow( - label: label, - enabled: enabled, - child: Row( - children: [ - Expanded( - child: MinimalSlider( - value: value, - min: min, - max: max, - onChanged: onChanged, - ), - ), - const SizedBox(width: 10), - ValueReadout(text: '${formatControlValue(value)}$suffix'), - ], - ), - ); -} - -/// A slider row whose value may be null, meaning the package resolves it. -/// -/// The track sits at [fallback] while the value is null, and an `auto` chip -/// clears it back. -class NullableSliderRow extends StatelessWidget { - /// Creates the row. - const NullableSliderRow({ - super.key, - required this.label, - required this.value, - required this.fallback, - required this.min, - required this.max, - required this.onChanged, - this.suffix = '', - this.enabled = true, - }); - - /// Row label. - final String label; - - /// Current override, or null for the package default. - final double? value; - - /// Where the track sits, and what the readout reports, while [value] is - /// null. Null parks the track at [min] — the package default of that field - /// is internal to the variant preset. - final double? fallback; - - /// Range start. - final double min; - - /// Range end. - final double max; - - /// Change callback; null clears the override. - final ValueChanged onChanged; - - /// Unit appended to the readout. - final String suffix; - - /// Whether the row accepts input. - final bool enabled; - - @override - Widget build(BuildContext context) { - final shown = value ?? fallback ?? min; - return ControlRow( - label: label, - enabled: enabled, - child: Row( - children: [ - Expanded( - child: MinimalSlider( - value: shown, - min: min, - max: max, - onChanged: onChanged, - ), - ), - const SizedBox(width: 10), - ValueReadout( - text: value == null - ? 'auto' - : '${formatControlValue(shown)}$suffix', - ), - const SizedBox(width: 8), - DemoChip( - label: 'auto', - selected: value == null, - onTap: () => onChanged(null), - ), - ], - ), - ); - } -} - -/// The fixed-width numeric readout beside a slider. -class ValueReadout extends StatelessWidget { - /// Creates a readout. - const ValueReadout({super.key, required this.text}); - - /// Formatted value. - final String text; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return SizedBox( - width: 52, - child: Text( - text, - textAlign: TextAlign.right, - style: TextStyle( - fontSize: 12, - color: t.muted, - fontFeatures: const [FontFeature.tabularFigures()], - decoration: TextDecoration.none, - ), - ), - ); - } -} - -/// Formats a control value for its readout: `2` rather than `2.00`. -String formatControlValue(double value) { - final fixed = value.toStringAsFixed(2); - if (!fixed.contains('.')) return fixed; - return fixed.replaceFirst(RegExp(r'\.?0+$'), ''); -} - -/// The install line above the playground: the pub command with the same copy -/// affordance the code panel uses, and a chip carrying the repository link. -class InstallBlock extends StatelessWidget { - /// Creates the install line. - const InstallBlock({ - super.key, - required this.command, - required this.repoLabel, - required this.onCopyCommand, - required this.onCopyRepo, - required this.copied, - }); - - /// The shell command shown, and copied by the Copy chip. - final String command; - - /// Label of the repository chip. - final String repoLabel; - - /// Copies [command]. - final VoidCallback onCopyCommand; - - /// Copies the repository link. - final VoidCallback onCopyRepo; - - /// Whether either confirmation is showing. - final bool copied; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Container( - width: double.infinity, - padding: const EdgeInsets.fromLTRB(16, 12, 12, 12), - decoration: BoxDecoration( - color: t.panel, - borderRadius: BorderRadius.circular(16), - ), - child: Wrap( - crossAxisAlignment: WrapCrossAlignment.center, - alignment: WrapAlignment.spaceBetween, - spacing: 12, - runSpacing: 10, - children: [ - Text( - command, - style: TextStyle( - fontSize: 12, - height: 1.6, - fontFamily: 'Menlo', - fontFamilyFallback: const ['Courier New', 'monospace'], - color: t.codeText, - decoration: TextDecoration.none, - ), - ), - // A Wrap rather than a Row: the actions break onto their own line - // on a narrow layout instead of overflowing. - Wrap( - crossAxisAlignment: WrapCrossAlignment.center, - spacing: 6, - runSpacing: 8, - children: [ - AnimatedOpacity( - opacity: copied ? 1 : 0, - duration: const Duration(milliseconds: 150), - child: Text( - 'Copied', - style: TextStyle( - fontSize: 12, - color: t.muted, - decoration: TextDecoration.none, - ), - ), - ), - DemoChip(label: 'Copy', selected: false, onTap: onCopyCommand), - DemoChip( - label: repoLabel, - selected: false, - onTap: onCopyRepo, - leading: Icon(Icons.link, size: 14, color: t.btnText), - ), - ], - ), - ], - ), - ); - } -} - -/// The playground's code panel: the generated snippet plus a -/// copy-to-clipboard action that confirms in place. -class CodeBlock extends StatelessWidget { - /// Creates the panel. - const CodeBlock({ - super.key, - required this.code, - required this.onCopy, - required this.copied, - }); - - /// Snippet text. - final String code; - - /// Copy action. - final VoidCallback onCopy; - - /// Whether the confirmation is showing. - final bool copied; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Container( - width: double.infinity, - padding: const EdgeInsets.all(16), - decoration: BoxDecoration( - color: t.panel, - borderRadius: BorderRadius.circular(16), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - AnimatedOpacity( - opacity: copied ? 1 : 0, - duration: const Duration(milliseconds: 150), - child: Text( - 'Copied', - style: TextStyle( - fontSize: 12, - color: t.muted, - decoration: TextDecoration.none, - ), - ), - ), - const SizedBox(width: 8), - DemoChip(label: 'Copy', selected: false, onTap: onCopy), - ], - ), - const SizedBox(height: 8), - SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Text( - code, - key: const ValueKey('playground-snippet'), - style: TextStyle( - fontSize: 12, - height: 1.6, - fontFamily: 'Menlo', - fontFamilyFallback: const ['Courier New', 'monospace'], - color: t.codeText, - decoration: TextDecoration.none, - ), - ), - ), - ], - ), - ); - } -} diff --git a/example/lib/src/playground/controls_panel.dart b/example/lib/src/playground/controls_panel.dart deleted file mode 100644 index 6556164..0000000 --- a/example/lib/src/playground/controls_panel.dart +++ /dev/null @@ -1,1080 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; - -import '../demo_theme.dart'; -import 'controls.dart'; -import 'playground_state.dart'; - -/// Every playground control, grouped into collapsible sections. -/// -/// The panel owns no state: it reads [state], hands each edit to [onEdit], -/// and routes the two playback concerns the section owns — swapping a -/// controller in ([onControllerMode]) and driving one ([onControllerAction]) -/// — back up to it. -class ControlsPanel extends StatelessWidget { - /// Creates the panel. - const ControlsPanel({ - super.key, - required this.state, - required this.onEdit, - required this.onControllerMode, - required this.onControllerAction, - }); - - /// The configuration every control reads and writes. - final PlaygroundState state; - - /// Applies a mutation to [state] and rebuilds. - final void Function(VoidCallback mutate) onEdit; - - /// Turns controller mode on or off. - final ValueChanged onControllerMode; - - /// Runs an action against every attached controller. - final void Function(void Function(BorderBeamController)) onControllerAction; - - @override - Widget build(BuildContext context) => Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: _sections(context), - ); - - List _sections(BuildContext context) { - final s = state; - final isLine = s.variant == BeamVariant.line; - final isPulse = s.variant.isPulse; - final isOutside = s.variant == BeamVariant.pulseOutside; - final travels = s.isTraveling; - final ring = s.isRing; - final brightness = DemoTheme.of(context).isDark - ? Brightness.dark - : Brightness.light; - return [ - ControlSection( - title: 'Variant & colors', - initiallyExpanded: true, - children: [ - ControlRow( - label: 'Variant', - child: ChipGroup( - children: [ - for (final entry in _variantLabels.entries) - DemoChip( - label: entry.value, - selected: s.variant == entry.key, - onTap: () => onEdit(() => s.variant = entry.key), - ), - ], - ), - ), - ControlRow( - label: 'Palette', - child: ChipGroup( - children: [ - for (final preset in PalettePreset.values) - DemoChip( - label: preset.label, - selected: s.palette == preset, - onTap: () => onEdit(() => s.palette = preset), - ), - ], - ), - ), - if (s.palette == PalettePreset.custom) ...[ - ControlRow( - label: 'Custom colors', - child: ChipGroup( - children: [ - for (final (i, swatch) in customSwatches.indexed) - DemoChip( - label: swatch.name, - selected: s.customColors.contains(i), - leading: _Dot(color: swatch.color), - onTap: () => onEdit(() => _toggleSwatch(i)), - ), - ], - ), - ), - ControlRow( - label: 'Base', - child: ChipGroup( - children: [ - for (final preset in PalettePreset.presets) - DemoChip( - label: preset.label, - selected: s.customBase == preset, - onTap: () => onEdit(() => s.customBase = preset), - ), - ], - ), - ), - _Hint( - 'The base supplies the blob geometry and the alpha structure ' - 'your colors are distributed over.', - ), - ], - if (s.palette == PalettePreset.seed) ...[ - ControlRow( - label: 'Seed', - child: ChipGroup( - children: [ - for (final (i, swatch) in customSwatches.indexed) - DemoChip( - label: swatch.name, - selected: s.seedColor == i, - leading: _Dot(color: swatch.color), - onTap: () => onEdit(() => s.seedColor = i), - ), - ], - ), - ), - ControlRow( - label: 'Harmony', - child: ChipGroup( - children: [ - for (final entry in _harmonyLabels.entries) - DemoChip( - label: entry.value, - selected: s.seedHarmony == entry.key, - onTap: () => onEdit(() => s.seedHarmony = entry.key), - ), - ], - ), - ), - ], - if (s.palette == PalettePreset.lerp) ...[ - ControlRow( - label: 'From', - child: ChipGroup( - children: [ - for (final preset in PalettePreset.presets) - DemoChip( - label: preset.label, - selected: s.lerpFrom == preset, - onTap: () => onEdit(() => s.lerpFrom = preset), - ), - ], - ), - ), - ControlRow( - label: 'To', - child: ChipGroup( - children: [ - for (final preset in PalettePreset.presets) - DemoChip( - label: preset.label, - selected: s.lerpTo == preset, - onTap: () => onEdit(() => s.lerpTo = preset), - ), - ], - ), - ), - SliderRow( - label: 'Blend', - value: s.lerpT, - min: 0, - max: 1, - onChanged: (v) => onEdit(() => s.lerpT = v), - ), - ], - SliderRow( - label: 'Alpha scale', - value: s.alphaScale, - min: 0, - max: 2, - suffix: '×', - onChanged: (v) => onEdit(() => s.alphaScale = v), - ), - ], - ), - ControlSection( - title: 'Shape', - initiallyExpanded: true, - children: [ - ControlRow( - label: 'Corners', - child: ChipGroup( - children: [ - DemoChip( - label: 'Stadium', - selected: s.stadium, - onTap: () => onEdit(() => s.stadium = !s.stadium), - ), - DemoChip( - label: 'Per corner', - selected: s.perCorner, - onTap: () => onEdit(() => s.perCorner = !s.perCorner), - ), - DemoChip( - label: 'Squircle', - selected: s.superellipse, - onTap: () => onEdit(() => s.superellipse = !s.superellipse), - ), - DemoChip( - label: 'Star contour', - selected: s.contour, - onTap: () => onEdit(() => s.contour = !s.contour), - ), - ], - ), - ), - if (s.contour) - _Hint( - 'A BeamPathContour replaces the rounded rectangle, so the ' - 'radius and squircle toggles stop applying. The mock surface ' - 'keeps its own corners — the beam never reads the child.', - ), - if (!s.stadium && !s.perCorner) - NullableSliderRow( - label: 'Radius', - value: s.radius, - fallback: s.defaultRadius, - min: 0, - max: 48, - suffix: 'px', - enabled: !s.contour, - onChanged: (v) => onEdit(() => s.radius = v), - ), - if (!s.stadium && s.perCorner) ...[ - SliderRow( - label: 'Top left', - value: s.radiusTopLeft, - min: 0, - max: 48, - suffix: 'px', - onChanged: (v) => onEdit(() => s.radiusTopLeft = v), - ), - SliderRow( - label: 'Top right', - value: s.radiusTopRight, - min: 0, - max: 48, - suffix: 'px', - onChanged: (v) => onEdit(() => s.radiusTopRight = v), - ), - SliderRow( - label: 'Bottom right', - value: s.radiusBottomRight, - min: 0, - max: 48, - suffix: 'px', - onChanged: (v) => onEdit(() => s.radiusBottomRight = v), - ), - SliderRow( - label: 'Bottom left', - value: s.radiusBottomLeft, - min: 0, - max: 48, - suffix: 'px', - onChanged: (v) => onEdit(() => s.radiusBottomLeft = v), - ), - ], - SliderRow( - label: 'Border width', - value: s.borderWidth, - min: 0.5, - max: 4, - suffix: 'px', - onChanged: (v) => onEdit(() => s.borderWidth = v), - ), - SliderRow( - label: 'Ring offset', - value: s.ringOffset, - min: -12, - max: 24, - suffix: 'px', - onChanged: (v) => onEdit(() => s.ringOffset = v), - ), - ControlRow( - label: 'Segment', - child: ChipGroup( - children: [ - for (final preset in SegmentPreset.values) - DemoChip( - label: preset.label, - selected: s.segmentPreset == preset, - onTap: () => onEdit(() => s.segmentPreset = preset), - ), - ], - ), - ), - if (s.segmentPreset == SegmentPreset.custom) ...[ - ControlRow( - label: 'Start edge', - child: ChipGroup( - children: [ - for (final entry in _edgeLabels.entries) - DemoChip( - label: entry.value, - selected: s.segmentStartEdge == entry.key, - onTap: () => onEdit(() => s.segmentStartEdge = entry.key), - ), - ], - ), - ), - SliderRow( - label: 'Start t', - value: s.segmentStartT, - min: 0, - max: 1, - onChanged: (v) => onEdit(() => s.segmentStartT = v), - ), - ControlRow( - label: 'End edge', - child: ChipGroup( - children: [ - for (final entry in _edgeLabels.entries) - DemoChip( - label: entry.value, - selected: s.segmentEndEdge == entry.key, - onTap: () => onEdit(() => s.segmentEndEdge = entry.key), - ), - ], - ), - ), - SliderRow( - label: 'End t', - value: s.segmentEndT, - min: 0, - max: 1, - onChanged: (v) => onEdit(() => s.segmentEndT = v), - ), - SliderRow( - label: 'Feather', - value: s.segmentFeather, - min: 0, - max: 120, - suffix: 'px', - onChanged: (v) => onEdit(() => s.segmentFeather = v), - ), - ], - if (isLine && s.segmentPreset == SegmentPreset.off) - ControlRow( - label: 'Edge', - child: ChipGroup( - children: [ - for (final entry in _edgeLabels.entries) - DemoChip( - label: entry.value, - selected: s.edge == entry.key, - onTap: () => onEdit(() => s.edge = entry.key), - ), - ], - ), - ), - if (isLine && s.segmentPreset == SegmentPreset.off) - ControlRow( - label: 'Corner wrap', - child: DemoChip( - label: 'Wrap corners', - selected: s.wrapCorners, - onTap: () => onEdit(() => s.wrapCorners = !s.wrapCorners), - ), - ), - ], - ), - ControlSection( - title: 'Timing', - children: [ - NullableSliderRow( - label: 'Cycle', - value: s.cycleSeconds, - fallback: s.defaultCycleSeconds, - min: 0.5, - max: 8, - suffix: 's', - onChanged: (v) => onEdit(() => s.cycleSeconds = v), - ), - SliderRow( - label: 'Cycle gap', - value: s.cycleGapSeconds, - min: 0, - max: 4, - suffix: 's', - enabled: !isPulse, - onChanged: (v) => onEdit(() => s.cycleGapSeconds = v), - ), - SliderRow( - label: 'Speed', - value: s.speed, - min: 0.25, - max: 4, - suffix: '×', - // A controller owns a single beam's rate; BeamSync owns the - // group's rate even when controller mode remains selected. - enabled: !s.controllerMode || s.syncDemo, - onChanged: (v) => onEdit(() => s.speed = v), - ), - if (travels) ...[ - ControlRow( - label: 'Direction', - child: ChipGroup( - children: [ - for (final entry in _directionLabels.entries) - DemoChip( - label: entry.value, - selected: s.direction == entry.key, - onTap: () => onEdit(() => s.direction = entry.key), - ), - ], - ), - ), - SliderRow( - label: 'Phase offset', - value: s.phaseOffset, - min: 0, - max: 1, - onChanged: (v) => onEdit(() => s.phaseOffset = v), - ), - ControlRow( - label: 'Beams', - child: ChipGroup( - children: [ - for (var count = 1; count <= 4; count++) - DemoChip( - label: '$count', - selected: s.beamCount == count, - onTap: () => onEdit(() => s.beamCount = count), - ), - ], - ), - ), - ], - NullableSliderRow( - label: 'Hue period', - value: s.huePeriodSeconds, - fallback: s.defaultHuePeriodSeconds, - min: 2, - max: 30, - suffix: 's', - onChanged: (v) => onEdit(() => s.huePeriodSeconds = v), - ), - if (isLine) ...[ - SliderRow( - label: 'Breathe', - value: s.breatheFactor, - min: 0.5, - max: 3, - suffix: '×', - onChanged: (v) => onEdit(() => s.breatheFactor = v), - ), - SliderRow( - label: 'Spike', - value: s.spikeFactor, - min: 0.5, - max: 3, - suffix: '×', - onChanged: (v) => onEdit(() => s.spikeFactor = v), - ), - SliderRow( - label: 'Spike 2', - value: s.spike2Factor, - min: 0.5, - max: 3, - suffix: '×', - onChanged: (v) => onEdit(() => s.spike2Factor = v), - ), - ], - ControlRow( - label: 'Hue', - child: ChipGroup( - children: [ - DemoChip( - label: 'Static colors', - selected: s.staticColors, - onTap: () => onEdit(() => s.staticColors = !s.staticColors), - ), - ], - ), - ), - ], - ), - ControlSection( - title: 'Style', - children: [ - SliderRow( - label: 'Strength', - value: s.strength, - min: 0, - max: 1, - onChanged: (v) => onEdit(() => s.strength = v), - ), - NullableSliderRow( - label: 'Brightness', - value: s.brightness, - fallback: s.defaultBrightness(brightness), - min: 0.5, - max: 3, - suffix: '×', - onChanged: (v) => onEdit(() => s.brightness = v), - ), - NullableSliderRow( - label: 'Saturation', - value: s.saturation, - fallback: s.defaultSaturation(brightness), - min: 0.5, - max: 3, - suffix: '×', - onChanged: (v) => onEdit(() => s.saturation = v), - ), - SliderRow( - label: 'Hue range', - value: s.hueRange, - min: 0, - max: 60, - suffix: '°', - // The line variant caps its own hue range at 13°. - enabled: !isPulse, - onChanged: (v) => onEdit(() => s.hueRange = v), - ), - ControlRow( - label: 'Hue mode', - child: ChipGroup( - children: [ - DemoChip( - label: 'Auto', - selected: s.hueMode == null, - onTap: () => onEdit(() => s.hueMode = null), - ), - for (final entry in _hueModeLabels.entries) - DemoChip( - label: entry.value, - selected: s.hueMode == entry.key, - onTap: () => onEdit(() => s.hueMode = entry.key), - ), - ], - ), - ), - SliderRow( - label: 'Hue base', - value: s.hueBase, - min: -180, - max: 180, - suffix: '°', - onChanged: (v) => onEdit(() => s.hueBase = v), - ), - SliderRow( - label: 'Stroke opacity', - value: s.strokeOpacityFactor, - min: 0, - max: 2, - suffix: '×', - onChanged: (v) => onEdit(() => s.strokeOpacityFactor = v), - ), - SliderRow( - label: 'Inner opacity', - value: s.innerOpacityFactor, - min: 0, - max: 2, - suffix: '×', - onChanged: (v) => onEdit(() => s.innerOpacityFactor = v), - ), - SliderRow( - label: 'Bloom opacity', - value: s.bloomOpacityFactor, - min: 0, - max: 2, - suffix: '×', - onChanged: (v) => onEdit(() => s.bloomOpacityFactor = v), - ), - if (ring) - SliderRow( - label: 'Tail length', - value: s.tailLength, - min: 0.5, - max: 2, - suffix: '×', - onChanged: (v) => onEdit(() => s.tailLength = v), - ), - SliderRow( - label: 'Glow spread', - value: s.glowSpread, - min: 0.5, - max: 3, - suffix: '×', - onChanged: (v) => onEdit(() => s.glowSpread = v), - ), - if (travels) - SliderRow( - label: 'Sparkle', - value: s.sparkle, - min: 0, - max: 1, - onChanged: (v) => onEdit(() => s.sparkle = v), - ), - if (ring) - ControlRow( - label: 'Comet', - child: ChipGroup( - children: [ - DemoChip( - label: 'Comet tail', - selected: s.comet, - onTap: () => onEdit(() => s.comet = !s.comet), - ), - ], - ), - ), - if (!isLine) - ControlRow( - label: 'Segments', - child: ChipGroup( - children: [ - DemoChip( - label: 'Off', - selected: s.segments == null, - onTap: () => onEdit(() => s.segments = null), - ), - for (final count in segmentChoices) - DemoChip( - label: '$count', - selected: s.segments == count, - onTap: () => onEdit(() => s.segments = count), - ), - ], - ), - ), - SliderRow( - label: 'Render scale', - value: s.renderScale, - min: 0.25, - max: 1, - suffix: '×', - onChanged: (v) => onEdit(() => s.renderScale = v), - ), - if (s.variant == BeamVariant.pulseInside) - SliderRow( - label: 'Inner size', - value: s.innerSizeScale, - min: 0.5, - max: 2, - suffix: '×', - onChanged: (v) => onEdit(() => s.innerSizeScale = v), - ), - if (isOutside) - ControlRow( - label: 'Recipe', - child: ChipGroup( - children: [ - DemoChip( - label: 'Stock pulse-outside', - selected: s.stockPulseOutside, - onTap: () => onEdit( - () => s.stockPulseOutside = !s.stockPulseOutside, - ), - ), - ], - ), - ), - if (isPulse) - SliderRow( - label: 'Glow boost', - value: s.glowBoost, - min: 0, - max: 3, - suffix: '×', - onChanged: (v) => onEdit(() => s.glowBoost = v), - ), - if (isOutside && s.stockPulseOutside) - _Hint( - 'BeamStyle.pulseOutsideStock is the React library\'s own ' - 'look, before the demo page\'s tuning: a tighter, dimmer halo. ' - 'Anything set here layers over it.', - ), - if (isOutside) ...[ - NullableSliderRow( - label: 'Core blur', - value: s.coreBlur, - fallback: null, - min: 0, - max: 60, - suffix: 'px', - onChanged: (v) => onEdit(() => s.coreBlur = v), - ), - NullableSliderRow( - label: 'Bloom blur', - value: s.bloomBlur, - fallback: null, - min: 0, - max: 120, - suffix: 'px', - onChanged: (v) => onEdit(() => s.bloomBlur = v), - ), - NullableSliderRow( - label: 'Glow brightness', - value: s.glowBrightness, - fallback: null, - min: 0.5, - max: 3, - suffix: '×', - onChanged: (v) => onEdit(() => s.glowBrightness = v), - ), - NullableSliderRow( - label: 'Glow saturation', - value: s.glowSaturation, - fallback: null, - min: 0.5, - max: 3, - suffix: '×', - onChanged: (v) => onEdit(() => s.glowSaturation = v), - ), - ], - ], - ), - ControlSection( - title: 'Playback', - initiallyExpanded: true, - children: [ - ControlRow( - label: 'Mode', - child: ChipGroup( - children: [ - DemoChip( - label: s.active ? 'Active' : 'Inactive', - selected: s.active, - enabled: !s.controllerMode || s.syncDemo, - onTap: () => onEdit(() => s.active = !s.active), - ), - DemoChip( - label: 'Controller', - selected: s.controllerMode, - onTap: () => onControllerMode(!s.controllerMode), - ), - ], - ), - ), - if (s.controllerMode) ...[ - ControlRow( - // A BeamSync group owns its own clock, so the controller has - // no beam to drive while the sync demo is on. - enabled: !s.syncDemo, - label: 'Transport', - child: ChipGroup( - children: [ - for (final entry - in { - 'Start': (c) => c.start(), - 'Pause': (c) => c.pause(), - 'Resume': (c) => c.resume(), - 'Stop': (c) => c.stop(), - 'Pulse': (c) => c.pulse(), - 'Flash': (c) => c.flash(), - }.entries) - DemoChip( - label: entry.key, - selected: false, - onTap: () => onControllerAction(entry.value), - ), - ], - ), - ), - SliderRow( - label: 'Controller speed', - value: s.controllerSpeed, - min: 0.25, - max: 4, - suffix: '×', - enabled: !s.syncDemo, - onChanged: (v) => onEdit(() { - s.controllerSpeed = v; - onControllerAction((c) => c.speed = v); - }), - ), - ] else ...[ - SliderRow( - label: 'Start after', - value: s.startAfterSeconds, - min: 0, - max: 3, - suffix: 's', - enabled: !s.syncDemo, - onChanged: (v) => onEdit(() => s.startAfterSeconds = v), - ), - SliderRow( - label: 'Duration', - value: s.durationSeconds, - min: 0, - max: 15, - suffix: 's', - enabled: !s.syncDemo, - onChanged: (v) => onEdit(() => s.durationSeconds = v), - ), - ], - ControlRow( - enabled: !s.syncDemo, - label: 'Repeat', - child: ChipGroup( - children: [ - for (final entry in _repeatLabels.entries) - DemoChip( - label: entry.value, - selected: s.repeatCycles == entry.key, - onTap: () => onEdit(() => s.repeatCycles = entry.key), - ), - ], - ), - ), - ControlRow( - label: 'Reduced motion', - child: ChipGroup( - children: [ - DemoChip( - label: 'Static frame', - selected: s.reducedMotion == null, - onTap: () => onEdit(() => s.reducedMotion = null), - ), - for (final entry in _reducedMotionLabels.entries) - DemoChip( - label: entry.value, - selected: s.reducedMotion == entry.key, - onTap: () => onEdit(() => s.reducedMotion = entry.key), - ), - ], - ), - ), - ControlRow( - enabled: !s.syncDemo, - label: 'Offscreen', - child: ChipGroup( - children: [ - DemoChip( - label: 'Default', - selected: s.pauseWhenOffscreen == null, - onTap: () => onEdit(() => s.pauseWhenOffscreen = null), - ), - DemoChip( - label: 'Pause offscreen', - selected: s.pauseWhenOffscreen == true, - onTap: () => onEdit(() => s.pauseWhenOffscreen = true), - ), - DemoChip( - label: 'Keep running', - selected: s.pauseWhenOffscreen == false, - onTap: () => onEdit(() => s.pauseWhenOffscreen = false), - ), - ], - ), - ), - ControlRow( - enabled: !s.syncDemo, - label: 'Fade curve', - child: ChipGroup( - children: [ - DemoChip( - label: 'Spring', - selected: !s.cssFadeCurve, - onTap: () => onEdit(() => s.cssFadeCurve = false), - ), - DemoChip( - label: 'CSS ease', - selected: s.cssFadeCurve, - onTap: () => onEdit(() => s.cssFadeCurve = true), - ), - ], - ), - ), - ControlRow( - label: 'Simulate', - child: ChipGroup( - children: [ - DemoChip( - label: 'Simulate reduced motion', - selected: s.simulateReducedMotion, - onTap: () => onEdit( - () => s.simulateReducedMotion = !s.simulateReducedMotion, - ), - ), - ], - ), - ), - _Hint( - 'Static frame is the package default, so it sets no field. ' - 'Simulate wraps the preview in a MediaQuery asking for reduced ' - 'motion — the same signal the platform sends.', - ), - ], - ), - ControlSection( - title: 'Drive', - children: [ - ControlRow( - label: 'Sources', - child: ChipGroup( - children: [ - DemoChip( - label: 'Progress', - selected: s.driveProgress, - onTap: () => onEdit(() => s.driveProgress = !s.driveProgress), - ), - DemoChip( - label: 'Follow pointer', - selected: s.followPointer, - onTap: () => onEdit(() => s.followPointer = !s.followPointer), - ), - DemoChip( - label: 'Strength from signal', - selected: s.strengthSignal, - onTap: () => - onEdit(() => s.strengthSignal = !s.strengthSignal), - ), - ], - ), - ), - if (s.driveProgress) - SliderRow( - // Named for what it sets, so it does not read as a second - // copy of the toggle above it. - label: 'Position', - value: s.progress, - min: 0, - max: 1, - enabled: travels, - onChanged: (v) => onEdit(() => s.progress = v), - ), - _Hint( - travels - ? 'Progress parks the sweep where you put it and follow eases ' - 'it to the pointer, so progress wins where both are on. ' - 'Strength rides a sine wave through a ' - 'strengthListenable, without a rebuild.' - : 'The pulse variants have no travel, so progress and follow ' - 'do nothing here. Strength still rides a sine wave ' - 'through a strengthListenable.', - ), - ], - ), - ControlSection( - title: 'Theme', - children: [ - ControlRow( - label: 'Inheritance', - child: ChipGroup( - children: [ - DemoChip( - label: 'BorderBeamTheme', - selected: s.themeDemo, - onTap: () => onEdit(() => s.themeDemo = !s.themeDemo), - ), - ], - ), - ), - ControlRow( - label: 'Group', - child: ChipGroup( - children: [ - DemoChip( - label: 'BeamSync', - selected: s.syncDemo, - onTap: () => onEdit(() => s.syncDemo = !s.syncDemo), - ), - ], - ), - ), - _Hint( - 'BorderBeamTheme wraps the preview in ocean colors and a ' - 'squircle-20 shape: controls left at their default inherit from ' - 'it, anything you set wins. BeamSync swaps the preview for three ' - 'beams on one clock, a third of a cycle apart.', - ), - ], - ), - ]; - } - - void _toggleSwatch(int index) { - final selected = state.customColors.toList(); - if (selected.contains(index)) { - if (selected.length <= minCustomColors) return; - selected.remove(index); - } else { - if (selected.length >= maxCustomColors) return; - selected.add(index); - } - state.customColors = selected; - } -} - -class _Dot extends StatelessWidget { - const _Dot({required this.color}); - - final Color color; - - @override - Widget build(BuildContext context) => Container( - width: 10, - height: 10, - decoration: BoxDecoration(color: color, shape: BoxShape.circle), - ); -} - -class _Hint extends StatelessWidget { - const _Hint(this.text); - - final String text; - - @override - Widget build(BuildContext context) { - final t = DemoTheme.of(context).tokens; - return Padding( - padding: const EdgeInsets.only(top: 6), - child: Text( - text, - style: TextStyle( - fontSize: 11, - height: 1.5, - color: t.muted, - decoration: TextDecoration.none, - ), - ), - ); - } -} - -const Map _variantLabels = { - BeamVariant.rotate: 'Large', - BeamVariant.small: 'Small', - BeamVariant.line: 'Line', - BeamVariant.pulseInside: 'Pulse Inner', - BeamVariant.pulseOutside: 'Pulse Outside', -}; - -const Map _harmonyLabels = { - BeamSeedHarmony.analogous: 'Analogous', - BeamSeedHarmony.complementary: 'Complementary', - BeamSeedHarmony.triadic: 'Triadic', - BeamSeedHarmony.monochrome: 'Monochrome', -}; - -const Map _edgeLabels = { - BeamEdge.top: 'Top', - BeamEdge.right: 'Right', - BeamEdge.bottom: 'Bottom', - BeamEdge.left: 'Left', -}; - -const Map _directionLabels = { - BeamDirection.forward: 'Forward', - BeamDirection.reverse: 'Reverse', - BeamDirection.bounce: 'Bounce', -}; - -const Map _hueModeLabels = { - BeamHueMode.pingPong: 'Ping-pong', - BeamHueMode.continuous: 'Continuous', -}; - -// Null is the forever default; the two counts are the shapes BeamRepeat -// takes. -const Map _repeatLabels = { - null: 'Forever', - 1: 'Once', - 3: '3 cycles', -}; - -// Static frame is the package default and lives on its own chip, which -// clears the field rather than setting it. -const Map _reducedMotionLabels = { - BeamReducedMotion.hide: 'Hide', - BeamReducedMotion.slow: 'Slow', - BeamReducedMotion.animate: 'Animate', -}; diff --git a/example/lib/src/playground/playground_section.dart b/example/lib/src/playground/playground_section.dart deleted file mode 100644 index 458fc77..0000000 --- a/example/lib/src/playground/playground_section.dart +++ /dev/null @@ -1,239 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/foundation.dart' show kIsWeb; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; - -import '../demo_theme.dart'; -import 'controls.dart'; -import 'controls_panel.dart'; -import 'playground_state.dart'; -import 'preview.dart'; -import 'share_codec.dart'; -import 'snippet.dart'; - -/// The interactive playground: every meaningful knob of the package's API -/// wired to a live preview and a generated snippet. -/// -/// The preview and the snippet are built from the same "only what differs -/// from the package default" rule, so what you read is what you see — with -/// the theme demo on, a control left at its default inherits from the -/// enclosing [BorderBeamTheme] instead. -/// -/// State round-trips through the URL: the current configuration is written -/// to the address bar on the web, and the share button copies a link that -/// reproduces it. -class PlaygroundSection extends StatefulWidget { - /// Const constructor. - const PlaygroundSection({super.key}); - - @override - State createState() => _PlaygroundSectionState(); -} - -// The control column of the two-column layout: wide enough for a slider to -// keep its label, readout, and `auto` chip on one line. -const double _controlsWidth = 420; - -// The install line above the playground. -const String _installCommand = 'flutter pub add flutter_border_beam'; -const String _repoUrl = 'https://github.com/SimplifyJobs/flutter_border_beam'; -const String _repoLabel = 'SimplifyJobs/flutter_border_beam'; - -class _PlaygroundSectionState extends State { - late PlaygroundState _state = _initialState(); - - // One controller per preview: a BorderBeamController may drive only one - // beam at a time, and the wide layout shows two. - final List _controllers = [ - BorderBeamController(), - BorderBeamController(), - ]; - - String? _copied; - Timer? _copiedTimer; - - static PlaygroundState _initialState() { - final encoded = playgroundStateStringFrom(Uri.base); - return encoded == null ? PlaygroundState() : decodePlaygroundState(encoded); - } - - @override - void dispose() { - _copiedTimer?.cancel(); - for (final controller in _controllers) { - controller.dispose(); - } - super.dispose(); - } - - void _edit(VoidCallback mutate) { - setState(mutate); - _publishState(); - } - - // On the web the address bar carries the configuration, so a reload — or a - // copied URL — reproduces it. - void _publishState() { - if (!kIsWeb) return; - final encoded = encodePlaygroundState(_state); - SystemNavigator.routeInformationUpdated( - uri: Uri(path: '/', query: encoded.isEmpty ? null : encoded), - replace: true, - ); - } - - void _controllerDo(void Function(BorderBeamController) action) { - for (final controller in _controllers) { - action(controller); - } - } - - void _setControllerMode(bool enabled) { - _edit(() => _state.controllerMode = enabled); - } - - void _copy(String label, String text) { - unawaited(Clipboard.setData(ClipboardData(text: text))); - setState(() => _copied = label); - _copiedTimer?.cancel(); - _copiedTimer = Timer(const Duration(milliseconds: 1600), () { - if (mounted) setState(() => _copied = null); - }); - } - - String _shareLink() { - final encoded = encodePlaygroundState(_state); - if (!kIsWeb) return playgroundShareUrl(encoded); - final base = Uri.base; - final page = Uri( - scheme: base.scheme, - host: base.host, - port: base.hasPort ? base.port : null, - path: base.path, - ).toString(); - return encoded.isEmpty ? page : '$page#$encoded'; - } - - @override - Widget build(BuildContext context) { - return LayoutBuilder( - builder: (context, constraints) { - // Wide enough for the controls to sit beside the preview instead of - // above it. - final wide = constraints.maxWidth >= 900; - final previewWidth = wide - ? constraints.maxWidth - _controlsWidth - 20 - : constraints.maxWidth; - final previews = PlaygroundPreviews( - state: _state, - controllers: _controllers, - // Both brightnesses fit beside each other once each half still - // holds a readable surface. - bothThemes: previewWidth >= 520, - ); - final controls = ControlsPanel( - state: _state, - onEdit: _edit, - onControllerMode: _setControllerMode, - onControllerAction: _controllerDo, - ); - final snippet = CodeBlock( - code: buildSnippet(_state), - copied: _copied == 'code', - onCopy: () => _copy('code', buildSnippet(_state)), - ); - - final install = InstallBlock( - command: _installCommand, - repoLabel: _repoLabel, - copied: _copied == 'install' || _copied == 'repo', - onCopyCommand: () => _copy('install', _installCommand), - onCopyRepo: () => _copy('repo', _repoUrl), - ); - - if (!wide) { - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - install, - const SizedBox(height: 12), - _toolbar(), - const SizedBox(height: 12), - previews, - const SizedBox(height: 16), - controls, - const SizedBox(height: 8), - snippet, - ], - ); - } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - install, - const SizedBox(height: 12), - _toolbar(), - const SizedBox(height: 12), - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox(width: _controlsWidth, child: controls), - const SizedBox(width: 20), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [previews, const SizedBox(height: 16), snippet], - ), - ), - ], - ), - ], - ); - }, - ); - } - - Widget _toolbar() { - final t = DemoTheme.of(context).tokens; - return Row( - children: [ - Expanded( - child: Text( - 'Every field the beam takes, live.', - style: TextStyle( - fontSize: 12, - color: t.muted, - decoration: TextDecoration.none, - ), - ), - ), - AnimatedOpacity( - opacity: _copied == 'link' ? 1 : 0, - duration: const Duration(milliseconds: 150), - child: Text( - 'Copied', - style: TextStyle( - fontSize: 12, - color: t.muted, - decoration: TextDecoration.none, - ), - ), - ), - const SizedBox(width: 8), - DemoChip( - label: 'Copy share link', - selected: false, - onTap: () => _copy('link', _shareLink()), - ), - const SizedBox(width: 6), - DemoChip( - label: 'Reset', - selected: false, - onTap: () => _edit(() => _state = PlaygroundState()), - ), - ], - ); - } -} diff --git a/example/lib/src/playground/playground_state.dart b/example/lib/src/playground/playground_state.dart deleted file mode 100644 index 161ecf8..0000000 --- a/example/lib/src/playground/playground_state.dart +++ /dev/null @@ -1,720 +0,0 @@ -import 'dart:math' as math; - -import 'package:flutter/material.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; - -/// The palette choices the playground offers: the eleven presets, a -/// user-assembled [BeamColors.custom] list, a [BeamColors.fromSeed] palette -/// derived from one swatch, and a [BeamColors.lerp] blend of two presets. -enum PalettePreset { - /// [BeamColors.colorful] — the package default. - colorful('Colorful', 'colorful', BeamColors.colorful), - - /// [BeamColors.mono]. - mono('Mono', 'mono', BeamColors.mono), - - /// [BeamColors.ocean]. - ocean('Ocean', 'ocean', BeamColors.ocean), - - /// [BeamColors.sunset]. - sunset('Sunset', 'sunset', BeamColors.sunset), - - /// [BeamColors.aurora]. - aurora('Aurora', 'aurora', BeamColors.aurora), - - /// [BeamColors.neon]. - neon('Neon', 'neon', BeamColors.neon), - - /// [BeamColors.candy]. - candy('Candy', 'candy', BeamColors.candy), - - /// [BeamColors.ember]. - ember('Ember', 'ember', BeamColors.ember), - - /// [BeamColors.ice]. - ice('Ice', 'ice', BeamColors.ice), - - /// [BeamColors.gold]. - gold('Gold', 'gold', BeamColors.gold), - - /// [BeamColors.holographic]. - holographic('Holographic', 'holographic', BeamColors.holographic), - - /// Colors picked from [customSwatches]; [colors] is null because the list - /// is built from the playground state. - custom('Custom', 'custom', null), - - /// A palette derived from one swatch through [BeamColors.fromSeed]. - seed('Seed', 'seed', null), - - /// Two presets blended through [BeamColors.lerp]. - lerp('Lerp', 'lerp', null); - - const PalettePreset(this.label, this.id, this.colors); - - /// Chip label. - final String label; - - /// Stable id used by the share codec and the generated snippet. - final String id; - - /// The preset this choice maps to, or null for the three assembled modes - /// ([custom], [seed], [lerp]). - final BeamColors? colors; - - /// The choices that name a package preset — what the lerp endpoints and - /// the custom base are picked from. - static List get presets => - values.where((preset) => preset.colors != null).toList(); -} - -/// One entry of the custom-color picker: a name for the control and the -/// color the snippet emits. -typedef Swatch = ({String name, Color color}); - -/// The fixed palette the custom-colors and seed controls pick from — a small -/// preset list rather than a full color picker, which keeps the state -/// shareable as a handful of indices. -const List customSwatches = [ - (name: 'Pink', color: Color(0xFFFF0080)), - (name: 'Cyan', color: Color(0xFF00E5FF)), - (name: 'Amber', color: Color(0xFFFFC400)), - (name: 'Violet', color: Color(0xFF7C4DFF)), - (name: 'Lime', color: Color(0xFFA6FF00)), - (name: 'Red', color: Color(0xFFFF3D00)), - (name: 'Teal', color: Color(0xFF1DE9B6)), - (name: 'Blue', color: Color(0xFF2979FF)), -]; - -/// Smallest and largest number of colors [BeamColors.custom] may be given -/// from the picker. -const int minCustomColors = 2; - -/// Largest number of colors the custom picker accepts. -const int maxCustomColors = 4; - -/// The dash counts the ring-segments control offers, alongside `off`. -const List segmentChoices = [4, 6, 8, 12, 16]; - -/// Partial-contour choices exposed by the Shape controls. -enum SegmentPreset { - /// The full contour. - off('Off', 'off'), - - /// [BeamSegment.bottomHalf]. - bottomHalf('Bottom half', 'bottomHalf'), - - /// [BeamSegment.topHalf]. - topHalf('Top half', 'topHalf'), - - /// [BeamSegment.leftHalf]. - leftHalf('Left half', 'leftHalf'), - - /// [BeamSegment.rightHalf]. - rightHalf('Right half', 'rightHalf'), - - /// [BeamSegment.bottomEdge]. - bottomEdge('Bottom edge', 'bottomEdge'), - - /// [BeamSegment.topEdge]. - topEdge('Top edge', 'topEdge'), - - /// A segment assembled from the two edge-anchor controls. - custom('Custom', 'custom'); - - const SegmentPreset(this.label, this.id); - - /// Chip label. - final String label; - - /// Stable share-link identifier. - final String id; -} - -/// The five-pointed star the shape section's contour toggle installs, so the -/// playground can show a beam travelling a path that is not a rounded -/// rectangle. -/// -/// The key is what [BeamPathContour] compares on: two contours drawing the -/// same star are one value, which keeps the beam's resolved config out of -/// the rebuild path. -const BeamPathContour starContour = BeamPathContour(_starPath, key: 'star'); - -/// Traces a five-pointed star inscribed in [rect]. -Path _starPath(Rect rect) { - const points = 5; - final center = rect.center; - final outer = rect.shortestSide / 2; - final inner = outer * 0.44; - final path = Path(); - for (var i = 0; i < points * 2; i++) { - final radius = i.isEven ? outer : inner; - // Start at 12 o'clock so the star stands upright. - final angle = -math.pi / 2 + i * math.pi / points; - final point = Offset( - center.dx + radius * math.cos(angle), - center.dy + radius * math.sin(angle), - ); - if (i == 0) { - path.moveTo(point.dx, point.dy); - } else { - path.lineTo(point.dx, point.dy); - } - } - return path..close(); -} - -/// Every knob the playground drives, in one mutable bag. -/// -/// A freshly constructed instance is the "all defaults" configuration: every -/// field holds the value the package would resolve on its own, so the -/// snippet generator and the live preview can both emit *only* what differs -/// from it. Fields whose package default depends on the variant or on a -/// theme preset are nullable, and null means "let the package decide". -class PlaygroundState { - /// Creates the all-defaults state. - PlaygroundState(); - - // ─── Variant & colors ─────────────────────────────────────────────────── - - /// Which effect the preview paints. - BeamVariant variant = BeamVariant.rotate; - - /// Selected palette. - PalettePreset palette = PalettePreset.colorful; - - /// Indices into [customSwatches] used when [palette] is - /// [PalettePreset.custom]. - List customColors = [0, 1]; - - /// The preset whose blob geometry and alpha structure the custom colors - /// are distributed over. - PalettePreset customBase = PalettePreset.colorful; - - /// Index into [customSwatches] of the [BeamColors.fromSeed] brand color. - int seedColor = 7; - - /// How [BeamColors.fromSeed] spreads the seed hue. - BeamSeedHarmony seedHarmony = BeamSeedHarmony.analogous; - - /// First endpoint of a [BeamColors.lerp] palette. - PalettePreset lerpFrom = PalettePreset.ocean; - - /// Second endpoint of a [BeamColors.lerp] palette. - PalettePreset lerpTo = PalettePreset.sunset; - - /// Where the [BeamColors.lerp] blend sits between its endpoints. - double lerpT = 0.5; - - /// Multiplier applied to every palette entry's alpha through - /// [BeamColors.scaleAlpha]. - double alphaScale = 1; - - // ─── Shape ────────────────────────────────────────────────────────────── - - /// Whether the contour is a pill ([BeamShape.stadium]). - bool stadium = false; - - /// Whether the four corners are set individually. - bool perCorner = false; - - /// Uniform corner radius override. Null keeps the variant preset. - double? radius; - - /// Top-left radius in per-corner mode. - double radiusTopLeft = 16; - - /// Top-right radius in per-corner mode. - double radiusTopRight = 16; - - /// Bottom-right radius in per-corner mode. - double radiusBottomRight = 16; - - /// Bottom-left radius in per-corner mode. - double radiusBottomLeft = 16; - - /// Whether the contour uses superellipse corners. - bool superellipse = false; - - /// Stroke ring thickness in logical px. - double borderWidth = 1; - - /// Which edge the line variant's beam rides. - BeamEdge edge = BeamEdge.bottom; - - /// How far the ring sits outside (positive) or inside (negative) the - /// child's bounds, in logical px. - double ringOffset = 0; - - /// Whether the beam travels [starContour] instead of a rounded rectangle. - bool contour = false; - - /// Which part of the contour is visible. - SegmentPreset segmentPreset = SegmentPreset.off; - - /// Edge carrying the custom segment's start anchor. - BeamEdge segmentStartEdge = BeamEdge.right; - - /// Position along [segmentStartEdge]'s clockwise straight run. - double segmentStartT = 0.5; - - /// Edge carrying the custom segment's end anchor. - BeamEdge segmentEndEdge = BeamEdge.left; - - /// Position along [segmentEndEdge]'s clockwise straight run. - double segmentEndT = 0.5; - - /// Fade length at each end of a custom segment, in logical px. - double segmentFeather = 48; - - /// Whether a segment-free line bends around its adjacent corners. - bool wrapCorners = false; - - // ─── Timing ───────────────────────────────────────────────────────────── - - /// Cycle length in seconds; null keeps the variant preset. - double? cycleSeconds; - - /// Rest between sweeps in seconds. - double cycleGapSeconds = 0; - - /// Declarative playback rate. Ignored in [controllerMode]. - double speed = 1; - - /// Which way the beam travels its contour. - BeamDirection direction = BeamDirection.forward; - - /// Fraction of a cycle, 0–1, the timeline starts at. - double phaseOffset = 0; - - /// How many beams travel the contour at once. - int beamCount = 1; - - /// Hue track period in seconds; null keeps the variant preset. - double? huePeriodSeconds; - - /// The line beam's breathe period, as a multiple of the cycle. - double breatheFactor = 1.3; - - /// The line beam's first spike period, as a multiple of the cycle. - double spikeFactor = 1.33; - - /// The line beam's second spike period, as a multiple of the cycle. - double spike2Factor = 1.7; - - /// Whether the hue animation is disabled. - bool staticColors = false; - - // ─── Style ────────────────────────────────────────────────────────────── - - /// Effect opacity, 0–1. - double strength = 1; - - /// Glow brightness multiplier; null keeps the theme preset. - double? brightness; - - /// Glow saturation multiplier; null keeps the theme preset. - double? saturation; - - /// Hue animation amplitude in degrees. - double hueRange = 30; - - /// Whether the hue swings or revolves; null keeps the variant default. - BeamHueMode? hueMode; - - /// Static hue offset in degrees. - double hueBase = 0; - - /// Stroke ring opacity multiplier. - double strokeOpacityFactor = 1; - - /// Inner glow opacity multiplier. - double innerOpacityFactor = 1; - - /// Bloom opacity multiplier. - double bloomOpacityFactor = 1; - - /// Angular width multiplier of the traveling window. - double tailLength = 1; - - /// How far the bloom and halo layers reach past the stroke ring. - double glowSpread = 1; - - /// Whether a soft halo trails the traveling head outside the ring. - bool comet = false; - - /// Density of the twinkles scattered at the traveling head, 0–1. - double sparkle = 0; - - /// Number of dashes the ring is broken into; null keeps it solid. - int? segments; - - /// Multiplier on the size of the pulse-inside inner wash. - double innerSizeScale = 1; - - /// The fraction of the box the beam is painted at before being magnified - /// back up to fill it. - double renderScale = 1; - - /// Whether pulse-outside paints [BeamStyle.pulseOutsideStock] — the React - /// library's own look, before the demo page's tuning — under the fields - /// set here. - bool stockPulseOutside = false; - - /// Pulse glow prominence multiplier. - double glowBoost = 1; - - /// pulse-outside core blur override in px; null keeps the preset. - double? coreBlur; - - /// pulse-outside halo blur override in px; null keeps the preset. - double? bloomBlur; - - /// pulse-outside glow brightness override; null keeps the preset. - double? glowBrightness; - - /// pulse-outside glow saturation override; null keeps the preset. - double? glowSaturation; - - // ─── Playback ─────────────────────────────────────────────────────────── - - /// Declarative play state. Ignored in [controllerMode]. - bool active = true; - - /// How many cycles the beam runs before it fades out; null loops forever. - int? repeatCycles; - - /// What the beam does under reduced motion; null keeps the package - /// default, [BeamReducedMotion.staticFrame]. - BeamReducedMotion? reducedMotion; - - /// Whether the preview is wrapped in a `MediaQuery` asking for reduced - /// motion, so [reducedMotion] can be watched without OS settings. A - /// preview concern only: it reaches neither the beam's fields nor the - /// snippet. - bool simulateReducedMotion = false; - - /// Whether the beam pauses while scrolled out of view. Null keeps the - /// package default (true), while false explicitly opts out. - bool? pauseWhenOffscreen; - - /// Whether the fades run on [BeamPlayback.cssEase] instead of the spring. - bool cssFadeCurve = false; - - /// Whether a [BorderBeamController] drives playback instead of the - /// declarative fields. - bool controllerMode = false; - - /// The controller's playback rate, used in [controllerMode]. - double controllerSpeed = 1; - - /// Autoplay delay in seconds; 0 means none. - double startAfterSeconds = 0; - - /// Total play time in seconds; 0 means forever. - double durationSeconds = 0; - - // ─── Drive ────────────────────────────────────────────────────────────── - - /// Whether `BorderBeam.progress` parks the sweep instead of the clock. - bool driveProgress = false; - - /// Where the driven sweep sits, 0–1. - double progress = 0.35; - - /// Whether the preview feeds pointer position to `BorderBeam.follow`. - bool followPointer = false; - - /// Whether a sine-wave signal drives `BorderBeam.strengthListenable`. - bool strengthSignal = false; - - // ─── Group demos ──────────────────────────────────────────────────────── - - /// Whether the preview sits inside a [BorderBeamTheme] supplying ocean + - /// squircle-20 defaults, so fields left at their default inherit from it. - bool themeDemo = false; - - /// Whether the preview shows three beams under one [BeamSync], each a - /// third of a cycle apart. - bool syncDemo = false; - - // ─── Derived values ───────────────────────────────────────────────────── - - /// The colors this state selects. - BeamColors get beamColors { - final base = switch (palette) { - PalettePreset.custom => BeamColors.custom([ - for (final i in customColors) customSwatches[i].color, - ], base: customBase.colors ?? BeamColors.colorful), - PalettePreset.seed => BeamColors.fromSeed( - customSwatches[seedColor].color, - harmony: seedHarmony, - ), - PalettePreset.lerp => BeamColors.lerp( - lerpFrom.colors ?? BeamColors.colorful, - lerpTo.colors ?? BeamColors.colorful, - lerpT, - ), - _ => palette.colors ?? BeamColors.colorful, - }; - return alphaScale == 1 ? base : base.scaleAlpha(alphaScale); - } - - /// Whether the palette differs from the package default. - bool get hasColors => palette != PalettePreset.colorful || alphaScale != 1; - - /// Whether the variant's beam travels its contour — the family that has a - /// direction, a phase, a head, and a progress to drive. - bool get isTraveling => !variant.isPulse; - - /// Whether the variant sweeps the whole ring, which is what a tail length - /// and a comet halo shape: rotate and small, but not the line beam. - bool get isRing => - variant == BeamVariant.rotate || variant == BeamVariant.small; - - /// The uniform radius the package would resolve on its own. - double get defaultRadius => variant.defaultBorderRadius; - - /// The cycle length in seconds the package would resolve on its own. - double get defaultCycleSeconds => - variant.defaultCycleDuration.inMilliseconds / 1000; - - /// The hue period in seconds the package would resolve on its own — 12s - /// for the traveling variants, and the pulse presets' own periods. - double get defaultHuePeriodSeconds => switch (variant) { - BeamVariant.pulseInside => 16, - BeamVariant.pulseOutside => 14, - _ => 12, - }; - - /// The brightness multiplier the preset carries for [variant] at - /// [themeBrightness]. - double defaultBrightness(Brightness themeBrightness) => - BeamThemeConfig.presetFor(variant, themeBrightness).brightness ?? 1.3; - - /// The saturation multiplier the preset carries for [variant] at - /// [themeBrightness]. - double defaultSaturation(Brightness themeBrightness) => - BeamThemeConfig.presetFor(variant, themeBrightness).saturation; - - /// The corner radii the beam contour uses, per-corner mode included. - /// Stadium corners are infinite and clamped per corner by the ring - /// geometry, which is what makes them track the box. - BorderRadius get borderRadius => stadium - ? const BorderRadius.all(Radius.circular(double.infinity)) - : perCorner - ? BorderRadius.only( - topLeft: Radius.circular(radiusTopLeft), - topRight: Radius.circular(radiusTopRight), - bottomRight: Radius.circular(radiusBottomRight), - bottomLeft: Radius.circular(radiusBottomLeft), - ) - : BorderRadius.circular(radius ?? defaultRadius); - - /// The same contour, sized for a concrete [size] — the preview surface's - /// own decoration needs finite stadium radii. - BorderRadius resolvedBorderRadius(Size size) => stadium - ? BorderRadius.circular( - (size.shortestSide / 2).clamp(0.0, double.maxFinite), - ) - : borderRadius; - - /// Whether the shape differs from what the package would resolve. - bool get hasShape => - stadium || - perCorner || - superellipse || - contour || - radius != null || - borderWidth != 1 || - ringOffset != 0 || - segmentPreset != SegmentPreset.off || - (variant == BeamVariant.line && - segmentPreset == SegmentPreset.off && - (edge != BeamEdge.bottom || wrapCorners)); - - /// The selected partial contour, or null for the full contour. - BeamSegment? get segment => switch (segmentPreset) { - SegmentPreset.off => null, - SegmentPreset.bottomHalf => BeamSegment.bottomHalf, - SegmentPreset.topHalf => BeamSegment.topHalf, - SegmentPreset.leftHalf => BeamSegment.leftHalf, - SegmentPreset.rightHalf => BeamSegment.rightHalf, - SegmentPreset.bottomEdge => BeamSegment.bottomEdge, - SegmentPreset.topEdge => BeamSegment.topEdge, - SegmentPreset.custom => BeamSegment( - start: BeamAnchor.edge(segmentStartEdge, segmentStartT), - end: BeamAnchor.edge(segmentEndEdge, segmentEndT), - feather: segmentFeather, - ), - }; - - // ─── Value objects ────────────────────────────────────────────────────── - - /// The [BeamShape] to hand the widget, or null when nothing differs from - /// the package default. - BeamShape? buildShape() { - if (!hasShape) return null; - final width = borderWidth == 1 ? null : borderWidth; - final se = superellipse ? true : null; - final beamEdge = - variant == BeamVariant.line && - segmentPreset == SegmentPreset.off && - edge != BeamEdge.bottom - ? edge - : null; - final offset = ringOffset == 0 ? null : ringOffset; - final path = contour ? starContour : null; - if (stadium) { - return BeamShape.stadium( - borderWidth: width, - superellipse: se, - edge: beamEdge, - ringOffset: offset, - contour: path, - segment: segment, - wrapCorners: - variant == BeamVariant.line && - segmentPreset == SegmentPreset.off && - wrapCorners - ? true - : null, - ); - } - return BeamShape( - radius: borderRadius, - borderWidth: width, - superellipse: se, - edge: beamEdge, - ringOffset: offset, - contour: path, - segment: segment, - wrapCorners: - variant == BeamVariant.line && - segmentPreset == SegmentPreset.off && - wrapCorners - ? true - : null, - ); - } - - /// The [BeamStyle] to hand the widget, or null when nothing differs. - BeamStyle? buildStyle() { - final style = BeamStyle( - colors: hasColors ? beamColors : null, - strength: strength == 1 ? null : strength, - brightness: brightness, - saturation: saturation, - hueRange: hueRange == 30 ? null : hueRange, - hueMode: hueMode, - hueBase: hueBase == 0 ? null : hueBase, - staticColors: staticColors ? true : null, - strokeOpacityFactor: strokeOpacityFactor == 1 - ? null - : strokeOpacityFactor, - innerOpacityFactor: innerOpacityFactor == 1 ? null : innerOpacityFactor, - bloomOpacityFactor: bloomOpacityFactor == 1 ? null : bloomOpacityFactor, - tailLength: isRing && tailLength != 1 ? tailLength : null, - glowSpread: glowSpread == 1 ? null : glowSpread, - comet: isRing && comet ? true : null, - sparkle: isTraveling && sparkle != 0 ? sparkle : null, - segments: variant == BeamVariant.line ? null : segments, - innerSizeScale: variant == BeamVariant.pulseInside && innerSizeScale != 1 - ? innerSizeScale - : null, - renderScale: renderScale == 1 ? null : renderScale, - glowBoost: variant.isPulse && glowBoost != 1 ? glowBoost : null, - coreBlur: variant == BeamVariant.pulseOutside ? coreBlur : null, - bloomBlur: variant == BeamVariant.pulseOutside ? bloomBlur : null, - glowBrightness: variant == BeamVariant.pulseOutside - ? glowBrightness - : null, - glowSaturation: variant == BeamVariant.pulseOutside - ? glowSaturation - : null, - ); - // The stock look is a whole style, not a field: it goes underneath, so - // anything set here still wins. - if (usesStockPulseOutside) { - return BeamStyle.pulseOutsideStock.merge(style); - } - return style == const BeamStyle() ? null : style; - } - - /// Whether the stock pulse-outside style applies — it is that variant's - /// own recipe, and no other variant reads it. - bool get usesStockPulseOutside => - stockPulseOutside && variant == BeamVariant.pulseOutside; - - /// The [BeamTiming] to hand the widget, or null when nothing differs. - /// - /// The breathe/spike factors belong to the line variant, the travel fields - /// to the traveling ones, and a controller owns the playback rate, so each - /// is dropped where it does not apply. - BeamTiming? buildTiming() { - final isLine = variant == BeamVariant.line; - final timing = BeamTiming( - cycle: cycleSeconds == null ? null : _durationOf(cycleSeconds!), - cycleGap: cycleGapSeconds == 0 ? null : _durationOf(cycleGapSeconds), - speed: speed == 1 || controllerMode ? null : speed, - direction: isTraveling && direction != BeamDirection.forward - ? direction - : null, - phaseOffset: isTraveling && phaseOffset != 0 ? phaseOffset : null, - beamCount: isTraveling && beamCount != 1 ? beamCount : null, - huePeriod: huePeriodSeconds == null - ? null - : _durationOf(huePeriodSeconds!), - breatheFactor: isLine && breatheFactor != 1.3 ? breatheFactor : null, - spikeFactor: isLine && spikeFactor != 1.33 ? spikeFactor : null, - spike2Factor: isLine && spike2Factor != 1.7 ? spike2Factor : null, - ); - return timing == const BeamTiming() ? null : timing; - } - - /// The [BeamPlayback] to hand the widget, or null when nothing differs. - /// - /// A controller owns scheduling exclusively, so `startAfter` and - /// `duration` are dropped alongside one; `repeat` and `reducedMotion` are - /// the beam's own and survive either way. - BeamPlayback? buildPlayback() { - final playback = BeamPlayback( - startAfter: startAfterSeconds == 0 || controllerMode - ? null - : _durationOf(startAfterSeconds), - duration: durationSeconds == 0 || controllerMode - ? null - : _durationOf(durationSeconds), - repeat: buildRepeat(), - reducedMotion: reducedMotion, - pauseWhenOffscreen: pauseWhenOffscreen, - fadeCurve: cssFadeCurve ? BeamPlayback.cssEase : null, - ); - return playback == const BeamPlayback() ? null : playback; - } - - /// The [BeamRepeat] the cycle-count control selects, or null while the - /// beam loops forever. - BeamRepeat? buildRepeat() => switch (repeatCycles) { - null => null, - 1 => const BeamRepeat.once(), - final int n => BeamRepeat.count(n), - }; - - /// The `active:` shorthand, or null when the controller owns playback or - /// the beam is simply on. - bool? buildActive() => controllerMode || active ? null : false; - - /// The `progress:` value, or null while the clock owns the travel — which - /// the pulse variants always do. - double? buildProgress() => driveProgress && isTraveling ? progress : null; - - /// Whether the preview feeds `follow:` a pointer position. - /// - /// `progress` parks the sweep where it says, so a beam driven by one has no - /// travel left for the pointer to pull; the pulse variants never travel. - bool get followsPointer => followPointer && isTraveling && !driveProgress; -} - -Duration _durationOf(double seconds) => - Duration(milliseconds: (seconds * 1000).round()); diff --git a/example/lib/src/playground/preview.dart b/example/lib/src/playground/preview.dart deleted file mode 100644 index 53def27..0000000 --- a/example/lib/src/playground/preview.dart +++ /dev/null @@ -1,363 +0,0 @@ -import 'dart:math' as math; - -import 'package:flutter/material.dart'; -import 'package:flutter/scheduler.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; - -import '../demo_theme.dart'; -import 'playground_state.dart'; - -// The theme the "Theme demo" toggle installs above the preview. -final BorderBeamThemeData _demoThemeData = BorderBeamThemeData( - style: const BeamStyle(colors: BeamColors.ocean), - shape: BeamShape.circular(20, superellipse: true), -); - -// The preview surface, and the frame that gives pulse-outside room to bloom. -const double _surfaceHeight = 128; -const double _maxSurfaceWidth = 320; -const double _frameHeight = 240; - -// The sync demo's three stacked cards. -const int _syncBeams = 3; -const double _syncSurfaceHeight = 52; -const double _syncGap = 14; - -// One full swing of the strength signal. -const Duration _signalPeriod = Duration(milliseconds: 2400); - -class PlaygroundPreviews extends StatelessWidget { - /// Creates the preview area. - const PlaygroundPreviews({ - super.key, - required this.state, - required this.controllers, - required this.bothThemes, - }); - - /// The configuration to render. - final PlaygroundState state; - - /// One controller per preview — a BorderBeamController drives a single - /// beam at a time, and the wide layout shows two. - final List controllers; - - /// Whether to render the dark and light backdrops side by side. - final bool bothThemes; - - @override - Widget build(BuildContext context) { - final isDark = DemoTheme.of(context).isDark; - if (!bothThemes) { - return _Preview( - key: GlobalObjectKey(controllers.first), - state: state, - brightness: isDark ? Brightness.dark : Brightness.light, - controller: controllers.first, - ); - } - return Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: _Preview( - key: GlobalObjectKey(controllers[0]), - state: state, - brightness: Brightness.dark, - controller: controllers[0], - ), - ), - const SizedBox(width: 16), - Expanded( - child: _Preview( - key: GlobalObjectKey(controllers[1]), - state: state, - brightness: Brightness.light, - controller: controllers[1], - ), - ), - ], - ); - } -} - -class _Preview extends StatefulWidget { - const _Preview({ - super.key, - required this.state, - required this.brightness, - required this.controller, - }); - - final PlaygroundState state; - final Brightness brightness; - final BorderBeamController controller; - - @override - State<_Preview> createState() => _PreviewState(); -} - -class _PreviewState extends State<_Preview> - with SingleTickerProviderStateMixin { - // Where the pointer is, in normalized box coordinates, while the Drive - // section's follow toggle is on. - Offset? _follow; - - // The signal behind `strengthListenable`: a sine wave, so the beam breathes - // with something that is neither the clock nor a rebuild. - final ValueNotifier _level = ValueNotifier(1); - late final Ticker _ticker = createTicker(_tick); - late bool _controllerMode = widget.state.controllerMode; - late bool _syncDemo = widget.state.syncDemo; - - @override - void initState() { - super.initState(); - _syncSignal(); - _startAttachedController(); - } - - @override - void didUpdateWidget(_Preview oldWidget) { - super.didUpdateWidget(oldWidget); - _syncSignal(); - if (!widget.state.followsPointer) _follow = null; - if (_controllerMode && !widget.state.controllerMode) { - // Restore a visible clock before BorderBeam detaches the controller; - // otherwise disabling controller mode after Stop leaves a blank beam. - widget.controller.start(); - } - final needsController = - widget.state.controllerMode && - !widget.state.syncDemo && - (!_controllerMode || _syncDemo); - _controllerMode = widget.state.controllerMode; - _syncDemo = widget.state.syncDemo; - if (needsController) _startAttachedController(); - } - - @override - void dispose() { - _ticker.dispose(); - _level.dispose(); - super.dispose(); - } - - void _syncSignal() { - final wanted = widget.state.strengthSignal; - if (wanted == _ticker.isActive) return; - if (wanted) { - _ticker.start(); - } else { - _ticker.stop(); - _level.value = 1; - } - } - - void _tick(Duration elapsed) { - final turns = elapsed.inMicroseconds / _signalPeriod.inMicroseconds; - // 0.15–1, so the bottom of the swing dims the beam rather than killing it. - _level.value = 0.575 + 0.425 * math.sin(turns * 2 * math.pi); - } - - void _startAttachedController() { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted || - !widget.state.controllerMode || - widget.state.syncDemo || - !widget.controller.isAttached) { - return; - } - widget.controller - ..speed = widget.state.controllerSpeed - ..start(); - }); - } - - void _track(Offset local, Size size) { - if (!widget.state.followsPointer) return; - setState(() { - _follow = Offset( - (local.dx / size.width).clamp(0.0, 1.0), - (local.dy / size.height).clamp(0.0, 1.0), - ); - }); - } - - void _release() { - if (_follow == null) return; - setState(() => _follow = null); - } - - @override - Widget build(BuildContext context) { - final state = widget.state; - final dark = widget.brightness == Brightness.dark; - final tokens = dark ? DemoTokens.dark : DemoTokens.light; - - Widget frame(Widget child) => Container( - height: _frameHeight, - decoration: BoxDecoration( - color: dark ? const Color(0xFF101010) : const Color(0xFFF7F7F7), - borderRadius: BorderRadius.circular(24), - ), - alignment: Alignment.center, - child: child, - ); - - return LayoutBuilder( - builder: (context, constraints) { - final width = math.min( - _maxSurfaceWidth, - math.max(120.0, constraints.maxWidth - 56), - ); - Widget content = state.syncDemo - ? _syncGroup(state, tokens, width) - : _single(state, tokens, width); - if (state.themeDemo) { - content = BorderBeamTheme(data: _demoThemeData, child: content); - } - if (state.simulateReducedMotion) { - // The same signal the platform sends, so the reducedMotion chips - // can be watched without touching OS settings. - content = MediaQuery( - data: MediaQuery.of(context).copyWith(disableAnimations: true), - child: content, - ); - } - // BeamTheme.auto reads the ambient brightness, so each preview only - // needs the right Theme above it — no explicit `theme:` field, which - // keeps the generated snippet faithful to what is on screen. - return Theme( - data: ThemeData(brightness: widget.brightness), - child: frame(content), - ); - }, - ); - } - - // The single configured beam, wrapped in a pointer listener while the - // follow toggle is on. - Widget _single(PlaygroundState state, DemoTokens tokens, double width) { - final segmentSide = math.min(width, 200.0); - final size = state.segmentPreset == SegmentPreset.off - ? Size(width, _surfaceHeight) - : Size.square(segmentSide); - final Widget beam = SizedBox( - width: size.width, - height: size.height, - child: BorderBeam( - variant: state.variant, - active: state.buildActive(), - style: state.buildStyle(), - shape: state.buildShape(), - timing: state.buildTiming(), - playback: state.buildPlayback(), - progress: state.buildProgress(), - follow: state.followsPointer ? _follow : null, - strengthListenable: state.strengthSignal ? _level : null, - controller: state.controllerMode ? widget.controller : null, - child: _MockSurface(state: state, tokens: tokens, size: size), - ), - ); - if (!state.followsPointer) return beam; - // The Listener carries touch drags; the MouseRegion adds plain hover, - // which sends no pointer events of its own. - return MouseRegion( - onHover: (event) => _track(event.localPosition, size), - onExit: (_) => _release(), - child: Listener( - onPointerDown: (event) => _track(event.localPosition, size), - onPointerMove: (event) => _track(event.localPosition, size), - onPointerUp: (_) => _release(), - onPointerCancel: (_) => _release(), - child: beam, - ), - ); - } - - // Three beams on one BeamSync clock, evenly spaced around the cycle. - // - // The group owns playback, and a BorderBeamController owns a clock of its - // own, so no controller is attached here. - Widget _syncGroup(PlaygroundState state, DemoTokens tokens, double width) { - final size = Size(width, _syncSurfaceHeight); - final base = state.buildTiming() ?? const BeamTiming(); - return BeamSync( - active: state.active, - speed: state.speed, - reducedMotion: state.reducedMotion ?? BeamReducedMotion.staticFrame, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - for (var i = 0; i < _syncBeams; i++) ...[ - if (i > 0) const SizedBox(height: _syncGap), - SizedBox( - width: width, - height: _syncSurfaceHeight, - child: BorderBeam( - variant: state.variant, - style: state.buildStyle(), - shape: state.buildShape(), - timing: base.copyWith(phaseOffset: i / _syncBeams), - progress: state.buildProgress(), - strengthListenable: state.strengthSignal ? _level : null, - child: _MockSurface( - state: state, - tokens: tokens, - size: size, - label: 'phaseOffset ${(i / _syncBeams).toStringAsFixed(2)}', - ), - ), - ), - ], - ], - ), - ); - } -} - -/// The surface the beam hugs. Its own corners must match the beam contour, -/// theme inheritance included — the beam does not read the child's shape. -class _MockSurface extends StatelessWidget { - const _MockSurface({ - required this.state, - required this.tokens, - required this.size, - this.label = 'Build anything...', - }); - - final PlaygroundState state; - final DemoTokens tokens; - final Size size; - final String label; - - @override - Widget build(BuildContext context) { - // With no shape of its own, the beam inherits the demo theme's squircle - // 20 — so the surface follows it there too. - final inherits = state.themeDemo && !state.hasShape; - final radius = inherits - ? BorderRadius.circular(20) - : state.resolvedBorderRadius(size); - final superellipse = inherits || state.superellipse; - final side = BorderSide(color: tokens.mockBorder); - return Container( - decoration: ShapeDecoration( - color: tokens.mockBg, - shape: superellipse - ? RoundedSuperellipseBorder(borderRadius: radius, side: side) - : RoundedRectangleBorder(borderRadius: radius, side: side), - ), - alignment: Alignment.center, - child: Text( - label, - style: TextStyle( - fontSize: 13, - color: tokens.mockPlaceholder, - decoration: TextDecoration.none, - ), - ), - ); - } -} diff --git a/example/lib/src/playground/share_codec.dart b/example/lib/src/playground/share_codec.dart deleted file mode 100644 index 1f4d43c..0000000 --- a/example/lib/src/playground/share_codec.dart +++ /dev/null @@ -1,365 +0,0 @@ -import 'package:flutter/foundation.dart' show listEquals; -import 'package:flutter_border_beam/flutter_border_beam.dart'; - -import 'playground_state.dart'; - -/// Where the example is published, used for the share link built off the web. -const String playgroundSiteUrl = - 'https://simplifyjobs.github.io/flutter_border_beam/'; - -/// Encodes [state] as a compact `key=value&key=value` string. -/// -/// Only fields that differ from a fresh [PlaygroundState] are written, so the -/// default configuration encodes to the empty string. Every value is plain -/// ASCII (`[A-Za-z0-9.,-]`), so the result needs no percent-escaping in a -/// URL query or fragment. -String encodePlaygroundState(PlaygroundState state) { - final d = PlaygroundState(); - final parts = []; - void put(String key, Object value) => parts.add('$key=$value'); - void number(String key, double value, double fallback) { - if (value != fallback) put(key, _formatNumber(value)); - } - - void optional(String key, double? value) { - if (value != null) put(key, _formatNumber(value)); - } - - void flag(String key, bool value) { - if (value) put(key, 1); - } - - void choice(String key, Enum value, Enum fallback) { - if (value != fallback) put(key, value.name); - } - - void integer(String key, int? value, int? fallback) { - if (value != fallback && value != null) put(key, value); - } - - if (state.variant != d.variant) put('v', _variantIds[state.variant]!); - if (state.palette != d.palette) put('p', state.palette.id); - if (!listEquals(state.customColors, d.customColors)) { - put('cc', state.customColors.join(',')); - } - if (state.customBase != d.customBase) put('pb', state.customBase.id); - integer('sdc', state.seedColor, d.seedColor); - choice('sdh', state.seedHarmony, d.seedHarmony); - if (state.lerpFrom != d.lerpFrom) put('lfa', state.lerpFrom.id); - if (state.lerpTo != d.lerpTo) put('lto', state.lerpTo.id); - number('lt', state.lerpT, d.lerpT); - number('al', state.alphaScale, d.alphaScale); - - flag('st', state.stadium); - flag('pc', state.perCorner); - optional('r', state.radius); - number('rtl', state.radiusTopLeft, d.radiusTopLeft); - number('rtr', state.radiusTopRight, d.radiusTopRight); - number('rbr', state.radiusBottomRight, d.radiusBottomRight); - number('rbl', state.radiusBottomLeft, d.radiusBottomLeft); - flag('se', state.superellipse); - number('bw', state.borderWidth, d.borderWidth); - choice('ed', state.edge, d.edge); - number('ro', state.ringOffset, d.ringOffset); - flag('ct', state.contour); - if (state.segmentPreset != SegmentPreset.off) { - put('sgp', state.segmentPreset.id); - if (state.segmentPreset == SegmentPreset.custom) { - if (state.segmentStartEdge != d.segmentStartEdge || - state.segmentStartT != d.segmentStartT) { - put( - 'sga', - '${state.segmentStartEdge.name},${_formatNumber(state.segmentStartT)}', - ); - } - if (state.segmentEndEdge != d.segmentEndEdge || - state.segmentEndT != d.segmentEndT) { - put( - 'sgb', - '${state.segmentEndEdge.name},${_formatNumber(state.segmentEndT)}', - ); - } - if (state.segmentFeather != d.segmentFeather) { - put('sgf', _formatNumber(state.segmentFeather)); - } - } - } - flag('wc', state.wrapCorners); - - optional('cy', state.cycleSeconds); - number('cg', state.cycleGapSeconds, d.cycleGapSeconds); - number('sp', state.speed, d.speed); - choice('dir', state.direction, d.direction); - number('po', state.phaseOffset, d.phaseOffset); - integer('bc', state.beamCount, d.beamCount); - optional('hp', state.huePeriodSeconds); - number('bf', state.breatheFactor, d.breatheFactor); - number('sf', state.spikeFactor, d.spikeFactor); - number('s2', state.spike2Factor, d.spike2Factor); - flag('sc', state.staticColors); - - number('str', state.strength, d.strength); - optional('br', state.brightness); - optional('sa', state.saturation); - number('hr', state.hueRange, d.hueRange); - if (state.hueMode case final BeamHueMode mode) put('hm', mode.name); - number('hb', state.hueBase, d.hueBase); - number('so', state.strokeOpacityFactor, d.strokeOpacityFactor); - number('io', state.innerOpacityFactor, d.innerOpacityFactor); - number('bo', state.bloomOpacityFactor, d.bloomOpacityFactor); - number('tl', state.tailLength, d.tailLength); - number('gs', state.glowSpread, d.glowSpread); - flag('co', state.comet); - number('sk', state.sparkle, d.sparkle); - integer('sg', state.segments, d.segments); - number('iss', state.innerSizeScale, d.innerSizeScale); - number('rs', state.renderScale, d.renderScale); - flag('pos', state.stockPulseOutside); - number('gb', state.glowBoost, d.glowBoost); - optional('cb', state.coreBlur); - optional('bb', state.bloomBlur); - optional('gbr', state.glowBrightness); - optional('gsa', state.glowSaturation); - - if (!state.active) put('a', 0); - integer('rp', state.repeatCycles, d.repeatCycles); - if (state.reducedMotion case final BeamReducedMotion mode) { - put('rm', mode.name); - } - flag('srm', state.simulateReducedMotion); - if (state.pauseWhenOffscreen case final bool value) { - put('pwo', value ? 1 : 0); - } - flag('fc', state.cssFadeCurve); - flag('cm', state.controllerMode); - number('cs', state.controllerSpeed, d.controllerSpeed); - number('sd', state.startAfterSeconds, d.startAfterSeconds); - number('du', state.durationSeconds, d.durationSeconds); - - flag('dp', state.driveProgress); - number('pr', state.progress, d.progress); - flag('fp', state.followPointer); - flag('ss', state.strengthSignal); - - flag('th', state.themeDemo); - flag('sy', state.syncDemo); - - return parts.join('&'); -} - -/// Decodes an [encodePlaygroundState] string back into a state. -/// -/// Unknown keys, malformed pairs, and out-of-range values are ignored: the -/// corresponding field keeps its default, so a truncated or hand-edited link -/// still opens a usable playground. -PlaygroundState decodePlaygroundState(String encoded) { - final state = PlaygroundState(); - final values = {}; - for (final pair in encoded.split('&')) { - if (pair.isEmpty) continue; - final split = pair.indexOf('='); - if (split <= 0) continue; - values[pair.substring(0, split)] = pair.substring(split + 1); - } - - double? read(String key, double min, double max) { - final raw = values[key]; - if (raw == null) return null; - final parsed = double.tryParse(raw); - if (parsed == null || parsed.isNaN || parsed < min || parsed > max) { - return null; - } - return parsed; - } - - bool? readFlag(String key) => switch (values[key]) { - '1' => true, - '0' => false, - _ => null, - }; - - int? readInt(String key, int min, int max) { - final parsed = int.tryParse(values[key] ?? ''); - if (parsed == null || parsed < min || parsed > max) return null; - return parsed; - } - - T? readEnum(String key, List options) { - final raw = values[key]; - for (final option in options) { - if (option.name == raw) return option; - } - return null; - } - - PalettePreset? readPreset(String key) { - for (final preset in PalettePreset.presets) { - if (preset.id == values[key]) return preset; - } - return null; - } - - ({BeamEdge edge, double t})? readAnchor(String key) { - final parts = values[key]?.split(','); - if (parts == null || parts.length != 2) return null; - BeamEdge? edge; - for (final option in BeamEdge.values) { - if (option.name == parts.first) edge = option; - } - final t = double.tryParse(parts.last); - if (edge == null || t == null || t.isNaN || t < 0 || t > 1) return null; - return (edge: edge, t: t); - } - - for (final entry in _variantIds.entries) { - if (entry.value == values['v']) state.variant = entry.key; - } - for (final preset in PalettePreset.values) { - if (preset.id == values['p']) state.palette = preset; - } - final colors = values['cc']; - if (colors != null) { - final parsed = [ - for (final part in colors.split(',')) - if (int.tryParse(part) case final int i) - if (i >= 0 && i < customSwatches.length) i, - ]; - if (parsed.length >= minCustomColors) { - state.customColors = parsed.take(maxCustomColors).toList(); - } - } - - state.customBase = readPreset('pb') ?? state.customBase; - state.seedColor = - readInt('sdc', 0, customSwatches.length - 1) ?? state.seedColor; - state.seedHarmony = - readEnum('sdh', BeamSeedHarmony.values) ?? state.seedHarmony; - state.lerpFrom = readPreset('lfa') ?? state.lerpFrom; - state.lerpTo = readPreset('lto') ?? state.lerpTo; - state.lerpT = read('lt', 0, 1) ?? state.lerpT; - state.alphaScale = read('al', 0, 2) ?? state.alphaScale; - - state.stadium = readFlag('st') ?? state.stadium; - state.perCorner = readFlag('pc') ?? state.perCorner; - state.radius = read('r', 0, 48) ?? state.radius; - state.radiusTopLeft = read('rtl', 0, 48) ?? state.radiusTopLeft; - state.radiusTopRight = read('rtr', 0, 48) ?? state.radiusTopRight; - state.radiusBottomRight = read('rbr', 0, 48) ?? state.radiusBottomRight; - state.radiusBottomLeft = read('rbl', 0, 48) ?? state.radiusBottomLeft; - state.superellipse = readFlag('se') ?? state.superellipse; - state.borderWidth = read('bw', 0.5, 4) ?? state.borderWidth; - state.edge = readEnum('ed', BeamEdge.values) ?? state.edge; - state.ringOffset = read('ro', -12, 24) ?? state.ringOffset; - state.contour = readFlag('ct') ?? state.contour; - for (final preset in SegmentPreset.values) { - if (preset.id == values['sgp']) state.segmentPreset = preset; - } - if (readAnchor('sga') case final anchor?) { - state.segmentStartEdge = anchor.edge; - state.segmentStartT = anchor.t; - } - if (readAnchor('sgb') case final anchor?) { - state.segmentEndEdge = anchor.edge; - state.segmentEndT = anchor.t; - } - state.segmentFeather = read('sgf', 0, 120) ?? state.segmentFeather; - state.wrapCorners = readFlag('wc') ?? state.wrapCorners; - - state.cycleSeconds = read('cy', 0.5, 8); - state.cycleGapSeconds = read('cg', 0, 4) ?? state.cycleGapSeconds; - state.speed = read('sp', 0.25, 4) ?? state.speed; - state.direction = readEnum('dir', BeamDirection.values) ?? state.direction; - state.phaseOffset = read('po', 0, 1) ?? state.phaseOffset; - state.beamCount = readInt('bc', 1, 4) ?? state.beamCount; - state.huePeriodSeconds = read('hp', 2, 30); - state.breatheFactor = read('bf', 0.5, 3) ?? state.breatheFactor; - state.spikeFactor = read('sf', 0.5, 3) ?? state.spikeFactor; - state.spike2Factor = read('s2', 0.5, 3) ?? state.spike2Factor; - state.staticColors = readFlag('sc') ?? state.staticColors; - - state.strength = read('str', 0, 1) ?? state.strength; - state.brightness = read('br', 0.5, 3); - state.saturation = read('sa', 0.5, 3); - state.hueRange = read('hr', 0, 60) ?? state.hueRange; - state.hueMode = readEnum('hm', BeamHueMode.values); - state.hueBase = read('hb', -180, 180) ?? state.hueBase; - state.strokeOpacityFactor = read('so', 0, 2) ?? state.strokeOpacityFactor; - state.innerOpacityFactor = read('io', 0, 2) ?? state.innerOpacityFactor; - state.bloomOpacityFactor = read('bo', 0, 2) ?? state.bloomOpacityFactor; - state.tailLength = read('tl', 0.5, 2) ?? state.tailLength; - state.glowSpread = read('gs', 0.5, 3) ?? state.glowSpread; - state.comet = readFlag('co') ?? state.comet; - state.sparkle = read('sk', 0, 1) ?? state.sparkle; - final segments = readInt('sg', 2, 64); - state.segments = segmentChoices.contains(segments) ? segments : null; - state.innerSizeScale = read('iss', 0.5, 2) ?? state.innerSizeScale; - state.renderScale = read('rs', 0.25, 1) ?? state.renderScale; - state.stockPulseOutside = readFlag('pos') ?? state.stockPulseOutside; - state.glowBoost = read('gb', 0, 3) ?? state.glowBoost; - state.coreBlur = read('cb', 0, 60); - state.bloomBlur = read('bb', 0, 120); - state.glowBrightness = read('gbr', 0.5, 3); - state.glowSaturation = read('gsa', 0.5, 3); - - state.active = readFlag('a') ?? state.active; - state.repeatCycles = readInt('rp', 1, 99); - state.reducedMotion = readEnum('rm', BeamReducedMotion.values); - state.simulateReducedMotion = readFlag('srm') ?? state.simulateReducedMotion; - state.pauseWhenOffscreen = readFlag('pwo') ?? state.pauseWhenOffscreen; - state.cssFadeCurve = readFlag('fc') ?? state.cssFadeCurve; - state.controllerMode = readFlag('cm') ?? state.controllerMode; - state.controllerSpeed = read('cs', 0.25, 4) ?? state.controllerSpeed; - state.startAfterSeconds = read('sd', 0, 3) ?? state.startAfterSeconds; - state.durationSeconds = read('du', 0, 15) ?? state.durationSeconds; - - state.driveProgress = readFlag('dp') ?? state.driveProgress; - state.progress = read('pr', 0, 1) ?? state.progress; - state.followPointer = readFlag('fp') ?? state.followPointer; - state.strengthSignal = readFlag('ss') ?? state.strengthSignal; - - state.themeDemo = readFlag('th') ?? state.themeDemo; - state.syncDemo = readFlag('sy') ?? state.syncDemo; - - return state; -} - -/// Pulls a playground state string out of [uri]. -/// -/// Three shapes reproduce a configuration, and all three are accepted: the -/// query (`?v=line`), a bare fragment (`#v=line` — the form the share button -/// hands out off the web), and a fragment carrying a route and query -/// (`#/?v=line` — the form Flutter web's hash routing writes back). Returns -/// null when the URL carries no state. -String? playgroundStateStringFrom(Uri uri) { - String? fromFragment(String fragment) { - if (fragment.isEmpty) return null; - final query = fragment.indexOf('?'); - if (query >= 0) return fragment.substring(query + 1); - // A fragment that is only a route path carries no state. - return fragment.startsWith('/') ? null : fragment; - } - - final fragment = fromFragment(uri.fragment); - if (fragment != null && fragment.isNotEmpty) return fragment; - return uri.query.isEmpty ? null : uri.query; -} - -/// The link that reproduces [encoded] on the published example site. -String playgroundShareUrl(String encoded) => - encoded.isEmpty ? playgroundSiteUrl : '$playgroundSiteUrl#$encoded'; - -const Map _variantIds = { - BeamVariant.rotate: 'rotate', - BeamVariant.small: 'small', - BeamVariant.line: 'line', - BeamVariant.pulseInside: 'pulse-inside', - BeamVariant.pulseOutside: 'pulse-outside', -}; - -/// Formats a double as compactly as the two-decimal control resolution -/// allows: `1.5` stays `1.5`, `2.0` becomes `2`. -String _formatNumber(double value) { - final fixed = value.toStringAsFixed(2); - if (!fixed.contains('.')) return fixed; - return fixed.replaceFirst(RegExp(r'\.?0+$'), ''); -} diff --git a/example/lib/src/playground/snippet.dart b/example/lib/src/playground/snippet.dart deleted file mode 100644 index 94e506f..0000000 --- a/example/lib/src/playground/snippet.dart +++ /dev/null @@ -1,363 +0,0 @@ -import 'package:flutter_border_beam/flutter_border_beam.dart'; - -import 'playground_state.dart'; - -/// Builds the Dart snippet that reproduces [state]. -/// -/// Only fields that differ from what the package resolves on its own are -/// emitted, so the default configuration prints the one-liner. The result is -/// paste-able as written: `const` sits on every value object that can carry -/// it, and the two constructions that cannot be const (a runtime-built -/// [BeamShape.circular], and a [BorderBeamThemeData] holding one) are -/// emitted without it. -/// -/// Two things a snippet cannot carry are named rather than pretended: a -/// [BeamPathContour] takes a builder function, so it prints as a commented -/// placeholder, and the values a pointer or a live signal supply print as -/// the variables the surrounding widget would hold. -String buildSnippet(PlaygroundState state) { - final buffer = StringBuffer(); - for (final line in _preamble(state)) { - buffer.writeln(line); - } - if (buffer.isNotEmpty) buffer.writeln(); - - var body = _beam(state); - if (state.syncDemo) { - final beams = [ - for (var i = 0; i < 3; i++) - '${_indent(_beam(state, synced: true, phaseOffset: i / 3), ' ')},', - ].join('\n'); - body = _wrap('BeamSync', [ - if (!state.active) 'active: false,', - if (state.speed != 1) 'speed: ${_num(state.speed)},', - if (state.reducedMotion case final BeamReducedMotion mode) - 'reducedMotion: BeamReducedMotion.${mode.name},', - '// One clock for the group; each beam has its own phase offset.', - ], 'Column(\n children: [\n$beams\n ],\n)'); - } - if (state.themeDemo) { - body = _wrap('BorderBeamTheme', [ - 'data: BorderBeamThemeData(', - ' style: const BeamStyle(colors: BeamColors.ocean),', - ' shape: BeamShape.circular(20, superellipse: true),', - '),', - ], body); - } - return (buffer..write(body)).toString(); -} - -// The declarations the beam's arguments refer to. -List _preamble(PlaygroundState state) => [ - if (state.controllerMode && !state.syncDemo) ...[ - 'final controller = BorderBeamController();', - '// controller.start() / .pause() / .resume() / .stop()', - '// controller.pulse() / .flash()', - '// controller.speed = ${_num(state.controllerSpeed)};', - ], - if (state.strengthSignal) - 'final level = ValueNotifier(1); // drive from your own signal', - if (state.followsPointer && !state.syncDemo) - '// pointer: the normalized pointer position (0–1 on each axis), from a ' - 'MouseRegion or a Listener.', -]; - -// Wraps [child] in [name], with [header] lines above the `child:` argument. -String _wrap(String name, List header, String child) { - final buffer = StringBuffer('$name(\n'); - for (final line in header) { - buffer.writeln(' $line'); - } - return (buffer - ..writeln(' child: ${_indent(child, ' ').trimLeft()},') - ..write(')')) - .toString(); -} - -// The BorderBeam call itself. -String _beam( - PlaygroundState state, { - bool synced = false, - double? phaseOffset, -}) { - final args = []; - - if (state.hasColors) args.add('colors: ${_colors(state)}'); - if (!synced && state.buildActive() == false) args.add('active: false'); - - final shape = _shape(state); - if (shape != null) args.add(shape); - - final style = _style(state); - if (style != null) { - args.add( - state.usesStockPulseOutside - ? 'style: $style' - : 'style: const BeamStyle(\n$style\n )', - ); - } - - final timing = _timing(state, synced: synced, phaseOffset: phaseOffset); - if (timing != null) args.add('timing: const BeamTiming(\n$timing\n )'); - - final playback = _playback(state, synced: synced); - if (playback != null) { - args.add('playback: const BeamPlayback(\n$playback\n )'); - } - - if (state.buildProgress() case final double progress) { - args.add('progress: ${_num(progress)}'); - } - if (state.followsPointer && !synced) args.add('follow: pointer'); - if (state.strengthSignal) args.add('strengthListenable: level'); - - if (state.controllerMode && !synced) args.add('controller: controller'); - args.add('child: child'); - - final name = _constructorNames[state.variant]!; - return 'BorderBeam.$name(\n ${args.join(',\n ')},\n)'; -} - -String _colors(PlaygroundState state) { - final base = switch (state.palette) { - PalettePreset.custom => _customColors(state), - PalettePreset.seed => _seedColors(state), - PalettePreset.lerp => - 'const BeamColors.lerp(${_preset(state.lerpFrom)}, ' - '${_preset(state.lerpTo)}, ${_num(state.lerpT)})', - _ => _preset(state.palette), - }; - return state.alphaScale == 1 - ? base - : '$base.scaleAlpha(${_num(state.alphaScale)})'; -} - -String _preset(PalettePreset preset) => - 'BeamColors.' - '${preset.colors == null ? PalettePreset.colorful.id : preset.id}'; - -String _customColors(PlaygroundState state) { - final colors = [ - for (final i in state.customColors) - _color(customSwatches[i].color.toARGB32()), - ]; - final base = state.customBase == PalettePreset.colorful - ? '' - : ', base: ${_preset(state.customBase)}'; - return 'const BeamColors.custom([${colors.join(', ')}]$base)'; -} - -String _seedColors(PlaygroundState state) { - final harmony = state.seedHarmony == BeamSeedHarmony.analogous - ? '' - : ', harmony: BeamSeedHarmony.${state.seedHarmony.name}'; - final seed = _color(customSwatches[state.seedColor].color.toARGB32()); - return 'const BeamColors.fromSeed($seed$harmony)'; -} - -String _color(int argb) => - 'Color(0x${argb.toRadixString(16).toUpperCase().padLeft(8, '0')})'; - -// The `borderRadius:` shorthand when a plain radius is all that changed, -// otherwise a full BeamShape. `BeamShape.all` stores the radius as a number -// instead of building a BorderRadius, which is what keeps it const. -String? _shape(PlaygroundState state) { - if (!state.hasShape) return null; - final isLine = state.variant == BeamVariant.line; - final extras = [ - if (state.borderWidth != 1) 'borderWidth: ${_num(state.borderWidth)}', - if (state.superellipse) 'superellipse: true', - if (isLine && - state.segmentPreset == SegmentPreset.off && - state.edge != BeamEdge.bottom) - 'edge: BeamEdge.${state.edge.name}', - if (state.ringOffset != 0) 'ringOffset: ${_num(state.ringOffset)}', - if (state.segmentPreset != SegmentPreset.off) 'segment: ${_segment(state)}', - if (isLine && state.segmentPreset == SegmentPreset.off && state.wrapCorners) - 'wrapCorners: true', - ]; - final contour = state.contour ? _contourPlaceholder : null; - - if (state.perCorner && !state.stadium) { - final radii = [ - 'topLeft: Radius.circular(${_num(state.radiusTopLeft)})', - 'topRight: Radius.circular(${_num(state.radiusTopRight)})', - 'bottomRight: Radius.circular(${_num(state.radiusBottomRight)})', - 'bottomLeft: Radius.circular(${_num(state.radiusBottomLeft)})', - ]; - return _shapeBlock('const BeamShape', [ - 'radius: BorderRadius.only(\n ${radii.join(',\n ')},\n ),', - for (final field in extras) '$field,', - ?contour, - ]); - } - - final head = state.stadium - ? 'const BeamShape.stadium' - : 'const BeamShape.all'; - final radius = state.radius ?? state.defaultRadius; - final positional = state.stadium ? [] : [_num(radius)]; - if (contour != null) { - return _shapeBlock(head, [ - for (final field in [...positional, ...extras]) '$field,', - contour, - ]); - } - if (!state.stadium && extras.isEmpty) { - return 'borderRadius: ${_num(radius)}'; - } - return 'shape: $head(${[...positional, ...extras].join(', ')})'; -} - -String _segment(PlaygroundState state) => switch (state.segmentPreset) { - SegmentPreset.off => throw StateError('Off has no BeamSegment'), - SegmentPreset.custom => - 'BeamSegment(start: ${_edgeAnchor(state.segmentStartEdge, state.segmentStartT)}, ' - 'end: ${_edgeAnchor(state.segmentEndEdge, state.segmentEndT)}, ' - 'feather: ${_num(state.segmentFeather)})', - final SegmentPreset preset => 'BeamSegment.${preset.id}', -}; - -String _edgeAnchor(BeamEdge edge, double t) => t == 0.5 - ? 'BeamAnchor.edge(BeamEdge.${edge.name})' - : 'BeamAnchor.edge(BeamEdge.${edge.name}, ${_num(t)})'; - -// A BeamPathContour takes a builder, which a generated snippet cannot write -// for you — the placeholder names the field and the key it compares on. -const String _contourPlaceholder = - "// contour: BeamPathContour(builder: yourPath, key: 'star'),"; - -String _shapeBlock(String head, List lines) => - 'shape: $head(\n ${lines.join('\n ')}\n )'; - -String? _style(PlaygroundState state) { - final isPulse = state.variant.isPulse; - final isOutside = state.variant == BeamVariant.pulseOutside; - // The four glow overrides only reach the painter on pulse-outside. - final coreBlur = isOutside ? state.coreBlur : null; - final bloomBlur = isOutside ? state.bloomBlur : null; - final glowBrightness = isOutside ? state.glowBrightness : null; - final glowSaturation = isOutside ? state.glowSaturation : null; - final segments = state.variant == BeamVariant.line ? null : state.segments; - final fields = [ - if (state.strength != 1) 'strength: ${_num(state.strength)}', - if (state.brightness case final double v) 'brightness: ${_num(v)}', - if (state.saturation case final double v) 'saturation: ${_num(v)}', - if (state.hueRange != 30) 'hueRange: ${_num(state.hueRange)}', - if (state.hueMode case final BeamHueMode v) - 'hueMode: BeamHueMode.${v.name}', - if (state.hueBase != 0) 'hueBase: ${_num(state.hueBase)}', - if (state.staticColors) 'staticColors: true', - if (state.strokeOpacityFactor != 1) - 'strokeOpacityFactor: ${_num(state.strokeOpacityFactor)}', - if (state.innerOpacityFactor != 1) - 'innerOpacityFactor: ${_num(state.innerOpacityFactor)}', - if (state.bloomOpacityFactor != 1) - 'bloomOpacityFactor: ${_num(state.bloomOpacityFactor)}', - if (state.isRing && state.tailLength != 1) - 'tailLength: ${_num(state.tailLength)}', - if (state.glowSpread != 1) 'glowSpread: ${_num(state.glowSpread)}', - if (state.isRing && state.comet) 'comet: true', - if (state.isTraveling && state.sparkle != 0) - 'sparkle: ${_num(state.sparkle)}', - if (segments case final int v) 'segments: $v', - if (state.variant == BeamVariant.pulseInside && state.innerSizeScale != 1) - 'innerSizeScale: ${_num(state.innerSizeScale)}', - if (state.renderScale != 1) 'renderScale: ${_num(state.renderScale)}', - if (isPulse && state.glowBoost != 1) 'glowBoost: ${_num(state.glowBoost)}', - if (coreBlur case final double v) 'coreBlur: ${_num(v)}', - if (bloomBlur case final double v) 'bloomBlur: ${_num(v)}', - if (glowBrightness case final double v) 'glowBrightness: ${_num(v)}', - if (glowSaturation case final double v) 'glowSaturation: ${_num(v)}', - ]; - if (state.usesStockPulseOutside) { - // The stock look is a whole style; merge layers the fields set here - // over it, which is what the preview does too. - return fields.isEmpty - ? _stockStyle - : '$_stockStyle.merge(\n const BeamStyle(\n ' - '${fields.join(',\n ')},\n ),\n )'; - } - return fields.isEmpty ? null : ' ${fields.join(',\n ')},'; -} - -const String _stockStyle = 'BeamStyle.pulseOutsideStock'; - -String? _timing( - PlaygroundState state, { - bool synced = false, - double? phaseOffset, -}) { - final isLine = state.variant == BeamVariant.line; - final travels = state.isTraveling; - final fields = [ - if (state.cycleSeconds case final double v) 'cycle: ${_duration(v)}', - if (state.cycleGapSeconds != 0) - 'cycleGap: ${_duration(state.cycleGapSeconds)}', - if (state.speed != 1 && !state.controllerMode && !synced) - 'speed: ${_num(state.speed)}', - if (travels && state.direction != BeamDirection.forward) - 'direction: BeamDirection.${state.direction.name}', - if (travels && (phaseOffset ?? state.phaseOffset) != 0) - 'phaseOffset: ${_num(phaseOffset ?? state.phaseOffset)}', - if (travels && state.beamCount != 1) 'beamCount: ${state.beamCount}', - if (state.huePeriodSeconds case final double v) - 'huePeriod: ${_duration(v)}', - if (isLine && state.breatheFactor != 1.3) - 'breatheFactor: ${_num(state.breatheFactor)}', - if (isLine && state.spikeFactor != 1.33) - 'spikeFactor: ${_num(state.spikeFactor)}', - if (isLine && state.spike2Factor != 1.7) - 'spike2Factor: ${_num(state.spike2Factor)}', - ]; - return fields.isEmpty ? null : ' ${fields.join(',\n ')},'; -} - -String? _playback(PlaygroundState state, {bool synced = false}) { - if (synced) return null; - // A controller owns scheduling exclusively; repeat and reduced motion stay - // the beam's own either way. - final scheduled = !state.controllerMode; - final fields = [ - if (scheduled && state.startAfterSeconds != 0) - 'startAfter: ${_duration(state.startAfterSeconds)}', - if (scheduled && state.durationSeconds != 0) - 'duration: ${_duration(state.durationSeconds)}', - if (state.repeatCycles case final int cycles) 'repeat: ${_repeat(cycles)}', - if (state.reducedMotion case final BeamReducedMotion v) - 'reducedMotion: BeamReducedMotion.${v.name}', - if (state.pauseWhenOffscreen case final bool value) - 'pauseWhenOffscreen: $value', - if (state.cssFadeCurve) 'fadeCurve: BeamPlayback.cssEase', - ]; - return fields.isEmpty ? null : ' ${fields.join(',\n ')},'; -} - -String _repeat(int cycles) => - cycles == 1 ? 'BeamRepeat.once()' : 'BeamRepeat.count($cycles)'; - -String _duration(double seconds) { - final ms = (seconds * 1000).round(); - return ms % 1000 == 0 - ? 'Duration(seconds: ${ms ~/ 1000})' - : 'Duration(milliseconds: $ms)'; -} - -/// Formats a double the way a hand-written argument would read: `2` rather -/// than `2.0`, `1.33` kept at the control's resolution. -String _num(double value) { - final fixed = value.toStringAsFixed(2); - if (!fixed.contains('.')) return fixed; - return fixed.replaceFirst(RegExp(r'\.?0+$'), ''); -} - -String _indent(String source, String prefix) => - source.split('\n').map((line) => '$prefix$line').join('\n'); - -const Map _constructorNames = { - BeamVariant.rotate: 'rotate', - BeamVariant.small: 'small', - BeamVariant.line: 'line', - BeamVariant.pulseInside: 'pulseInside', - BeamVariant.pulseOutside: 'pulseOutside', -}; diff --git a/example/lib/src/surfaces.dart b/example/lib/src/surfaces.dart new file mode 100644 index 0000000..1c278ef --- /dev/null +++ b/example/lib/src/surfaces.dart @@ -0,0 +1,285 @@ +import 'dart:math' as math; + +import 'package:material_ui/material_ui.dart'; + +import 'tokens.dart'; + +/// The quiet, realistic surfaces the beams wrap — one per effect, each the +/// kind of widget that effect is for. Purely presentational; every one +/// takes its [width] from the stage. + +/// A continuous-corner (superellipse) shape of [radius], the way iOS rounds +/// its surfaces. The beams around these surfaces use the same corners +/// (`BeamShape(superellipse: true)`), so the light sits on the edge. +RoundedSuperellipseBorder squircle(double radius, {Color? side}) => + RoundedSuperellipseBorder( + borderRadius: BorderRadius.circular(radius), + side: side == null ? BorderSide.none : BorderSide(color: side), + ); + +ShapeDecoration _box(Tokens t, double radius) => ShapeDecoration( + color: t.surface, + shape: squircle(radius, side: t.surfaceLine), +); + +TextStyle _text(Color color, {double size = 13, FontWeight? weight}) => + TextStyle( + fontSize: size, + height: 1.25, + fontWeight: weight, + color: color, + letterSpacing: -0.1, + ); + +/// The corner radius the card-shaped surfaces share. +const double surfaceRadius = 20; + +/// An agent's task list — the card `rotate` laps. +class TaskCard extends StatelessWidget { + /// Creates the card. + const TaskCard({super.key, required this.width}); + + /// Laid-out width. + final double width; + + static const _tasks = [ + 'Generate colour palettes', + 'Recommend font pairings', + 'Create layout templates', + 'Build the section engine', + ]; + + @override + Widget build(BuildContext context) { + final t = Tokens.of(context); + return Container( + width: width, + decoration: _box(t, surfaceRadius), + padding: const EdgeInsets.fromLTRB(20, 18, 20, 22), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + ShimmerText('Working…', base: t.placeholder, highlight: t.text), + const SizedBox(height: 22), + for (final (i, task) in _tasks.indexed) ...[ + if (i > 0) const SizedBox(height: 18), + Row( + children: [ + i < 2 + ? Icon(Icons.check_circle, size: 16, color: t.icon) + : CustomPaint( + size: const Size.square(16), + painter: _DashedCircle(t.icon), + ), + const SizedBox(width: 12), + Expanded( + child: Text( + task, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _text(i < 2 ? t.placeholder : t.surfaceText), + ), + ), + ], + ), + ], + ], + ), + ); + } +} + +/// A chat composer — the input `line` rides the bottom edge of. +class Composer extends StatelessWidget { + /// Creates the composer. + const Composer({super.key, required this.width}); + + /// Laid-out width. + final double width; + + @override + Widget build(BuildContext context) { + final t = Tokens.of(context); + Widget chip(String label) => Container( + height: 26, + padding: const EdgeInsets.only(left: 9, right: 5), + decoration: ShapeDecoration( + color: t.chip, + shape: squircle(13, side: t.chipLine), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(label, style: _text(t.surfaceText, size: 12)), + Icon(Icons.keyboard_arrow_down, size: 16, color: t.icon), + ], + ), + ); + return Container( + width: width, + height: 140, + decoration: _box(t, surfaceRadius), + padding: const EdgeInsets.fromLTRB(16, 16, 10, 10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Build anything…', style: _text(t.placeholder, size: 15)), + const Spacer(), + Row( + children: [ + chip('Agent'), + const SizedBox(width: 6), + chip('Auto'), + const Spacer(), + // Empty input, so the send button rests. + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: t.chip, + shape: BoxShape.circle, + border: Border.all(color: t.chipLine), + ), + child: Icon(Icons.arrow_upward, size: 18, color: t.icon), + ), + ], + ), + ], + ), + ); + } +} + +/// An assistant mid-answer — the "thinking" state `pulse` breathes in. +class ThinkingCard extends StatelessWidget { + /// Creates the card. + const ThinkingCard({super.key, required this.width}); + + /// Laid-out width. + final double width; + + @override + Widget build(BuildContext context) { + final t = Tokens.of(context); + return Container( + width: width, + decoration: _box(t, surfaceRadius), + padding: const EdgeInsets.fromLTRB(18, 18, 18, 22), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Container( + width: 28, + height: 28, + decoration: BoxDecoration( + color: t.chip, + shape: BoxShape.circle, + border: Border.all(color: t.chipLine), + ), + child: Icon(Icons.auto_awesome, size: 14, color: t.icon), + ), + const SizedBox(width: 10), + ShimmerText('Thinking', base: t.placeholder, highlight: t.text), + ], + ), + const SizedBox(height: 20), + for (final fraction in const [1.0, 0.88, 0.56]) ...[ + FractionallySizedBox( + widthFactor: fraction, + child: Container( + height: 8, + decoration: ShapeDecoration(color: t.chip, shape: squircle(4)), + ), + ), + const SizedBox(height: 10), + ], + ], + ), + ); + } +} + +/// A loading label with a highlight sweeping across it. +class ShimmerText extends StatefulWidget { + /// Creates the label. + const ShimmerText( + this.text, { + super.key, + required this.base, + required this.highlight, + }); + + /// The label. + final String text; + + /// Resting colour. + final Color base; + + /// The colour of the sweep. + final Color highlight; + + @override + State createState() => _ShimmerTextState(); +} + +class _ShimmerTextState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _sweep = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 2000), + )..repeat(); + + @override + void dispose() { + _sweep.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => AnimatedBuilder( + animation: _sweep, + builder: (context, child) { + final x = 1 - _sweep.value * 2; // sweeps left to right + return ShaderMask( + shaderCallback: (bounds) => LinearGradient( + begin: Alignment(-x - 1, 0), + end: Alignment(-x + 1, 0), + colors: [widget.base, widget.highlight, widget.base], + ).createShader(bounds), + child: child, + ); + }, + child: Text( + widget.text, + style: _text(widget.base, size: 14, weight: FontWeight.w500), + ), + ); +} + +class _DashedCircle extends CustomPainter { + const _DashedCircle(this.color); + + final Color color; + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = 1.5 + ..strokeCap = StrokeCap.round; + final rect = (Offset.zero & size).deflate(1); + const dashes = 8; + const sweep = 2 * math.pi / dashes; + for (var i = 0; i < dashes; i++) { + canvas.drawArc(rect, i * sweep, sweep * 0.55, false, paint); + } + } + + @override + bool shouldRepaint(_DashedCircle oldDelegate) => oldDelegate.color != color; +} diff --git a/example/lib/src/tokens.dart b/example/lib/src/tokens.dart new file mode 100644 index 0000000..43f02c3 --- /dev/null +++ b/example/lib/src/tokens.dart @@ -0,0 +1,148 @@ +import 'package:material_ui/material_ui.dart'; + +/// The example's colours, after the original border-beam demo's design +/// tokens. A [ThemeExtension], so `MaterialApp` cross-fades between the dark +/// and light sets when the theme flips. +@immutable +class Tokens extends ThemeExtension { + /// Creates a token set. + const Tokens({ + required this.bg, + required this.spot, + required this.text, + required this.muted, + required this.faint, + required this.track, + required this.thumb, + required this.surface, + required this.surfaceLine, + required this.chip, + required this.chipLine, + required this.surfaceText, + required this.placeholder, + required this.icon, + }); + + /// Dark tokens — the default. + static const dark = Tokens( + bg: Color(0xFF070707), + spot: Color(0xFF111111), + text: Color(0xFFFBFBFB), + muted: Color(0x99FBFBFB), + faint: Color(0x4DFBFBFB), + track: Color(0xFF141414), + thumb: Color(0xFF2C2C2C), + surface: Color(0xFF161616), + surfaceLine: Color(0xFF242629), + chip: Color(0x0DFFFFFF), + chipLine: Color(0x0AFFFFFF), + surfaceText: Color(0xFFC0C0C0), + placeholder: Color(0xFF5A5A5A), + icon: Color(0xFF808388), + ); + + /// Light tokens. + static const light = Tokens( + bg: Color(0xFFF7F7F8), + spot: Color(0xFFFFFFFF), + text: Color(0xFF111114), + muted: Color(0xFF6B6B78), + faint: Color(0xFFA5A5AE), + track: Color(0xFFECECEF), + thumb: Color(0xFFFFFFFF), + surface: Color(0xFFFFFFFF), + surfaceLine: Color(0xFFE2E2E8), + chip: Color(0x0A111111), + chipLine: Color(0x0D000000), + surfaceText: Color(0xFF3A3A48), + placeholder: Color(0xFF9A9AA4), + icon: Color(0xFF6B6E76), + ); + + /// Page background. + final Color bg; + + /// The centre of the stage's spotlight. + final Color spot; + + /// Primary text. + final Color text; + + /// Secondary text. + final Color muted; + + /// Hints and code. + final Color faint; + + /// Control tracks. + final Color track; + + /// The selected segment of a control. + final Color thumb; + + /// The mock surfaces the beams wrap. + final Color surface; + + /// The surfaces' 1px ring. + final Color surfaceLine; + + /// Chips and skeleton bars inside a surface. + final Color chip; + + /// Chip hairlines. + final Color chipLine; + + /// Body text inside a surface. + final Color surfaceText; + + /// Placeholder text inside a surface. + final Color placeholder; + + /// Glyphs inside a surface. + final Color icon; + + /// The tokens of the ambient theme. + static Tokens of(BuildContext context) => + Theme.of(context).extension()!; + + @override + Tokens copyWith() => this; + + @override + Tokens lerp(Tokens? other, double t) { + if (other == null) return this; + Color mix(Color a, Color b) => Color.lerp(a, b, t)!; + return Tokens( + bg: mix(bg, other.bg), + spot: mix(spot, other.spot), + text: mix(text, other.text), + muted: mix(muted, other.muted), + faint: mix(faint, other.faint), + track: mix(track, other.track), + thumb: mix(thumb, other.thumb), + surface: mix(surface, other.surface), + surfaceLine: mix(surfaceLine, other.surfaceLine), + chip: mix(chip, other.chip), + chipLine: mix(chipLine, other.chipLine), + surfaceText: mix(surfaceText, other.surfaceText), + placeholder: mix(placeholder, other.placeholder), + icon: mix(icon, other.icon), + ); + } +} + +/// The app theme for [brightness]: Material only as a carrier for [Tokens] +/// and the platform's type, with ripples off. +ThemeData buildTheme(Brightness brightness) { + final tokens = brightness == Brightness.dark ? Tokens.dark : Tokens.light; + return ThemeData( + brightness: brightness, + scaffoldBackgroundColor: tokens.bg, + splashFactory: NoSplash.splashFactory, + highlightColor: Colors.transparent, + extensions: [tokens], + ); +} + +/// A strong ease-out for things that respond to a tap. +const Curve easeOut = Cubic(0.23, 1, 0.32, 1); diff --git a/example/pubspec.lock b/example/pubspec.lock index 8636d13..52a87ee 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -29,10 +29,10 @@ packages: dependency: transitive description: name: clock - sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e url: "https://pub.dev" source: hosted - version: "1.1.2" + version: "1.1.3" collection: dependency: transitive description: @@ -41,6 +41,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.1" + cupertino_ui: + dependency: transitive + description: + name: cupertino_ui + sha256: c3eaf7f5bdfee36deb0b14a4cbf7602f1b6b8d8b8576b81f38fc08c25881c94c + url: "https://pub.dev" + source: hosted + version: "1.1.7" fake_async: dependency: transitive description: @@ -60,7 +68,7 @@ packages: path: ".." relative: true source: path - version: "0.1.0" + version: "0.2.0" flutter_lints: dependency: "direct dev" description: @@ -69,11 +77,24 @@ packages: url: "https://pub.dev" source: hosted version: "6.0.0" + flutter_localizations: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" flutter_test: dependency: "direct dev" description: flutter source: sdk version: "0.0.0" + intl: + dependency: transitive + description: + name: intl + sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867" + url: "https://pub.dev" + source: hosted + version: "0.20.3" leak_tracker: dependency: transitive description: @@ -106,14 +127,22 @@ packages: url: "https://pub.dev" source: hosted version: "6.1.0" + listen: + dependency: transitive + description: + name: listen + sha256: "47501a08016a43fcad79252439d723f50f14f88fa7bfd8a177e0a417e5c9e1f2" + url: "https://pub.dev" + source: hosted + version: "1.0.1" 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: @@ -122,14 +151,22 @@ packages: url: "https://pub.dev" source: hosted version: "0.13.0" + material_ui: + dependency: "direct main" + description: + name: material_ui + sha256: a6b19012df437a356cbc01f8ea22a105e07194c47c9a6009da0032a0ce35c4ab + url: "https://pub.dev" + source: hosted + version: "1.11.1" meta: dependency: transitive description: name: meta - sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "1.18.0" + version: "1.19.0" path: dependency: transitive description: @@ -155,10 +192,10 @@ packages: dependency: transitive description: name: stack_trace - sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" url: "https://pub.dev" source: hosted - version: "1.12.1" + version: "1.12.2" stream_channel: dependency: transitive description: @@ -187,18 +224,18 @@ packages: dependency: transitive description: name: test_api - sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" + sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f" url: "https://pub.dev" source: hosted - version: "0.7.11" + version: "0.7.14" 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: @@ -208,5 +245,5 @@ packages: source: hosted version: "15.2.0" sdks: - dart: ">=3.10.0-0 <4.0.0" - flutter: ">=3.35.0" + dart: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 795c783..20174e8 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -1,19 +1,21 @@ name: flutter_border_beam_example description: >- - Gallery and interactive playground for the flutter_border_beam package, - plus the recording reels used to capture its demo videos. + One-screen showcase of the flutter_border_beam effects and palettes, plus + the recording reels used to capture its demo videos. publish_to: 'none' version: 1.0.0+1 environment: - sdk: ^3.9.0 + sdk: ^3.13.0 + flutter: ">=3.47.0" dependencies: flutter: sdk: flutter flutter_border_beam: path: ../ + material_ui: ^1.11.1 dev_dependencies: flutter_test: diff --git a/example/test/gallery_smoke_test.dart b/example/test/gallery_smoke_test.dart deleted file mode 100644 index b269dce..0000000 --- a/example/test/gallery_smoke_test.dart +++ /dev/null @@ -1,459 +0,0 @@ -import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam_example/main.dart'; -import 'package:flutter_border_beam_example/src/mocks.dart'; -import 'package:flutter_border_beam_example/src/playground/controls_panel.dart'; -import 'package:flutter_test/flutter_test.dart'; - -/// Reads the playground's generated snippet. -String snippetText(WidgetTester tester) => - tester.widget(find.byKey(const ValueKey('playground-snippet'))).data!; - -/// Advances past the demo's implicit animations. `pumpAndSettle` never -/// returns here: a running beam keeps its ticker scheduled forever. -Future settle(WidgetTester tester) async { - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - await tester.pump(const Duration(milliseconds: 300)); -} - -/// Scrolls [label] into view before tapping it — the demo is one long -/// scroll view, and a tap on an off-screen widget silently hits nothing. -Future tapLabel(WidgetTester tester, String label) async { - await tapFinder(tester, find.text(label)); -} - -/// The same, for a label that also appears elsewhere on the page: the -/// playground's own controls are scoped to the [ControlsPanel]. -Future tapControl(WidgetTester tester, String label) async { - await tapFinder( - tester, - find.descendant(of: find.byType(ControlsPanel), matching: find.text(label)), - ); -} - -/// Scrolls [finder] into view and taps it. -Future tapFinder(WidgetTester tester, Finder finder) async { - await settle(tester); - await tester.ensureVisible(finder); - await tester.pump(); - await tester.tap(finder); - await settle(tester); -} - -/// Mounts the demo on a tall viewport — the gallery is one long page. -Future pumpGallery(WidgetTester tester) async { - tester.view.physicalSize = const Size(1200, 3600); - tester.view.devicePixelRatio = 2; - addTearDown(tester.view.reset); - await tester.pumpWidget(const BorderBeamDemoApp()); - await tester.pump(const Duration(milliseconds: 300)); -} - -void main() { - testWidgets('gallery renders both tabs, the themed section, and the ' - 'playground', (tester) async { - tester.view.physicalSize = const Size(1200, 3600); - tester.view.devicePixelRatio = 2; - addTearDown(tester.view.reset); - - await tester.pumpWidget(const BorderBeamDemoApp()); - await tester.pump(const Duration(milliseconds: 300)); - - expect(find.text('Border beam'), findsOneWidget); - expect(find.text('Build anything...'), findsWidgets); - expect(find.text('Playground'), findsOneWidget); - - // The themed gallery: three variants under one BorderBeamTheme. - expect(find.text('Themed'), findsOneWidget); - expect(find.text('rotate'), findsOneWidget); - expect(find.text('small'), findsOneWidget); - expect(find.text('pulseInside'), findsOneWidget); - expect(find.text('Rest between sweeps'), findsOneWidget); - expect(find.text('Partial contours'), findsOneWidget); - expect(find.text('Half phone'), findsOneWidget); - expect(find.text('Half phone · line'), findsOneWidget); - expect(find.text('Half phone · pulse'), findsOneWidget); - expect(find.text('Corner wrap'), findsOneWidget); - - // Switch to the Pulse tab. - await tapLabel(tester, 'Pulse'); - expect(find.text('Working...'), findsOneWidget); - expect(find.text('Subscribe'), findsOneWidget); - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: a default configuration prints the one-liner', ( - tester, - ) async { - tester.view.physicalSize = const Size(1200, 3600); - tester.view.devicePixelRatio = 2; - addTearDown(tester.view.reset); - - await tester.pumpWidget(const BorderBeamDemoApp()); - await tester.pump(const Duration(milliseconds: 300)); - - expect(snippetText(tester), 'BorderBeam.rotate(\n child: child,\n)'); - }); - - testWidgets('playground: variant, shape, and palette changes reach the ' - 'snippet', (tester) async { - tester.view.physicalSize = const Size(1200, 3600); - tester.view.devicePixelRatio = 2; - addTearDown(tester.view.reset); - - await tester.pumpWidget(const BorderBeamDemoApp()); - await tester.pump(const Duration(milliseconds: 300)); - - final before = snippetText(tester); - - await tapLabel(tester, 'Line'); - expect(snippetText(tester), startsWith('BorderBeam.line(')); - expect(snippetText(tester), isNot(before)); - - await tapLabel(tester, 'Ocean'); - expect(snippetText(tester), contains('colors: BeamColors.ocean')); - - await tapLabel(tester, 'Stadium'); - expect(snippetText(tester), contains('BeamShape.stadium(')); - - await tapLabel(tester, 'Squircle'); - expect(snippetText(tester), contains('superellipse: true')); - - await tapLabel(tester, 'Pulse Outside'); - expect(snippetText(tester), startsWith('BorderBeam.pulseOutside(')); - - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: segment chips and corner wrap reach the snippet', ( - tester, - ) async { - await pumpGallery(tester); - - await tapControl(tester, 'Bottom half'); - expect(snippetText(tester), contains('BeamSegment.bottomHalf')); - - await tapControl(tester, 'Top edge'); - expect(snippetText(tester), contains('BeamSegment.topEdge')); - - await tapFinder( - tester, - find - .descendant( - of: find.byType(ControlsPanel), - matching: find.text('Custom'), - ) - .last, - ); - expect( - snippetText(tester), - contains( - 'BeamSegment(start: BeamAnchor.edge(BeamEdge.right), ' - 'end: BeamAnchor.edge(BeamEdge.left), feather: 48)', - ), - ); - expect(find.text('Start edge'), findsOneWidget); - expect(find.text('End edge'), findsOneWidget); - expect(find.text('Feather'), findsOneWidget); - - await tapControl(tester, 'Off'); - await tapControl(tester, 'Line'); - await tapControl(tester, 'Wrap corners'); - expect(snippetText(tester), contains('wrapCorners: true')); - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: controller mode swaps in a controller and its ' - 'transport', (tester) async { - tester.view.physicalSize = const Size(1200, 3600); - tester.view.devicePixelRatio = 2; - addTearDown(tester.view.reset); - - await tester.pumpWidget(const BorderBeamDemoApp()); - await tester.pump(const Duration(milliseconds: 300)); - - expect(find.text('Start'), findsNothing); - - await tapLabel(tester, 'Controller'); - expect(snippetText(tester), contains('final controller =')); - expect(snippetText(tester), contains('controller: controller')); - // The declarative scheduling fields are the controller's now. - expect(snippetText(tester), isNot(contains('playback:'))); - expect(find.text('Start'), findsOneWidget); - - for (final action in ['Pause', 'Resume', 'Stop', 'Start']) { - await tapLabel(tester, action); - } - - await tapLabel(tester, 'Controller'); - expect(snippetText(tester), isNot(contains('controller: controller'))); - expect(find.text('Start'), findsNothing); - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: the theme toggle wraps the snippet in a ' - 'BorderBeamTheme', (tester) async { - tester.view.physicalSize = const Size(1200, 3600); - tester.view.devicePixelRatio = 2; - addTearDown(tester.view.reset); - - await tester.pumpWidget(const BorderBeamDemoApp()); - await tester.pump(const Duration(milliseconds: 300)); - - await tapLabel(tester, 'Theme'); - await tapLabel(tester, 'BorderBeamTheme'); - expect(snippetText(tester), startsWith('BorderBeamTheme(')); - expect(snippetText(tester), contains('BeamColors.ocean')); - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: Reset returns every control to its default', ( - tester, - ) async { - tester.view.physicalSize = const Size(1200, 3600); - tester.view.devicePixelRatio = 2; - addTearDown(tester.view.reset); - - await tester.pumpWidget(const BorderBeamDemoApp()); - await tester.pump(const Duration(milliseconds: 300)); - - await tapLabel(tester, 'Line'); - await tapLabel(tester, 'Stadium'); - expect( - snippetText(tester), - isNot('BorderBeam.rotate(\n child: child,\n)'), - ); - - await tapLabel(tester, 'Reset'); - expect(snippetText(tester), 'BorderBeam.rotate(\n child: child,\n)'); - expect(tester.takeException(), isNull); - }); - - testWidgets('gallery: the palette, surface, motion, progress, and sync ' - 'sections all render', (tester) async { - await pumpGallery(tester); - - for (final title in [ - 'Palettes', - 'Surfaces', - 'Motion', - 'Driven progress', - 'Sync', - 'Partial contours', - ]) { - await tester.ensureVisible(find.text(title)); - await settle(tester); - expect(find.text(title), findsOneWidget, reason: '$title section'); - } - - for (final label in ['Half phone', 'Half phone · line', 'Corner wrap']) { - await tester.ensureVisible(find.text(label)); - await settle(tester); - expect(find.text(label), findsOneWidget); - } - - // One card per palette preset, named by the constant it uses. - for (final preset in ['colorful', 'mono', 'gold', 'holographic']) { - expect(find.text(preset), findsOneWidget); - } - - // The four surface entry points. - for (final label in [ - 'BeamDecoration', - 'BeamFocusRing', - 'BeamHover', - 'BeamPress', - ]) { - expect(find.text(label), findsOneWidget); - } - - // The motion cards. - for (final label in ['reverse', 'bounce', 'beamCount 3', 'segments 8']) { - expect(find.text(label), findsOneWidget); - } - - expect(tester.takeException(), isNull); - }); - - testWidgets('gallery: the surface wrappers light on focus, hover, and ' - 'press', (tester) async { - await pumpGallery(tester); - - // Focus: the ring follows the field's own subtree. - await tapFinder(tester, find.byType(MockFocusField)); - expect( - Focus.of(tester.element(find.text('Tap to focus'))).hasFocus, - isTrue, - ); - - // Hover: a mouse entering the card starts the beam and steers it. - final card = find.text('BeamHover'); - await tester.ensureVisible(card); - await settle(tester); - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - await mouse.addPointer(location: Offset.zero); - addTearDown(mouse.removePointer); - await mouse.moveTo(tester.getCenter(card)); - await settle(tester); - await mouse.moveTo(Offset.zero); - await settle(tester); - - // Press: pointer down lights it, and the release is held for the - // minimum duration. - final press = find.text('BeamPress'); - await tester.ensureVisible(press); - await settle(tester); - final finger = await tester.startGesture(tester.getCenter(press)); - await settle(tester); - await finger.up(); - await settle(tester); - - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: the Drive section feeds progress, the pointer, ' - 'and a signal', (tester) async { - await pumpGallery(tester); - - await tapControl(tester, 'Drive'); - await tapControl(tester, 'Progress'); - expect(snippetText(tester), contains('progress: 0.35')); - - await tapControl(tester, 'Strength from signal'); - expect(snippetText(tester), contains('strengthListenable: level')); - - // Follow loses to progress while both are on, so it reaches the snippet - // only once progress is off again. - await tapControl(tester, 'Follow pointer'); - expect(snippetText(tester), isNot(contains('follow: pointer'))); - await tapControl(tester, 'Progress'); - expect(snippetText(tester), contains('follow: pointer')); - - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: the sync toggle swaps in a BeamSync group', ( - tester, - ) async { - await pumpGallery(tester); - - await tapControl(tester, 'Theme'); - await tapControl(tester, 'BeamSync'); - expect(snippetText(tester), startsWith('BeamSync(')); - // The group's three beams are labelled with the phase each one runs at. - expect(find.text('phaseOffset 0.00'), findsWidgets); - expect(find.text('phaseOffset 0.33'), findsWidgets); - - await tapControl(tester, 'BeamSync'); - expect(snippetText(tester), startsWith('BorderBeam.rotate(')); - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: the controller transport carries pulse and ' - 'flash', (tester) async { - await pumpGallery(tester); - - await tapControl(tester, 'Controller'); - expect(snippetText(tester), contains('controller.pulse() / .flash()')); - - for (final action in ['Pulse', 'Flash', 'Pause', 'Resume', 'Start']) { - await tapControl(tester, action); - } - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: controllers start when previews attach or return ' - 'from sync mode', (tester) async { - tester.view.physicalSize = const Size(519, 3600); - tester.view.devicePixelRatio = 1; - addTearDown(tester.view.reset); - await tester.pumpWidget(const BorderBeamDemoApp()); - await tester.pump(const Duration(milliseconds: 300)); - - await tapControl(tester, 'Controller'); - var controlled = tester - .widgetList(find.byType(BorderBeam)) - .where((beam) => beam.controller != null) - .toList(); - expect(controlled, hasLength(1)); - expect(controlled.single.controller!.isActive, isTrue); - - tester.view.physicalSize = const Size(1200, 3600); - await settle(tester); - controlled = tester - .widgetList(find.byType(BorderBeam)) - .where((beam) => beam.controller != null) - .toList(); - expect(controlled, hasLength(2)); - expect(controlled.every((beam) => beam.controller!.isActive), isTrue); - - await tapControl(tester, 'Theme'); - await tapControl(tester, 'BeamSync'); - expect( - tester - .widgetList(find.byType(BorderBeam)) - .where((beam) => beam.controller != null), - isEmpty, - ); - - await tapControl(tester, 'BeamSync'); - controlled = tester - .widgetList(find.byType(BorderBeam)) - .where((beam) => beam.controller != null) - .toList(); - expect(controlled, hasLength(2)); - expect(controlled.every((beam) => beam.controller!.isActive), isTrue); - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: the new palette modes reach the snippet', ( - tester, - ) async { - await pumpGallery(tester); - - await tapControl(tester, 'Holographic'); - expect(snippetText(tester), contains('colors: BeamColors.holographic')); - - await tapControl(tester, 'Seed'); - expect(snippetText(tester), contains('BeamColors.fromSeed(')); - await tapControl(tester, 'Triadic'); - expect(snippetText(tester), contains('BeamSeedHarmony.triadic')); - - await tapControl(tester, 'Lerp'); - expect(snippetText(tester), contains('BeamColors.lerp(')); - - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: reduced motion can be chosen and simulated', ( - tester, - ) async { - await pumpGallery(tester); - - await tapControl(tester, 'Slow'); - expect( - snippetText(tester), - contains('reducedMotion: BeamReducedMotion.slow'), - ); - - // Simulating is a preview concern: the beam's fields do not change. - final before = snippetText(tester); - await tapControl(tester, 'Simulate reduced motion'); - expect(snippetText(tester), before); - expect(tester.takeException(), isNull); - }); - - testWidgets('playground: the star contour and ring offset reach the ' - 'shape', (tester) async { - await pumpGallery(tester); - - await tapControl(tester, 'Star contour'); - expect( - snippetText(tester), - contains("// contour: BeamPathContour(builder: yourPath, key: 'star')"), - ); - expect(tester.takeException(), isNull); - }); -} diff --git a/example/test/playground_config_test.dart b/example/test/playground_config_test.dart deleted file mode 100644 index 6521150..0000000 --- a/example/test/playground_config_test.dart +++ /dev/null @@ -1,142 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam_example/src/playground/playground_state.dart'; -import 'package:flutter_test/flutter_test.dart'; - -/// The playground hands the widget four value objects it assembled itself, so -/// a gating mistake there is a beam that throws rather than a snippet that -/// reads oddly. These mount the extremes the controls can reach. -void main() { - Future pumpConfig( - WidgetTester tester, - PlaygroundState state, { - bool reducedMotion = false, - }) async { - Widget beam = SizedBox( - width: 320, - height: 128, - child: BorderBeam( - variant: state.variant, - active: state.buildActive(), - style: state.buildStyle(), - shape: state.buildShape(), - timing: state.buildTiming(), - playback: state.buildPlayback(), - progress: state.buildProgress(), - child: const SizedBox.expand(), - ), - ); - if (reducedMotion) { - beam = MediaQuery( - data: const MediaQueryData(disableAnimations: true), - child: beam, - ); - } - await tester.pumpWidget(MaterialApp(home: Center(child: beam))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 400)); - await tester.pump(const Duration(milliseconds: 900)); - expect(tester.takeException(), isNull); - // Unmount so no ticker outlives the test. - await tester.pumpWidget(const SizedBox.shrink()); - } - - testWidgets('a rotate beam with every ring control at once paints', ( - tester, - ) async { - await pumpConfig( - tester, - PlaygroundState() - ..palette = PalettePreset.lerp - ..alphaScale = 0.7 - ..radius = 24 - ..superellipse = true - ..borderWidth = 3 - ..ringOffset = 8 - ..contour = true - ..hueMode = BeamHueMode.continuous - ..tailLength = 1.8 - ..glowSpread = 2.5 - ..comet = true - ..sparkle = 1 - ..segments = 16 - ..renderScale = 0.5 - ..direction = BeamDirection.bounce - ..phaseOffset = 0.75 - ..beamCount = 4 - ..repeatCycles = 3 - ..cssFadeCurve = true - ..pauseWhenOffscreen = true, - ); - }); - - testWidgets('a line beam on a non-default edge, with a contour, paints', ( - tester, - ) async { - await pumpConfig( - tester, - PlaygroundState() - ..variant = BeamVariant.line - ..palette = PalettePreset.seed - ..seedHarmony = BeamSeedHarmony.complementary - ..edge = BeamEdge.right - ..contour = true - ..stadium = true - ..sparkle = 0.6 - ..beamCount = 3 - ..cycleGapSeconds = 0.5, - ); - }); - - testWidgets('the stock pulse-outside recipe paints, tuned over', ( - tester, - ) async { - await pumpConfig( - tester, - PlaygroundState() - ..variant = BeamVariant.pulseOutside - ..stockPulseOutside = true - ..glowBoost = 1.6 - ..coreBlur = 24 - ..bloomBlur = 90 - ..segments = 12 - ..renderScale = 0.75, - ); - }); - - testWidgets('pulse-inside honours the inner wash scale', (tester) async { - await pumpConfig( - tester, - PlaygroundState() - ..variant = BeamVariant.pulseInside - ..innerSizeScale = 2 - ..glowBoost = 2.5 - ..perCorner = true - ..radiusTopLeft = 0 - ..radiusBottomRight = 48, - ); - }); - - testWidgets('a progress-driven beam under reduced motion paints', ( - tester, - ) async { - await pumpConfig( - tester, - PlaygroundState() - ..driveProgress = true - ..progress = 0.9 - ..reducedMotion = BeamReducedMotion.slow - ..strength = 0.4, - reducedMotion: true, - ); - }); - - testWidgets('a hidden beam under reduced motion paints nothing and does ' - 'not throw', (tester) async { - await pumpConfig( - tester, - PlaygroundState()..reducedMotion = BeamReducedMotion.hide, - reducedMotion: true, - ); - }); -} diff --git a/example/test/share_codec_test.dart b/example/test/share_codec_test.dart deleted file mode 100644 index 5e84814..0000000 --- a/example/test/share_codec_test.dart +++ /dev/null @@ -1,408 +0,0 @@ -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam_example/src/playground/playground_state.dart'; -import 'package:flutter_border_beam_example/src/playground/share_codec.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('encodePlaygroundState', () { - test('encodes the default configuration to the empty string', () { - expect(encodePlaygroundState(PlaygroundState()), isEmpty); - }); - - test('writes only the fields that differ from the default', () { - final state = PlaygroundState() - ..variant = BeamVariant.line - ..strength = 0.6; - expect(encodePlaygroundState(state), 'v=line&str=0.6'); - }); - - test('trims trailing zeros from numbers', () { - final state = PlaygroundState()..borderWidth = 2; - expect(encodePlaygroundState(state), 'bw=2'); - }); - - test('preserves custom swatches while another palette is selected', () { - final state = PlaygroundState() - ..palette = PalettePreset.ocean - ..customColors = [2, 5, 7]; - final decoded = decodePlaygroundState(encodePlaygroundState(state)); - expect(decoded.palette, PalettePreset.ocean); - expect(decoded.customColors, [2, 5, 7]); - }); - - test('preserves an explicit offscreen opt-out', () { - final state = PlaygroundState()..pauseWhenOffscreen = false; - final encoded = encodePlaygroundState(state); - expect(encoded, 'pwo=0'); - expect(decodePlaygroundState(encoded).pauseWhenOffscreen, isFalse); - }); - - test('emits only ASCII that needs no percent-escaping', () { - final state = PlaygroundState() - ..palette = PalettePreset.custom - ..customColors = [2, 5, 7] - ..hueBase = -120 - ..cycleSeconds = 2.5; - final encoded = encodePlaygroundState(state); - expect(encoded, matches(RegExp(r'^[A-Za-z0-9.,=&-]*$'))); - expect(encoded, contains('cc=2,5,7')); - expect(encoded, contains('hb=-120')); - expect(encoded, contains('cy=2.5')); - }); - }); - - group('decodePlaygroundState', () { - test('restores every field through a round trip', () { - final state = PlaygroundState() - ..variant = BeamVariant.pulseOutside - ..palette = PalettePreset.custom - ..customColors = [1, 4, 6] - ..customBase = PalettePreset.aurora - ..seedColor = 3 - ..seedHarmony = BeamSeedHarmony.triadic - ..lerpFrom = PalettePreset.ice - ..lerpTo = PalettePreset.gold - ..lerpT = 0.25 - ..alphaScale = 0.6 - ..stadium = true - ..perCorner = true - ..radius = 24 - ..radiusTopLeft = 4 - ..radiusTopRight = 8 - ..radiusBottomRight = 12 - ..radiusBottomLeft = 20 - ..superellipse = true - ..borderWidth = 2.5 - ..edge = BeamEdge.right - ..ringOffset = -6 - ..contour = true - ..segmentPreset = SegmentPreset.custom - ..segmentStartEdge = BeamEdge.bottom - ..segmentStartT = 0.2 - ..segmentEndEdge = BeamEdge.top - ..segmentEndT = 0.8 - ..segmentFeather = 72 - ..wrapCorners = true - ..cycleSeconds = 3.25 - ..cycleGapSeconds = 1.5 - ..speed = 2 - ..direction = BeamDirection.bounce - ..phaseOffset = 0.5 - ..beamCount = 3 - ..huePeriodSeconds = 7 - ..breatheFactor = 2 - ..spikeFactor = 0.75 - ..spike2Factor = 2.5 - ..staticColors = true - ..strength = 0.35 - ..brightness = 1.8 - ..saturation = 0.9 - ..hueRange = 12 - ..hueMode = BeamHueMode.continuous - ..hueBase = 45 - ..strokeOpacityFactor = 0.5 - ..innerOpacityFactor = 1.5 - ..bloomOpacityFactor = 0.25 - ..tailLength = 1.75 - ..glowSpread = 2.5 - ..comet = true - ..sparkle = 0.4 - ..segments = 12 - ..innerSizeScale = 1.4 - ..renderScale = 0.5 - ..stockPulseOutside = true - ..glowBoost = 2.2 - ..coreBlur = 18 - ..bloomBlur = 64 - ..glowBrightness = 1.4 - ..glowSaturation = 2.1 - ..active = false - ..repeatCycles = 3 - ..reducedMotion = BeamReducedMotion.slow - ..simulateReducedMotion = true - ..pauseWhenOffscreen = true - ..cssFadeCurve = true - ..driveProgress = true - ..progress = 0.8 - ..followPointer = true - ..strengthSignal = true - ..syncDemo = true - ..controllerMode = true - ..controllerSpeed = 3 - ..startAfterSeconds = 1.5 - ..durationSeconds = 9 - ..themeDemo = true; - - final encoded = encodePlaygroundState(state); - final decoded = decodePlaygroundState(encoded); - - expect(encodePlaygroundState(decoded), encoded); - expect(decoded.variant, BeamVariant.pulseOutside); - expect(decoded.palette, PalettePreset.custom); - expect(decoded.customColors, [1, 4, 6]); - expect(decoded.stadium, isTrue); - expect(decoded.perCorner, isTrue); - expect(decoded.superellipse, isTrue); - expect(decoded.borderWidth, 2.5); - expect(decoded.cycleSeconds, 3.25); - expect(decoded.huePeriodSeconds, 7); - expect(decoded.hueBase, 45); - expect(decoded.active, isFalse); - expect(decoded.controllerMode, isTrue); - expect(decoded.controllerSpeed, 3); - expect(decoded.themeDemo, isTrue); - expect(decoded.customBase, PalettePreset.aurora); - expect(decoded.seedColor, 3); - expect(decoded.seedHarmony, BeamSeedHarmony.triadic); - expect(decoded.lerpFrom, PalettePreset.ice); - expect(decoded.lerpTo, PalettePreset.gold); - expect(decoded.lerpT, 0.25); - expect(decoded.alphaScale, 0.6); - expect(decoded.edge, BeamEdge.right); - expect(decoded.ringOffset, -6); - expect(decoded.contour, isTrue); - expect(decoded.segmentPreset, SegmentPreset.custom); - expect(decoded.segmentStartEdge, BeamEdge.bottom); - expect(decoded.segmentStartT, 0.2); - expect(decoded.segmentEndEdge, BeamEdge.top); - expect(decoded.segmentEndT, 0.8); - expect(decoded.segmentFeather, 72); - expect(decoded.wrapCorners, isTrue); - expect(decoded.direction, BeamDirection.bounce); - expect(decoded.phaseOffset, 0.5); - expect(decoded.beamCount, 3); - expect(decoded.hueMode, BeamHueMode.continuous); - expect(decoded.tailLength, 1.75); - expect(decoded.glowSpread, 2.5); - expect(decoded.comet, isTrue); - expect(decoded.sparkle, 0.4); - expect(decoded.segments, 12); - expect(decoded.innerSizeScale, 1.4); - expect(decoded.renderScale, 0.5); - expect(decoded.stockPulseOutside, isTrue); - expect(decoded.pauseWhenOffscreen, isTrue); - expect(decoded.cssFadeCurve, isTrue); - expect(decoded.repeatCycles, 3); - expect(decoded.reducedMotion, BeamReducedMotion.slow); - expect(decoded.simulateReducedMotion, isTrue); - expect(decoded.driveProgress, isTrue); - expect(decoded.progress, 0.8); - expect(decoded.followPointer, isTrue); - expect(decoded.strengthSignal, isTrue); - expect(decoded.syncDemo, isTrue); - }); - - test('an empty string decodes to the defaults', () { - final decoded = decodePlaygroundState(''); - expect(encodePlaygroundState(decoded), isEmpty); - expect(decoded.variant, BeamVariant.rotate); - expect(decoded.cycleSeconds, isNull); - }); - - test('ignores unknown keys, malformed pairs, and bad values', () { - final decoded = decodePlaygroundState( - 'nope=1&&=5&v=not-a-variant&p=nope&str=huge&bw=99&hb=-999&sc=maybe', - ); - expect(decoded.variant, BeamVariant.rotate); - expect(decoded.palette, PalettePreset.colorful); - expect(decoded.strength, 1); - expect(decoded.borderWidth, 1, reason: 'out of the 0.5–4 range'); - expect(decoded.hueBase, 0, reason: 'out of the -180–180 range'); - expect(decoded.staticColors, isFalse); - }); - - test('drops out-of-bounds swatch indices and short custom lists', () { - expect(decodePlaygroundState('cc=0,99,x,3').customColors, [0, 3]); - expect( - decodePlaygroundState('cc=0').customColors, - PlaygroundState().customColors, - reason: 'fewer than two colors is not a usable custom palette', - ); - expect(decodePlaygroundState('cc=0,1,2,3,4,5').customColors.length, 4); - }); - }); - - group('playgroundStateStringFrom', () { - test('reads a query string', () { - expect( - playgroundStateStringFrom(Uri.parse('https://x.dev/?v=line&str=0.5')), - 'v=line&str=0.5', - ); - }); - - test('reads a bare fragment — the form the share button hands out', () { - expect( - playgroundStateStringFrom(Uri.parse('https://x.dev/#v=line')), - 'v=line', - ); - }); - - test('reads a fragment carrying a route and query', () { - expect( - playgroundStateStringFrom(Uri.parse('https://x.dev/#/?v=line')), - 'v=line', - ); - }); - - test('returns null when there is no state to read', () { - expect(playgroundStateStringFrom(Uri.parse('https://x.dev/')), isNull); - expect(playgroundStateStringFrom(Uri.parse('https://x.dev/#/')), isNull); - expect(playgroundStateStringFrom(Uri.parse('file:///tmp/app')), isNull); - }); - }); - - group('playgroundShareUrl', () { - test('appends the state to the published site as a fragment', () { - expect(playgroundShareUrl('v=line'), '$playgroundSiteUrl#v=line'); - }); - - test('a default configuration shares the bare site URL', () { - expect(playgroundShareUrl(''), playgroundSiteUrl); - }); - - test('round-trips through the URL it builds', () { - final state = PlaygroundState() - ..variant = BeamVariant.small - ..stadium = true; - final encoded = encodePlaygroundState(state); - final uri = Uri.parse(playgroundShareUrl(encoded)); - final decoded = decodePlaygroundState(playgroundStateStringFrom(uri)!); - expect(decoded.variant, BeamVariant.small); - expect(decoded.stadium, isTrue); - }); - }); - - group('the new controls', () { - test('each new palette mode round-trips its own fields', () { - for (final palette in [ - PalettePreset.holographic, - PalettePreset.seed, - PalettePreset.lerp, - PalettePreset.custom, - ]) { - final state = PlaygroundState()..palette = palette; - final decoded = decodePlaygroundState(encodePlaygroundState(state)); - expect(decoded.palette, palette); - } - }); - - test('a default configuration still encodes to the empty string', () { - // Every new field must default to what the package resolves on its - // own, or the share link stops being empty at rest. - expect(encodePlaygroundState(PlaygroundState()), isEmpty); - }); - - test('enum values encode as their names, still escaping-free', () { - final state = PlaygroundState() - ..edge = BeamEdge.left - ..direction = BeamDirection.reverse - ..hueMode = BeamHueMode.pingPong - ..reducedMotion = BeamReducedMotion.hide - ..seedHarmony = BeamSeedHarmony.monochrome; - final encoded = encodePlaygroundState(state); - expect(encoded, matches(RegExp(r'^[A-Za-z0-9.,=&-]*$'))); - expect(encoded, contains('ed=left')); - expect(encoded, contains('dir=reverse')); - expect(encoded, contains('hm=pingPong')); - expect(encoded, contains('rm=hide')); - expect(encoded, contains('sdh=monochrome')); - }); - - test('segment presets and custom anchors use the compact shape keys', () { - final preset = PlaygroundState() - ..segmentPreset = SegmentPreset.bottomHalf; - expect(encodePlaygroundState(preset), 'sgp=bottomHalf'); - - final custom = PlaygroundState() - ..segmentPreset = SegmentPreset.custom - ..segmentStartEdge = BeamEdge.top - ..segmentStartT = 0.25 - ..segmentEndEdge = BeamEdge.bottom - ..segmentEndT = 0.75 - ..segmentFeather = 64 - ..wrapCorners = true; - final encoded = encodePlaygroundState(custom); - expect(encoded, contains('sgp=custom')); - expect(encoded, contains('sga=top,0.25')); - expect(encoded, contains('sgb=bottom,0.75')); - expect(encoded, contains('sgf=64')); - expect(encoded, contains('wc=1')); - - final decoded = decodePlaygroundState(encoded); - expect(decoded.segmentPreset, SegmentPreset.custom); - expect(decoded.segmentStartEdge, BeamEdge.top); - expect(decoded.segmentStartT, 0.25); - expect(decoded.segmentEndEdge, BeamEdge.bottom); - expect(decoded.segmentEndT, 0.75); - expect(decoded.segmentFeather, 64); - expect(decoded.wrapCorners, isTrue); - }); - - test('unknown enum names and out-of-range numbers are ignored', () { - final decoded = decodePlaygroundState( - 'ed=diagonal&dir=sideways&hm=strobe&rm=never&sdh=nope&' - 'ro=999&po=4&bc=9&sg=7&rp=0&pr=2&al=-1<=5&tl=9&gs=9&sk=3&' - 'iss=9&rs=4', - ); - final d = PlaygroundState(); - expect(decoded.edge, d.edge); - expect(decoded.direction, d.direction); - expect(decoded.hueMode, isNull); - expect(decoded.reducedMotion, isNull); - expect(decoded.seedHarmony, d.seedHarmony); - expect(decoded.ringOffset, d.ringOffset); - expect(decoded.phaseOffset, d.phaseOffset); - expect(decoded.beamCount, d.beamCount); - expect(decoded.segments, isNull, reason: '7 is not an offered count'); - expect(decoded.repeatCycles, isNull); - expect(decoded.progress, d.progress); - expect(decoded.alphaScale, d.alphaScale); - expect(decoded.lerpT, d.lerpT); - expect(decoded.tailLength, d.tailLength); - expect(decoded.glowSpread, d.glowSpread); - expect(decoded.sparkle, d.sparkle); - expect(decoded.innerSizeScale, d.innerSizeScale); - expect(decoded.renderScale, d.renderScale); - }); - - test('bad segment ids, anchors, feather, and wrap values are ignored', () { - final decoded = decodePlaygroundState( - 'sgp=diagonal&sga=right,4&sgb=nope,0.5&sgf=121&wc=maybe', - ); - final d = PlaygroundState(); - expect(decoded.segmentPreset, d.segmentPreset); - expect(decoded.segmentStartEdge, d.segmentStartEdge); - expect(decoded.segmentStartT, d.segmentStartT); - expect(decoded.segmentEndEdge, d.segmentEndEdge); - expect(decoded.segmentEndT, d.segmentEndT); - expect(decoded.segmentFeather, d.segmentFeather); - expect(decoded.wrapCorners, d.wrapCorners); - }); - - test('an assembled palette cannot be a lerp endpoint or a custom ' - 'base', () { - final decoded = decodePlaygroundState('pb=seed&lfa=lerp<o=custom'); - final d = PlaygroundState(); - expect(decoded.customBase, d.customBase); - expect(decoded.lerpFrom, d.lerpFrom); - expect(decoded.lerpTo, d.lerpTo); - }); - - test('the drive and group toggles round-trip', () { - final state = PlaygroundState() - ..driveProgress = true - ..progress = 0.9 - ..followPointer = true - ..strengthSignal = true - ..simulateReducedMotion = true - ..syncDemo = true; - final decoded = decodePlaygroundState(encodePlaygroundState(state)); - expect(decoded.driveProgress, isTrue); - expect(decoded.progress, 0.9); - expect(decoded.followPointer, isTrue); - expect(decoded.strengthSignal, isTrue); - expect(decoded.simulateReducedMotion, isTrue); - expect(decoded.syncDemo, isTrue); - }); - }); -} diff --git a/example/test/snippet_test.dart b/example/test/snippet_test.dart deleted file mode 100644 index 7b9d1ff..0000000 --- a/example/test/snippet_test.dart +++ /dev/null @@ -1,540 +0,0 @@ -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam_example/src/playground/playground_state.dart'; -import 'package:flutter_border_beam_example/src/playground/snippet.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - test('a default configuration prints the one-liner', () { - expect( - buildSnippet(PlaygroundState()), - 'BorderBeam.rotate(\n child: child,\n)', - ); - }); - - test('picks the named constructor for the variant', () { - for (final entry in { - BeamVariant.rotate: 'BorderBeam.rotate(', - BeamVariant.small: 'BorderBeam.small(', - BeamVariant.line: 'BorderBeam.line(', - BeamVariant.pulseInside: 'BorderBeam.pulseInside(', - BeamVariant.pulseOutside: 'BorderBeam.pulseOutside(', - }.entries) { - final state = PlaygroundState()..variant = entry.key; - expect(buildSnippet(state), startsWith(entry.value)); - } - }); - - test('the small variant leaves its preset radius inherited', () { - final state = PlaygroundState()..variant = BeamVariant.small; - expect(buildSnippet(state), isNot(contains('borderRadius:'))); - }); - - test('a plain radius uses the borderRadius shorthand', () { - final state = PlaygroundState()..radius = 24; - expect(buildSnippet(state), contains('borderRadius: 24')); - expect(buildSnippet(state), isNot(contains('BeamShape'))); - }); - - test('a radius with a squircle or a width uses the const BeamShape.all', () { - final state = PlaygroundState() - ..radius = 24 - ..superellipse = true - ..borderWidth = 2; - expect( - buildSnippet(state), - contains( - 'shape: const BeamShape.all(24, borderWidth: 2, ' - 'superellipse: true)', - ), - ); - }); - - test('stadium corners emit the const named constructor', () { - final state = PlaygroundState()..stadium = true; - expect(buildSnippet(state), contains('shape: const BeamShape.stadium()')); - }); - - test('per-corner mode emits a const BorderRadius.only', () { - final state = PlaygroundState() - ..perCorner = true - ..radiusTopLeft = 4 - ..radiusBottomRight = 28; - final snippet = buildSnippet(state); - expect(snippet, contains('shape: const BeamShape(')); - expect(snippet, contains('radius: BorderRadius.only(')); - expect(snippet, contains('topLeft: Radius.circular(4)')); - expect(snippet, contains('bottomRight: Radius.circular(28)')); - }); - - test('sub-second durations are emitted in milliseconds', () { - final state = PlaygroundState()..cycleGapSeconds = 0.9; - expect( - buildSnippet(state), - contains('cycleGap: Duration(milliseconds: 900)'), - ); - }); - - test('whole-second durations are emitted in seconds', () { - final state = PlaygroundState()..cycleGapSeconds = 2; - expect(buildSnippet(state), contains('cycleGap: Duration(seconds: 2)')); - }); - - test('custom colors are emitted as a const list of Color literals', () { - final state = PlaygroundState() - ..palette = PalettePreset.custom - ..customColors = [0, 1]; - expect( - buildSnippet(state), - contains( - 'colors: const BeamColors.custom([Color(0xFFFF0080), ' - 'Color(0xFF00E5FF)])', - ), - ); - }); - - test('controller mode declares the controller and drops playback', () { - final state = PlaygroundState() - ..controllerMode = true - ..controllerSpeed = 2 - ..speed = 3 - ..startAfterSeconds = 1 - ..durationSeconds = 5; - final snippet = buildSnippet(state); - expect(snippet, startsWith('final controller = BorderBeamController();')); - expect(snippet, contains('// controller.speed = 2;')); - expect(snippet, contains('controller: controller')); - // A controller owns scheduling and the rate exclusively. - expect(snippet, isNot(contains('playback:'))); - expect(snippet, isNot(contains('speed:'))); - }); - - test('scheduling fields ride BeamPlayback outside controller mode', () { - final state = PlaygroundState() - ..startAfterSeconds = 0.5 - ..durationSeconds = 6; - final snippet = buildSnippet(state); - expect(snippet, contains('playback: const BeamPlayback(')); - expect(snippet, contains('startAfter: Duration(milliseconds: 500)')); - expect(snippet, contains('duration: Duration(seconds: 6)')); - }); - - test('an inactive beam uses the active shorthand', () { - final state = PlaygroundState()..active = false; - expect(buildSnippet(state), contains('active: false')); - }); - - test('theme mode nests the beam under a BorderBeamTheme', () { - final state = PlaygroundState()..themeDemo = true; - final snippet = buildSnippet(state); - expect(snippet, startsWith('BorderBeamTheme(')); - expect( - snippet, - contains('style: const BeamStyle(colors: BeamColors.ocean)'), - ); - expect( - snippet, - contains('shape: BeamShape.circular(20, superellipse: true)'), - ); - expect(snippet, contains(' child: BorderBeam.rotate(')); - expect(snippet, endsWith(')')); - }); - - test('line-only timing fields are dropped on other variants', () { - final state = PlaygroundState() - ..variant = BeamVariant.rotate - ..breatheFactor = 2 - ..spikeFactor = 2; - expect(buildSnippet(state), isNot(contains('breatheFactor'))); - - state.variant = BeamVariant.line; - expect(buildSnippet(state), contains('breatheFactor: 2')); - expect(buildSnippet(state), contains('spikeFactor: 2')); - }); - - test('pulse-only style fields are dropped on other variants', () { - final state = PlaygroundState() - ..glowBoost = 2 - ..coreBlur = 20; - expect(buildSnippet(state), isNot(contains('glowBoost'))); - expect(buildSnippet(state), isNot(contains('coreBlur'))); - - state.variant = BeamVariant.pulseInside; - expect(buildSnippet(state), contains('glowBoost: 2')); - expect(buildSnippet(state), isNot(contains('coreBlur'))); - - state.variant = BeamVariant.pulseOutside; - expect(buildSnippet(state), contains('coreBlur: 20')); - }); - - test('numbers read as hand-written arguments', () { - final state = PlaygroundState() - ..strength = 0.5 - ..hueBase = -30 - ..strokeOpacityFactor = 1.25; - final snippet = buildSnippet(state); - expect(snippet, contains('strength: 0.5')); - expect(snippet, contains('hueBase: -30')); - expect(snippet, contains('strokeOpacityFactor: 1.25')); - }); - - group('palettes', () { - test('a preset emits its constant', () { - final state = PlaygroundState()..palette = PalettePreset.aurora; - expect(buildSnippet(state), contains('colors: BeamColors.aurora')); - }); - - test('seed mode emits BeamColors.fromSeed, harmony only when set', () { - final state = PlaygroundState() - ..palette = PalettePreset.seed - ..seedColor = 1; - expect( - buildSnippet(state), - contains('colors: const BeamColors.fromSeed(Color(0xFF00E5FF))'), - ); - - state.seedHarmony = BeamSeedHarmony.triadic; - expect( - buildSnippet(state), - contains( - 'const BeamColors.fromSeed(Color(0xFF00E5FF), ' - 'harmony: BeamSeedHarmony.triadic)', - ), - ); - }); - - test('lerp mode emits both endpoints and the blend', () { - final state = PlaygroundState() - ..palette = PalettePreset.lerp - ..lerpFrom = PalettePreset.ice - ..lerpTo = PalettePreset.ember - ..lerpT = 0.25; - expect( - buildSnippet(state), - contains( - 'colors: const BeamColors.lerp(BeamColors.ice, ' - 'BeamColors.ember, 0.25)', - ), - ); - }); - - test('a custom base is emitted only when it is not colorful', () { - final state = PlaygroundState()..palette = PalettePreset.custom; - expect(buildSnippet(state), isNot(contains('base:'))); - - state.customBase = PalettePreset.ocean; - expect(buildSnippet(state), contains('base: BeamColors.ocean')); - }); - - test('scaleAlpha wraps the palette, default colors included', () { - final state = PlaygroundState()..alphaScale = 0.6; - expect( - buildSnippet(state), - contains('colors: BeamColors.colorful.scaleAlpha(0.6)'), - ); - - state.palette = PalettePreset.gold; - expect( - buildSnippet(state), - contains('colors: BeamColors.gold.scaleAlpha(0.6)'), - ); - }); - }); - - group('shape', () { - test('the line edge is emitted only on the line variant', () { - final state = PlaygroundState()..edge = BeamEdge.top; - expect(buildSnippet(state), isNot(contains('edge:'))); - - state.variant = BeamVariant.line; - expect(buildSnippet(state), contains('edge: BeamEdge.top')); - }); - - test('a ring offset promotes the shorthand to a const BeamShape', () { - final state = PlaygroundState()..ringOffset = 6; - expect( - buildSnippet(state), - contains('shape: const BeamShape.all(16, ringOffset: 6)'), - ); - }); - - test('a contour emits a commented placeholder, since it takes a ' - 'builder', () { - final state = PlaygroundState()..contour = true; - final snippet = buildSnippet(state); - expect(snippet, contains('shape: const BeamShape.all(')); - expect( - snippet, - contains("// contour: BeamPathContour(builder: yourPath, key: 'star')"), - ); - }); - - test('segment presets emit their const BeamSegment fields', () { - final state = PlaygroundState()..segmentPreset = SegmentPreset.bottomHalf; - expect(buildSnippet(state), contains('segment: BeamSegment.bottomHalf')); - - state.segmentPreset = SegmentPreset.topEdge; - expect(buildSnippet(state), contains('segment: BeamSegment.topEdge')); - }); - - test('a custom segment emits const edge anchors and feathering', () { - final state = PlaygroundState() - ..segmentPreset = SegmentPreset.custom - ..segmentFeather = 48; - expect( - buildSnippet(state), - contains( - 'segment: BeamSegment(start: BeamAnchor.edge(BeamEdge.right), ' - 'end: BeamAnchor.edge(BeamEdge.left), feather: 48)', - ), - ); - - state.segmentStartT = 0.25; - expect( - buildSnippet(state), - contains('BeamAnchor.edge(BeamEdge.right, 0.25)'), - ); - }); - - test('corner wrap is line-only and segment takes precedence over edge', () { - final state = PlaygroundState() - ..wrapCorners = true - ..edge = BeamEdge.top; - expect(buildSnippet(state), isNot(contains('wrapCorners'))); - - state.variant = BeamVariant.line; - expect(buildSnippet(state), contains('wrapCorners: true')); - expect(buildSnippet(state), contains('edge: BeamEdge.top')); - - state.segmentPreset = SegmentPreset.bottomHalf; - final segmented = buildSnippet(state); - expect(segmented, contains('segment: BeamSegment.bottomHalf')); - expect(segmented, isNot(contains('wrapCorners'))); - expect(segmented, isNot(contains('edge:'))); - }); - }); - - group('style', () { - test('hue mode is emitted only when it is set', () { - final state = PlaygroundState(); - expect(buildSnippet(state), isNot(contains('hueMode'))); - - state.hueMode = BeamHueMode.continuous; - expect(buildSnippet(state), contains('hueMode: BeamHueMode.continuous')); - }); - - test('tail length and comet are ring-only', () { - final state = PlaygroundState() - ..variant = BeamVariant.line - ..tailLength = 1.5 - ..comet = true; - expect(buildSnippet(state), isNot(contains('tailLength'))); - expect(buildSnippet(state), isNot(contains('comet'))); - - state.variant = BeamVariant.small; - expect(buildSnippet(state), contains('tailLength: 1.5')); - expect(buildSnippet(state), contains('comet: true')); - }); - - test('sparkle is dropped on the pulse variants', () { - final state = PlaygroundState() - ..variant = BeamVariant.pulseInside - ..sparkle = 0.5; - expect(buildSnippet(state), isNot(contains('sparkle'))); - - state.variant = BeamVariant.line; - expect(buildSnippet(state), contains('sparkle: 0.5')); - }); - - test('segments are dropped on the line variant', () { - final state = PlaygroundState() - ..variant = BeamVariant.line - ..segments = 8; - expect(buildSnippet(state), isNot(contains('segments'))); - - state.variant = BeamVariant.pulseOutside; - expect(buildSnippet(state), contains('segments: 8')); - }); - - test('glow spread applies to every variant', () { - final state = PlaygroundState()..glowSpread = 2; - expect(buildSnippet(state), contains('glowSpread: 2')); - }); - }); - - group('timing', () { - test('the travel fields are dropped on the pulse variants', () { - final state = PlaygroundState() - ..variant = BeamVariant.pulseInside - ..direction = BeamDirection.bounce - ..phaseOffset = 0.25 - ..beamCount = 3; - final pulse = buildSnippet(state); - expect(pulse, isNot(contains('direction'))); - expect(pulse, isNot(contains('phaseOffset'))); - expect(pulse, isNot(contains('beamCount'))); - - state.variant = BeamVariant.rotate; - final rotate = buildSnippet(state); - expect(rotate, contains('direction: BeamDirection.bounce')); - expect(rotate, contains('phaseOffset: 0.25')); - expect(rotate, contains('beamCount: 3')); - }); - }); - - group('playback', () { - test('repeat emits the constructor the chip selects', () { - final state = PlaygroundState()..repeatCycles = 1; - expect(buildSnippet(state), contains('repeat: BeamRepeat.once()')); - - state.repeatCycles = 3; - expect(buildSnippet(state), contains('repeat: BeamRepeat.count(3)')); - - state.repeatCycles = null; - expect(buildSnippet(state), isNot(contains('repeat'))); - }); - - test('static-frame reduced motion sets no field', () { - final state = PlaygroundState(); - expect(buildSnippet(state), isNot(contains('reducedMotion'))); - - state.reducedMotion = BeamReducedMotion.slow; - expect( - buildSnippet(state), - contains('reducedMotion: BeamReducedMotion.slow'), - ); - }); - - test('repeat survives controller mode, where scheduling does not', () { - final state = PlaygroundState() - ..controllerMode = true - ..repeatCycles = 3 - ..startAfterSeconds = 1 - ..durationSeconds = 5; - final snippet = buildSnippet(state); - expect(snippet, contains('repeat: BeamRepeat.count(3)')); - expect(snippet, isNot(contains('startAfter'))); - expect(snippet, isNot(contains('duration:'))); - }); - }); - - group('drive', () { - test('progress rides a flat parameter, and only where a beam travels', () { - final state = PlaygroundState() - ..driveProgress = true - ..progress = 0.4; - expect(buildSnippet(state), contains('progress: 0.4')); - - state.variant = BeamVariant.pulseOutside; - expect(buildSnippet(state), isNot(contains('progress'))); - }); - - test('follow names the pointer variable and explains it', () { - final state = PlaygroundState()..followPointer = true; - final snippet = buildSnippet(state); - expect(snippet, contains('// pointer:')); - expect(snippet, contains('follow: pointer')); - }); - - test('progress wins over follow', () { - final state = PlaygroundState() - ..followPointer = true - ..driveProgress = true; - final snippet = buildSnippet(state); - expect(snippet, contains('progress:')); - expect(snippet, isNot(contains('follow:'))); - }); - - test('the strength signal declares its notifier', () { - final state = PlaygroundState()..strengthSignal = true; - final snippet = buildSnippet(state); - expect(snippet, startsWith('final level = ValueNotifier(1);')); - expect(snippet, contains('strengthListenable: level')); - }); - }); - - test('the sync demo wraps the beam in a BeamSync', () { - final state = PlaygroundState()..syncDemo = true; - final snippet = buildSnippet(state); - expect(snippet, startsWith('BeamSync(')); - expect(snippet, contains('child: Column(')); - expect('BorderBeam.rotate('.allMatches(snippet), hasLength(3)); - expect(snippet, contains('phaseOffset: 0.33')); - expect(snippet, contains('phaseOffset: 0.67')); - expect(snippet, endsWith(')')); - }); - - test('the sync demo owns playback and never emits a controller', () { - final state = PlaygroundState() - ..syncDemo = true - ..controllerMode = true - ..active = false - ..speed = 2 - ..reducedMotion = BeamReducedMotion.slow - ..repeatCycles = 3; - final snippet = buildSnippet(state); - expect(snippet, contains('active: false')); - expect(snippet, contains('speed: 2')); - expect(snippet, contains('reducedMotion: BeamReducedMotion.slow')); - expect(snippet, isNot(contains('BorderBeamController'))); - expect(snippet, isNot(contains('controller: controller'))); - expect(snippet, isNot(contains('repeat:'))); - }); - - test('the sync demo nests inside the theme demo', () { - final state = PlaygroundState() - ..syncDemo = true - ..themeDemo = true; - final snippet = buildSnippet(state); - expect(snippet, startsWith('BorderBeamTheme(')); - expect(snippet, contains('child: BeamSync(')); - }); - - group('the newest style and playback fields', () { - test('inner size is pulse-inside only, render scale is universal', () { - final state = PlaygroundState() - ..innerSizeScale = 1.4 - ..renderScale = 0.5; - expect(buildSnippet(state), isNot(contains('innerSizeScale'))); - expect(buildSnippet(state), contains('renderScale: 0.5')); - - state.variant = BeamVariant.pulseInside; - expect(buildSnippet(state), contains('innerSizeScale: 1.4')); - }); - - test('the stock recipe replaces the const style, and merges what is ' - 'set over it', () { - final state = PlaygroundState() - ..variant = BeamVariant.pulseOutside - ..stockPulseOutside = true; - expect( - buildSnippet(state), - contains('style: BeamStyle.pulseOutsideStock'), - ); - expect(buildSnippet(state), isNot(contains('merge('))); - - state.glowBoost = 1.4; - final merged = buildSnippet(state); - expect(merged, contains('BeamStyle.pulseOutsideStock.merge(')); - expect(merged, contains('glowBoost: 1.4')); - }); - - test('the stock recipe is dropped on every other variant', () { - final state = PlaygroundState()..stockPulseOutside = true; - expect(buildSnippet(state), isNot(contains('pulseOutsideStock'))); - }); - - test('offscreen pause and the CSS fade curve ride BeamPlayback', () { - final state = PlaygroundState() - ..pauseWhenOffscreen = true - ..cssFadeCurve = true; - final snippet = buildSnippet(state); - expect(snippet, contains('pauseWhenOffscreen: true')); - expect(snippet, contains('fadeCurve: BeamPlayback.cssEase')); - }); - - test('offscreen pausing can be explicitly disabled', () { - final state = PlaygroundState()..pauseWhenOffscreen = false; - expect(buildSnippet(state), contains('pauseWhenOffscreen: false')); - }); - }); -} diff --git a/example/web/index.html b/example/web/index.html index cc8d0f0..d7f243e 100644 --- a/example/web/index.html +++ b/example/web/index.html @@ -19,24 +19,24 @@ - + - + - - + + - - + + @@ -49,7 +49,7 @@ - flutter_border_beam playground + flutter_border_beam diff --git a/example/web/manifest.json b/example/web/manifest.json index 9cede53..16d76a8 100644 --- a/example/web/manifest.json +++ b/example/web/manifest.json @@ -1,11 +1,11 @@ { - "name": "flutter_border_beam playground", + "name": "flutter_border_beam", "short_name": "border beam", "start_url": ".", "display": "standalone", "background_color": "#070707", "theme_color": "#070707", - "description": "Interactive playground and gallery for flutter_border_beam — animated border beam effects for Flutter.", + "description": "Animated border beam effects for Flutter: rotate, line, and pulse.", "orientation": "any", "prefer_related_applications": false, "icons": [ diff --git a/lib/flutter_border_beam.dart b/lib/flutter_border_beam.dart index 2907cff..8471ff3 100644 --- a/lib/flutter_border_beam.dart +++ b/lib/flutter_border_beam.dart @@ -1,35 +1,26 @@ /// Animated border beam effects for Flutter. /// -/// A faithful port of the border-beam React library: traveling and breathing -/// glow animations around any widget, with rotate, line, and pulse variants, -/// eleven color presets plus custom palettes, superellipse borders, and an -/// optional playback controller. +/// Travelling and breathing light around any widget's border — three +/// effects, a gallery of palettes plus your own, superellipse corners, +/// theming, and playback control — drawn by one fragment shader in a single +/// pass, with no offscreen layers or blurs. library; export 'src/beam_sync.dart' show BeamSync; export 'src/border_beam.dart' show BorderBeam; export 'src/border_beam_controller.dart' show BorderBeamController; export 'src/border_beam_theme.dart' show BorderBeamTheme, BorderBeamThemeData; -export 'src/models/beam_blob.dart' show BeamBlob, LineBlob; +export 'src/effects/beam_effect.dart' + show BeamEffect, LineEffect, PulseEffect, RotateEffect; export 'src/models/beam_colors.dart' show BeamColors, BeamSeedHarmony; export 'src/models/beam_options.dart' - show - BeamContour, - BeamDirection, - BeamEdge, - BeamHueMode, - BeamPathContour, - BeamPulseOutsideTuning, - BeamReducedMotion, - BeamRepeat; + show BeamDirection, BeamEdge, BeamHueMode, BeamReducedMotion, BeamRepeat; export 'src/models/beam_playback.dart' show BeamPlayback; export 'src/models/beam_segment.dart' show BeamAnchor, BeamCorner, BeamSegment; export 'src/models/beam_shape.dart' show BeamShape; export 'src/models/beam_style.dart' show BeamStyle; export 'src/models/beam_theme.dart' show BeamTheme; -export 'src/models/beam_theme_config.dart' show BeamThemeConfig; export 'src/models/beam_timing.dart' show BeamTiming; -export 'src/models/beam_variant.dart' show BeamVariant; export 'src/widgets/beam_decoration.dart' show BeamDecoration; export 'src/widgets/beam_focus_ring.dart' show BeamFocusRing; export 'src/widgets/beam_hover.dart' show BeamHover; diff --git a/lib/src/animation/beam_clock.dart b/lib/src/animation/beam_clock.dart index bb912a8..bc8adb9 100644 --- a/lib/src/animation/beam_clock.dart +++ b/lib/src/animation/beam_clock.dart @@ -9,81 +9,73 @@ enum BeamFadeStage { /// Not animating a fade (either idle or fully visible). none, - /// Fading in (0.6s). + /// Fading in ([BeamClock.fadeInSeconds]). fadingIn, - /// Fading out (0.5s). + /// Fading out ([BeamClock.fadeOutSeconds]). fadingOut, } /// The single time source of a beam instance. /// -/// Mirrors the source library's model: every animated value is a pure -/// function of elapsed time, driven by ONE [Ticker] (the React library uses -/// one shared requestAnimationFrame loop). The clock integrates scaled -/// deltas so [speed] changes and pauses keep continuity, runs the -/// fade-in/fade-out envelope (spring-eased via [FadeSpringCurve] unless -/// [fadeCurve] replaces it), and can -/// cap its notification rate for the pulse variants (~30fps in the source). +/// Every animated value is a pure function of elapsed time, driven by ONE +/// [Ticker]. The clock integrates scaled deltas so [speed] changes and +/// pauses keep continuity, and runs the fade-in/fade-out envelope +/// (critically damped springs — [BeamSpringCurve.fadeIn] and +/// [BeamSpringCurve.fadeOut] — unless [fadeCurve] replaces them) and the +/// [pulse]/[flash] boosts on top. It notifies on every display frame — the +/// beam is cheap enough to run at the panel's full rate, 120Hz included. +/// +/// The fades and boosts run on [activeSeconds], real time while ticking, not +/// on the animation timeline: [speed], [seek], and [retime] move the +/// animation without stretching, skipping, or replaying a fade. class BeamClock extends ChangeNotifier { - /// Creates a clock. [createTicker] is typically - /// `TickerProviderStateMixin.createTicker`. [maxFps] caps notification - /// frequency while not fading (null = every frame). [onFadeComplete] fires + /// Creates a clock. `createTicker` is typically + /// `TickerProviderStateMixin.createTicker`. [onFadeComplete] fires /// with `true` when a fade-in finishes and `false` when a fade-out /// finishes. [fadeCurve] replaces the spring easing of both fades. - BeamClock({ - required Ticker Function(TickerCallback) createTicker, - this.maxFps, - this.onFadeComplete, - this.fadeCurve, - }) : _createTicker = createTicker; + BeamClock({required this._createTicker, this.onFadeComplete, this.fadeCurve}); - /// Fade-in duration in seconds (React `beam-fade-in 0.6s`). - static const double fadeInSeconds = 0.6; + /// Fade-in duration in seconds: [BeamSpringCurve.fadeIn]'s settling time, + /// so the spring plays in real time, whatever the [speed]. + static const double fadeInSeconds = 0.475; - /// Fade-out duration in seconds (React `beam-fade-out 0.5s`). - static const double fadeOutSeconds = 0.5; + /// Fade-out duration in seconds: [BeamSpringCurve.fadeOut]'s settling + /// time. + static const double fadeOutSeconds = 0.581; /// How far [pulse] lifts [boost] at its peak. static const double pulsePeak = 2; /// How far [flash] lifts [boost] at its peak. /// - /// High enough that every layer reaches the clamp `BeamLayerUtils` - /// applies, which is what makes the blink read as full opacity. + /// High enough that the beam saturates at full opacity, which is what + /// makes the blink read as a flash. static const double flashPeak = 4; - // Spring-eased fade, isolated here so the curve is trivially replaceable. - static const _defaultFadeCurve = FadeSpringCurve.instance; - final Ticker Function(TickerCallback) _createTicker; - /// Optional notification rate cap (frames per second) while not fading. - final double? maxFps; - /// Fired when a fade completes; the argument is whether the beam is now /// active (`true` after fade-in, `false` after fade-out). final ValueChanged? onFadeComplete; - /// The easing both fades run on; null uses the spring - /// ([FadeSpringCurve]). + /// The easing both fades run on; null uses the springs + /// ([BeamSpringCurve.fadeIn], [BeamSpringCurve.fadeOut]). /// /// Settable so a beam can pick up `BeamPlayback.fadeCurve` after its clock /// exists. It is read per frame, so a change lands on the next one — and /// mid-fade, since both stages read the curve from where they already are. Curve? fadeCurve; - Curve get _fadeCurve => fadeCurve ?? _defaultFadeCurve; - Ticker? _ticker; Duration _lastRaw = Duration.zero; double _elapsed = 0; double _activeSeconds = 0; double _speed = 1; BeamFadeStage _stage = BeamFadeStage.none; + // The [activeSeconds] the current fade started at. double _fadeStart = 0; double _fadeFromOpacity = 0; - double _lastNotify = -1; bool _visible = false; _Boost? _boost; @@ -93,8 +85,9 @@ class BeamClock extends ChangeNotifier { /// Unscaled wall time accumulated while the ticker is running. /// /// Unlike [elapsedSeconds], this is unaffected by playback speed and does - /// not advance while paused. Scheduling uses it for duration limits so an - /// offscreen pause suspends the remaining play time too. + /// not advance while paused. The fades and boosts run on it, and + /// scheduling uses it for duration limits, so an offscreen pause suspends + /// the remaining play time too. double get activeSeconds => _activeSeconds; /// Whether the ticker is currently producing frames. @@ -119,7 +112,7 @@ class BeamClock extends ChangeNotifier { double get boost { final b = _boost; if (b == null) return 1; - return 1 + b.envelopeAt(_elapsed) * (b.peak - 1); + return 1 + b.envelopeAt(_activeSeconds) * (b.peak - 1); } /// Lifts the beam to [pulsePeak] and settles back over ~0.6s — a one-shot @@ -141,7 +134,7 @@ class BeamClock extends ChangeNotifier { void _startBoost(_Boost boost) { if (!_visible || !isRunning) return; - _boost = boost.startingAt(_elapsed); + _boost = boost.startingAt(_activeSeconds); notifyListeners(); } @@ -154,22 +147,28 @@ class BeamClock extends ChangeNotifier { /// The current fade envelope value (0–1). /// - /// The spring curve is lightly under-damped and overshoots its target by - /// up to ~3%; the result is clamped so it is always a valid opacity. + /// The default springs are critically damped and never leave 0–1; the + /// result is clamped anyway, since a custom [fadeCurve] may overshoot. double get fadeOpacity { final raw = switch (_stage) { BeamFadeStage.none => _visible ? 1.0 : 0.0, BeamFadeStage.fadingIn => _fadeFromOpacity + (1 - _fadeFromOpacity) * - _fadeCurve.transform( - ((_elapsed - _fadeStart) / fadeInSeconds).clamp(0.0, 1.0), + (fadeCurve ?? BeamSpringCurve.fadeIn).transform( + ((_activeSeconds - _fadeStart) / fadeInSeconds).clamp( + 0.0, + 1.0, + ), ), BeamFadeStage.fadingOut => _fadeFromOpacity * (1 - - _fadeCurve.transform( - ((_elapsed - _fadeStart) / fadeOutSeconds).clamp(0.0, 1.0), + (fadeCurve ?? BeamSpringCurve.fadeOut).transform( + ((_activeSeconds - _fadeStart) / fadeOutSeconds).clamp( + 0.0, + 1.0, + ), )), }; return raw.clamp(0.0, 1.0); @@ -200,8 +199,11 @@ class BeamClock extends ChangeNotifier { } } - /// Activates the beam: resets the timeline (matching CSS animation restart - /// when `data-active` is re-applied) and fades in. + /// Activates the beam: restarts the timeline from zero and fades in. + /// + /// Mid-fade-out it reverses the fade instead, from the opacity it has + /// reached, and keeps the timeline. A no-op while the beam is already + /// visible — paused or not; [resume] restarts a paused one. void activate() { if (_visible && _stage != BeamFadeStage.fadingOut) return; if (_stage == BeamFadeStage.fadingOut) { @@ -216,7 +218,7 @@ class BeamClock extends ChangeNotifier { } _visible = true; _stage = BeamFadeStage.fadingIn; - _fadeStart = _elapsed; + _fadeStart = _activeSeconds; _startTicker(); notifyListeners(); } @@ -226,12 +228,13 @@ class BeamClock extends ChangeNotifier { if (!_visible || _stage == BeamFadeStage.fadingOut) return; _fadeFromOpacity = fadeOpacity; _stage = BeamFadeStage.fadingOut; - _fadeStart = _elapsed; + _fadeStart = _activeSeconds; _startTicker(); notifyListeners(); } - /// Freezes the timeline, keeping the current frame on screen. + /// Freezes the timeline — and any fade or boost in progress — keeping the + /// current frame on screen. void pause() => _ticker?.stop(); /// Resumes after [pause]. @@ -239,7 +242,8 @@ class BeamClock extends ChangeNotifier { if (_visible && !isRunning) _startTicker(); } - /// Jumps the timeline to [seconds]. + /// Jumps the timeline to [seconds]. A fade or boost in progress carries on + /// as it was. void seek(double seconds) { _elapsed = seconds; notifyListeners(); @@ -251,25 +255,24 @@ class BeamClock extends ChangeNotifier { /// Used when a beam's cycle duration changes mid-run: every animated /// track derived from the cycle reads `elapsed / cycleSeconds`, so /// multiplying elapsed time by `newCycle / oldCycle` leaves each track at - /// the exact fraction it had. The fade envelope and the frame-rate cap - /// are wall-clock schedules, not cycle-relative ones, so their anchors - /// move with the timeline rather than being scaled — the fade keeps its - /// current opacity and its remaining duration. + /// the exact fraction it had. The fades and boosts run on + /// [activeSeconds], not on the timeline, so they keep their current value + /// and their remaining duration. void retime(double factor) { assert(factor > 0, 'retime factor must be positive'); - final shift = _elapsed * factor - _elapsed; - _elapsed += shift; - _fadeStart += shift; - _lastNotify += shift; - _boost = _boost?.shiftedBy(shift); + _elapsed *= factor; notifyListeners(); } /// Marks the beam visible at full opacity without animating (used for /// reduced motion and for initially-active beams that must not fade in). + /// + /// Drops any boost in progress: with the ticker stopped it would otherwise + /// hold its current value forever. void showStatic() { _visible = true; _stage = BeamFadeStage.none; + _boost = null; _ticker?.stop(); notifyListeners(); } @@ -291,32 +294,25 @@ class BeamClock extends ChangeNotifier { _activeSeconds += deltaSeconds; _elapsed += deltaSeconds * _speed; - var mustNotify = true; if (_stage == BeamFadeStage.fadingIn && - _elapsed - _fadeStart >= fadeInSeconds) { + _activeSeconds - _fadeStart >= fadeInSeconds) { _stage = BeamFadeStage.none; onFadeComplete?.call(true); } else if (_stage == BeamFadeStage.fadingOut && - _elapsed - _fadeStart >= fadeOutSeconds) { + _activeSeconds - _fadeStart >= fadeOutSeconds) { _stage = BeamFadeStage.none; _visible = false; _ticker!.stop(); _elapsed = 0; + // Nothing is left to play a boost on, and the stopped ticker would + // otherwise hold one at its current value until the next activation. + _boost = null; _notifyTimelineReset(); onFadeComplete?.call(false); - } else if (_stage == BeamFadeStage.none && maxFps != null && !isBoosting) { - // Rate cap (pulse variants): skip paint-frame notifications, matching - // the source's ~30fps pulse driver. Time still accumulates. A boost is - // short and steep, so it plays at the full frame rate. - final interval = 1 / maxFps! - 0.002; - if (_elapsed - _lastNotify < interval) mustNotify = false; } // Drop a spent boost, keeping the frame that lands back at 1. - if (_boost?.isDoneAt(_elapsed) ?? false) _boost = null; - if (mustNotify) { - _lastNotify = _elapsed; - notifyListeners(); - } + if (_boost?.isDoneAt(_activeSeconds) ?? false) _boost = null; + notifyListeners(); } @override @@ -342,7 +338,7 @@ class _Boost { /// The multiplier at the top of the envelope. final double peak; - /// Seconds spent climbing to [peak], spring-eased like the fade. + /// Seconds spent climbing to [peak], on [BeamSpringCurve.pop]. final double rise; /// Seconds held at [peak]. @@ -352,7 +348,7 @@ class _Boost { /// has no visible corner at either end. final double fall; - /// Timeline position the envelope started at. + /// The [BeamClock.activeSeconds] the envelope started at. final double startedAt; double get _total => rise + hold + fall; @@ -360,21 +356,13 @@ class _Boost { _Boost startingAt(double now) => _Boost(peak: peak, rise: rise, hold: hold, fall: fall, startedAt: now); - _Boost shiftedBy(double shift) => _Boost( - peak: peak, - rise: rise, - hold: hold, - fall: fall, - startedAt: startedAt + shift, - ); - bool isDoneAt(double now) => now - startedAt >= _total; - /// The 0–1 envelope at timeline position [now]. + /// The 0–1 envelope at [BeamClock.activeSeconds] [now]. double envelopeAt(double now) { var x = now - startedAt; if (x <= 0) return rise > 0 ? 0 : 1; - if (x < rise) return FadeSpringCurve.instance.transform(x / rise); + if (x < rise) return BeamSpringCurve.pop.transform(x / rise); x -= rise; if (x < hold) return 1; x -= hold; diff --git a/lib/src/animation/beam_phases.dart b/lib/src/animation/beam_phases.dart index be0e201..17438fd 100644 --- a/lib/src/animation/beam_phases.dart +++ b/lib/src/animation/beam_phases.dart @@ -2,83 +2,50 @@ import 'dart:math' as math; import 'package:flutter/animation.dart' show Curves; -import '../constants/line_keyframes.dart'; -import '../constants/pulse_params.dart'; import '../models/beam_config.dart'; import '../models/beam_options.dart'; -import '../models/beam_variant.dart'; -import 'beam_clock.dart'; -import 'oscillator.dart'; -/// Samples a keyframe table at cycle progress [t] (0–1). +/// The time-driven values one frame is painted from. /// -/// [easedSegments] applies ease-in-out within each segment, matching CSS -/// `animation-timing-function: ease-in-out` semantics (the timing function -/// applies per keyframe segment); linear tables pass `false`. -double sampleKeyframes( - List frames, - double t, { - bool easedSegments = false, -}) { - final clamped = t.clamp(0.0, 1.0); - for (var i = 1; i < frames.length; i++) { - final prev = frames[i - 1]; - final next = frames[i]; - if (clamped <= next.t) { - final span = next.t - prev.t; - if (span <= 0) return next.value; - var local = (clamped - prev.t) / span; - if (easedSegments) local = Curves.easeInOut.transform(local); - return prev.value + (next.value - prev.value) * local; - } - } - return frames.last.value; -} - -/// Every animated value the painter needs for one frame. +/// Effects turn these into light; nothing here knows what an effect looks +/// like. class BeamFramePhases { /// Creates a frame phase snapshot. const BeamFramePhases({ required this.fadeOpacity, required this.hueDegrees, - this.bloomHueDegrees = 0, - this.angleRadians = 0, this.travelProgress = 0, this.travellers = const [0], this.reversedNow = false, this.finished = false, - this.lineX = 0.06, - this.lineW = 0.5, - this.lineH = 0.8, - this.spike = 1, - this.spike2 = 1, - this.edge = 1, - this.pulse = const PulsePhaseSet.identity(), + this.cycles = 0, + this.driven = false, + this.hueTime, }); - /// Fade envelope (0–1), multiplied into every layer opacity. Carries the - /// rest between sweeps (`BeamTiming.cycleGap`) as well as the beam's own - /// fade in and out. + /// Fade envelope (0–1), multiplied into the whole beam. Carries the rest + /// between sweeps (`BeamTiming.cycleGap`) as well as the beam's own fade in + /// and out. final double fadeOpacity; /// Animated hue rotation in degrees (excludes the static hue base). final double hueDegrees; - /// The line bloom's separate hue track (±(hueRange+10)°, over - /// `BeamConfig.bloomHuePeriodSeconds`). - final double bloomHueDegrees; - - /// Rotating conic window angle (rotate/small), radians. - final double angleRadians; + /// The time the hue track reads, in seconds — for effects that run a + /// second hue track of their own. + /// + /// Null when the hue holds still (a static frame): an effect's own tracks + /// then hold the palette's colours too, as [hueDegrees] does at 0. + final double? hueTime; - /// Raw sweep progress (0–1) of the leading beam through the current cycle. + /// Sweep progress (0–1) of the leading beam through the current cycle. /// /// Equal to `travellers.first`. Already carries the travel direction and /// the phase offset, and is the value a driven `BorderBeam.progress` /// replaces. final double travelProgress; - /// Sweep progress (0–1) of every beam travelling the contour, spaced + /// Sweep progress (0–1) of every beam travelling the border, spaced /// `1 / BeamConfig.beamCount` apart. Never empty; the first entry is /// [travelProgress]. final List travellers; @@ -86,209 +53,153 @@ class BeamFramePhases { /// Whether the current cycle runs mirrored — always false under /// [BeamDirection.forward], always true under [BeamDirection.reverse], and /// alternating per cycle under [BeamDirection.bounce]. - /// - /// The geometry in [travellers] is already mirrored; this flag lets a - /// strategy mirror asymmetric tables (a comet tail, a spike schedule) to - /// match. final bool reversedNow; /// Whether the beam has run out its `BeamPlayback.repeat` budget. - /// - /// The widget reacts by deactivating the clock, so the beam fades out the - /// way an inactive one does rather than cutting off. final bool finished; - /// Line beam x position, fraction of width. - final double lineX; - - /// Line beam width factor. - final double lineW; - - /// Line beam height factor. - final double lineH; + /// Elapsed time in cycles (continuous, never wraps): the clock the ambient + /// effects breathe and stream by. + final double cycles; - /// Line spike scale (drives spikes at 8/78/92%; inverted at 36/92%). - final double spike; - - /// Second line spike scale (drives spikes at 22/50/64%). - final double spike2; - - /// Line edge fade factor multiplying all three layers. - final double edge; - - /// Pulse oscillator values. - final PulsePhaseSet pulse; + /// Whether [travelProgress] comes from `BorderBeam.progress` or `follow` + /// rather than the clock. Effects map a driven position linearly (a + /// readout) and a timed one with their own easing. + final bool driven; } -/// Computes [BeamFramePhases] from elapsed time for a given config, -/// mirroring the source's CSS keyframes and JS pulse driver exactly. +/// Computes [BeamFramePhases] from elapsed time for a given config. class BeamPhaseResolver { /// Creates a resolver for [config]. - factory BeamPhaseResolver(BeamConfig config) => BeamPhaseResolver._( - config, - config.variant.isPulse - ? PulseParams.resolve( - config.variant, - config.brightness, - config.cycleSeconds, - ) - : null, - ); - - BeamPhaseResolver._(this.config, PulseParams? pulseParams) - : _bank = pulseParams == null ? null : PulseOscillatorBank(pulseParams); + BeamPhaseResolver(this.config); /// The resolved beam configuration. final BeamConfig config; - final PulseOscillatorBank? _bank; - /// Seconds added to the sample time of the fixed-period hue tracks only. + /// Seconds added to the sample time of the fixed-period hue track only. /// - /// The cycle-derived tracks (rotate angle, line travel, pulse - /// oscillators) all scale with [BeamConfig.cycleSeconds], so a cycle - /// change can be absorbed by rescaling elapsed time - /// ([BeamClock.retime]) — their fractions come out unchanged. The hue - /// tracks run on fixed periods ([BeamConfig.huePeriodSeconds], - /// [BeamConfig.bloomHuePeriodSeconds]) and would jump under that rescale, - /// so the widget shifts them back by the amount the timeline moved. - /// - /// See [breatheTimeOffset] for the cycle-derived tracks that still need a - /// correction, because the retime target is not always a pure rescale. + /// The cycle-derived tracks all scale with [BeamConfig.cycleSeconds], so a + /// cycle change is absorbed by rescaling elapsed time (`BeamClock.retime`). + /// The hue track runs on a fixed period and would jump under that rescale, + /// so the widget shifts it back by the amount the timeline moved. double hueTimeOffset = 0; /// Cycles the beam is allowed to run before it reports /// [BeamFramePhases.finished], or null to run forever. - /// - /// The resolved form of `BeamPlayback.repeat`: playback is the widget's - /// business rather than a painted value, so it rides on the resolver - /// instead of on [BeamConfig]. int? repeatCycles; - /// Seconds added to the sample time of the travel tracks only. + /// Seconds added to the sample time of the travel track only. /// - /// Shifts where the sweep sits without touching the hue tracks. The widget - /// uses it to hand a `BorderBeam.follow` gesture back to the clock: the - /// timed sweep picks up from wherever the pointer left the beam instead of - /// snapping back to its own schedule. + /// The widget uses it to hand a `BorderBeam.follow` gesture back to the + /// clock: the timed sweep picks up from wherever the pointer left the beam. double travelTimeOffset = 0; - /// Seconds added to the sample time of the line variant's breathe and - /// spike tracks only. + /// Seconds added to the sample time of the ambient track + /// ([BeamFramePhases.cycles]) only. /// - /// Those tracks scale with the cycle, so a *pure ratio* rescale of elapsed - /// time is what holds their phase. A retime does not always produce one: - /// once a cycle gap, a phase offset, or a [travelTimeOffset] hand-back is - /// in play, the clock is moved to put the *sweep* where it belongs, and - /// that target is not the pure rescale. The widget sets this to the - /// difference, so these tracks read the timeline they would have had. - /// - /// It corrects for a *cycle* change only. Changing one of the factors that - /// define these periods (`BeamTiming.breatheFactor` and friends) re-phases - /// the affected track by design, the same way changing - /// `BeamTiming.huePeriod` re-phases the hue: a period change describes a - /// different animation, so there is no phase to carry over. The widget - /// drops this offset whenever the timeline restarts. + /// A retime is a pure rescale only without a gap, phase offset, or follow + /// hand-back in play; otherwise the clock is moved to put the *sweep* where + /// it belongs. The widget sets this to the difference, so the ambient track + /// reads the timeline it would have had. double breatheTimeOffset = 0; + bool get _travels => config.effect.travels; + /// Samples all phases at [t] seconds with the given [fadeOpacity]. /// /// [progress] takes the travel over when non-null (`BorderBeam.progress` /// and `BorderBeam.follow`): the sweep sits at that fraction (0–1) instead - /// of running with the clock, while the fade envelope and the hue tracks - /// keep running. A driven progress is used as given — - /// [BeamConfig.direction] and [BeamConfig.phaseOffset] shape the timed - /// sweep, not this value. + /// of running with the clock, while the fade and hue keep running. BeamFramePhases sample(double t, double fadeOpacity, {double? progress}) { - final v = config.variant; final hue = _hue(t); - final sweep = _sweep(t, progress); - switch (v) { - case BeamVariant.rotate || BeamVariant.small: - return BeamFramePhases( - fadeOpacity: fadeOpacity * sweep.envelope, - hueDegrees: hue, - angleRadians: sweep.travellers.first * 2 * math.pi, - travelProgress: sweep.travellers.first, - travellers: sweep.travellers, - reversedNow: sweep.reversed, - finished: sweep.finished, - ); - case BeamVariant.line: - final head = sweep.travellers.first; - final cs = config.cycleSeconds; - final bt = t + breatheTimeOffset; - final breathe = (bt / (cs * config.breatheFactor)) % 1.0; - final spikeT = (bt / (cs * config.spikeFactor)) % 1.0; - final spike2T = (bt / (cs * config.spike2Factor)) % 1.0; - return BeamFramePhases( - fadeOpacity: fadeOpacity * sweep.envelope, - hueDegrees: hue, - bloomHueDegrees: _pingPongHue( - t + hueTimeOffset, - config.bloomHuePeriodSeconds, - config.hueRange + 10, - ), - travelProgress: head, - travellers: sweep.travellers, - reversedNow: sweep.reversed, - finished: sweep.finished, - lineX: sampleKeyframes(lineTravelX, head), - lineW: sampleKeyframes(lineTravelW, head), - edge: sampleKeyframes(lineEdgeFade, head), - lineH: sampleKeyframes(lineBreatheH, breathe, easedSegments: true), - spike: sampleKeyframes(lineSpike, spikeT, easedSegments: true), - spike2: sampleKeyframes(lineSpike2, spike2T, easedSegments: true), - ); - case BeamVariant.pulseInside || BeamVariant.pulseOutside: - return BeamFramePhases( - fadeOpacity: fadeOpacity, - hueDegrees: hue, - finished: sweep.finished, - pulse: _bank!.sample(t), - ); + // The phase offset moves the breathing along with the sweep, so two beams + // on different offsets are out of step whichever family they belong to. + final cycles = + (t + breatheTimeOffset) / config.cycleSeconds + config.phaseOffset; + if (!_travels) { + return BeamFramePhases( + fadeOpacity: fadeOpacity, + hueDegrees: hue, + hueTime: t + hueTimeOffset, + reversedNow: config.direction == BeamDirection.reverse, + finished: _finished(_shift(t)), + cycles: cycles, + ); } + final sweep = _sweep(t, progress); + return BeamFramePhases( + fadeOpacity: fadeOpacity * sweep.envelope, + hueDegrees: hue, + hueTime: t + hueTimeOffset, + travelProgress: sweep.travellers.first, + travellers: sweep.travellers, + reversedNow: sweep.reversed, + finished: sweep.finished, + cycles: cycles, + driven: progress != null, + ); } /// Whether the beam has spent its [repeatCycles] budget at [t] seconds. - /// - /// The same test [sample] reports through [BeamFramePhases.finished], - /// without building a frame: the widget checks it every tick. - bool finishedAt(double t) { + bool finishedAt(double t) => _finished(_shift(t)); + + bool _finished(double shifted) { final budget = repeatCycles; - if (budget == null) return false; - return _cycleIndex(_shift(t)) >= budget; + return budget != null && _cycleIndex(shifted) >= budget; } - /// The travel timeline at [t]: the phase offset and any follow hand-back - /// folded in. double _shift(double t) => t + config.phaseOffset * config.cycleSeconds + travelTimeOffset; + double get _period => + config.cycleSeconds + (_travels ? config.gapSeconds : 0); + int _cycleIndex(double shifted) { - final period = - config.cycleSeconds + (config.variant.isPulse ? 0 : config.gapSeconds); + final period = _period; return period <= 0 ? 0 : (shifted / period).floor(); } - /// The travel state of every beam at [t]: their progress, the gap - /// envelope, whether this cycle runs mirrored, and whether the repeat - /// budget is spent. + bool _reversedIn(int cycleIndex) => switch (config.direction) { + BeamDirection.forward => false, + BeamDirection.reverse => true, + BeamDirection.bounce => cycleIndex.isOdd, + }; + + /// The [travelTimeOffset] at which the timed sweep sits at [progress] + /// (0–1) at [t] seconds — how the widget hands a `BorderBeam.follow` + /// gesture back to the clock without a snap. + /// + /// Of the timeline positions that put the sweep at [progress] mid-run, + /// travelling the way it travels now, this picks the nearest: within the + /// current cycle, or — unless the direction alternates — a cycle either + /// side. So a bouncing beam keeps its direction, and a beam pulled out of + /// the rest between sweeps resumes its sweep rather than the rest. + double travelOffsetHolding(double t, double progress) { + final shifted = _shift(t); + final cycle = config.cycleSeconds; + final period = _period; + final index = _cycleIndex(shifted); + final p = progress.isNaN ? 0.0 : progress.clamp(0.0, 1.0); + // Just short of the cycle end, which is the next cycle's start. + final forward = math.min(_reversedIn(index) ? 1 - p : p, 1 - 1e-9); + var target = index * period + forward * cycle; + if (config.direction != BeamDirection.bounce && period > 0) { + final distance = (target - shifted).abs(); + if ((target - period - shifted).abs() < distance) { + target -= period; + } else if ((target + period - shifted).abs() < distance) { + target += period; + } + } + return travelTimeOffset + target - shifted; + } + _Sweep _sweep(double t, double? driven) { - // The phase offset moves the beam along its own timeline; the hue tracks - // run on fixed periods of their own and stay where they are. final shifted = _shift(t); final cycleIndex = _cycleIndex(shifted); - final budget = repeatCycles; - final finished = budget != null && cycleIndex >= budget; - final reversed = switch (config.direction) { - BeamDirection.forward => false, - BeamDirection.reverse => true, - BeamDirection.bounce => cycleIndex.isOdd, - }; - + final finished = _finished(shifted); + final reversed = _reversedIn(cycleIndex); if (driven != null) { - // A driven progress replaces the sweep outright, so there is no gap to - // rest in either. final head = driven.clamp(0.0, 1.0); return _Sweep(_spread(head), 1, false, finished); } @@ -302,8 +213,6 @@ class BeamPhaseResolver { ); } - /// Places [head] and the remaining `beamCount - 1` beams evenly around the - /// cycle, keeping [head] first. List _spread(double head, {bool reversed = false}) { final n = config.beamCount; if (n <= 1) return [head]; @@ -315,41 +224,60 @@ class BeamPhaseResolver { }); } - /// A representative static frame for reduced motion: mid-cycle, no hue - /// offset, full opacity. + /// A representative static frame for reduced motion: full opacity, the + /// palette's own colours, travelling effects mid-sweep. /// - /// The frame is shown for as long as reduced motion lasts, so it carries - /// the palette's own colors — a hue sampled from the ping-pong would tint - /// the whole effect by an arbitrary offset. + /// The sweep is the first cycle's, partway through, facing the way the beam + /// travels: a reversed beam's head, its trail, and the beams behind it are + /// mirrored exactly as they are when it runs. + /// + /// The ambient clock ([BeamFramePhases.cycles]) carries the phase offset + /// as it does when the beam runs, so still beams on different offsets + /// breathe at different points rather than in lockstep. The sweep does + /// not: it stays where it is lit. /// /// A driven [progress] is honored: a beam whose sweep is a progress /// readout still reads its value under reduced motion. BeamFramePhases staticFrame({double? progress}) { - if (config.variant.isPulse) { - // Freeze the breathing at rest, matching the source's - // prefers-reduced-motion behavior (animations disabled entirely). - return const BeamFramePhases(fadeOpacity: 1, hueDegrees: 0); + if (!_travels) { + return BeamFramePhases( + fadeOpacity: 1, + hueDegrees: 0, + cycles: _staticCycles, + reversedNow: config.direction == BeamDirection.reverse, + ); + } + if (progress != null) { + final head = progress.clamp(0.0, 1.0); + return BeamFramePhases( + fadeOpacity: 1, + hueDegrees: 0, + travelProgress: head, + travellers: _spread(head), + cycles: _staticCycles, + driven: true, + ); } - // The traveling variants keep their mid-cycle geometry. - final phases = sample(config.cycleSeconds / 2, 1, progress: progress); + final reversed = _reversedIn(0); + final head = reversed ? 1 - _staticSweep : _staticSweep; return BeamFramePhases( fadeOpacity: 1, hueDegrees: 0, - angleRadians: phases.angleRadians, - travelProgress: phases.travelProgress, - travellers: phases.travellers, - reversedNow: phases.reversedNow, - lineX: phases.lineX, - lineW: phases.lineW, - lineH: phases.lineH, - spike: phases.spike, - spike2: phases.spike2, - edge: phases.edge, + travelProgress: head, + travellers: _spread(head, reversed: reversed), + reversedNow: reversed, + cycles: _staticCycles, ); } - /// Travel progress through one sweep (0–1) and the gap envelope that - /// multiplies into the fade at [t]. + // How far through its sweep a travelling effect's static frame sits. + static const double _staticSweep = 0.35; + + // The ambient clock of a static frame: a representative instant, moved by + // the phase offset the way `sample` moves it. + double get _staticCycles => 0.3 + config.phaseOffset; + + /// Travel progress through one sweep (0–1) and the gap envelope at [t]. /// /// Without a gap this is the plain `t / cycle` wrap. With one, the sweep /// runs over the first `cycleSeconds` of each `cycle + gap` period and then @@ -372,29 +300,25 @@ class BeamPhaseResolver { return (1.0, 0.0); } - // Smoothstep: zero slope at both ends, so the rest opens and closes without - // a visible corner. static double _smoothstep(double x) { final c = x.clamp(0.0, 1.0); return c * c * (3 - 2 * c); } double _hue(double t) { - if (config.staticColors) return 0; final hueT = t + hueTimeOffset; return switch (config.hueMode) { - // Continuous full revolution (sawtooth 0→360°). + BeamHueMode.none => 0, BeamHueMode.continuous => ((hueT / config.huePeriodSeconds) % 1.0) * 360, BeamHueMode.pingPong => _pingPongHue( hueT, config.huePeriodSeconds, - config.hueRange, + config.hueShift, ), }; } - // CSS `beam-hue-shift`: keyframes −range @0%, +range @50%, −range @100%, - // ease-in-out per segment. + // −range at 0%, +range at 50%, −range at 100%, eased per half. static double _pingPongHue(double t, double period, double range) { final cycle = (t / period) % 1.0; final local = cycle < 0.5 ? cycle / 0.5 : (1 - cycle) / 0.5; @@ -403,8 +327,6 @@ class BeamPhaseResolver { } } -/// One frame of travel: where every beam sits, the gap envelope, whether the -/// cycle is mirrored, and whether the repeat budget is spent. class _Sweep { const _Sweep(this.travellers, this.envelope, this.reversed, this.finished); diff --git a/lib/src/animation/oscillator.dart b/lib/src/animation/oscillator.dart deleted file mode 100644 index 4a89067..0000000 --- a/lib/src/animation/oscillator.dart +++ /dev/null @@ -1,201 +0,0 @@ -import 'dart:math' as math; - -import 'package:flutter/foundation.dart'; - -import '../constants/pulse_params.dart'; - -/// The cosine ping-pong easing of the source's pulse driver: -/// 0 at integer phases, 1 at half-integer phases, smooth in between. -/// Negative phases (from positive delays) are valid — cosine is even. -double pingPong(double phase) => (1 - math.cos(2 * math.pi * phase)) / 2; - -/// A single sinusoidal oscillator ping-ponging between [a] and [b] over -/// [period] seconds, phase-shifted by [delay] seconds. -class PulseOscillator { - /// Creates an oscillator. - const PulseOscillator({ - required this.a, - required this.b, - required this.period, - this.delay = 0, - }); - - /// Value at phase 0 (and every full period). - final double a; - - /// Value at half period. - final double b; - - /// Full period in seconds. - final double period; - - /// Phase offset in seconds (desyncs otherwise-identical oscillators). - final double delay; - - /// Samples the oscillator at [t] seconds. - double sample(double t) => a + (b - a) * pingPong((t - delay) / period); -} - -/// The animated pulse values for one frame: three blob size/drift groups, a -/// global height factor, and four corner opacity factors. -class PulsePhaseSet { - /// Creates a phase set. See [PulseOscillatorBank.sample]. - const PulsePhaseSet({ - required this.bw, - required this.bh, - required this.bx, - required this.by, - required this.bgh, - required this.bopTl, - required this.bopTr, - required this.bopBl, - required this.bopBr, - }); - - /// A static set with every factor at rest (used for reduced motion). - const PulsePhaseSet.identity() - : bw = const [1, 1, 1], - bh = const [1, 1, 1], - bx = const [0, 0, 0], - by = const [0, 0, 0], - bgh = 1, - bopTl = 1, - bopTr = 1, - bopBl = 1, - bopBr = 1; - - /// Width factors for regions 1–3 (index 0–2). - final List bw; - - /// Height factors for regions 1–3. - final List bh; - - /// Horizontal drift in px for regions 1–3. - final List bx; - - /// Vertical drift in px for regions 1–3. - final List by; - - /// Global height breathing factor. - final double bgh; - - /// Top-left corner opacity factor. - final double bopTl; - - /// Top-right corner opacity factor. - final double bopTr; - - /// Bottom-left corner opacity factor. - final double bopBl; - - /// Bottom-right corner opacity factor. - final double bopBr; -} - -/// The 17-oscillator table of the source's pulse driver -/// (React `pulseOscillatorDefs`), parameterized by [PulseParams]. -class PulseOscillatorBank { - /// Builds the bank for tuned parameters [p]. - PulseOscillatorBank(PulseParams p) - : _bw = [ - PulseOscillator(a: 1 - p.sp, b: 1 + p.sp * 1.1, period: p.ss * 0.9), - PulseOscillator(a: 1 + p.sp, b: 1 - p.sp * 0.85, period: p.ss * 1.1), - PulseOscillator( - a: 1 - p.sp * 0.6, - b: 1 + p.sp * 1.15, - period: p.ss * 0.98, - ), - ], - _bh = [ - PulseOscillator( - a: 1 + p.sp * 0.9, - b: 1 - p.sp * 0.85, - period: p.ss * 1.26, - ), - PulseOscillator( - a: 1 - p.sp * 0.8, - b: 1 + p.sp * 1.05, - period: p.ss * 0.81, - ), - PulseOscillator(a: 1 + p.sp * 0.75, b: 1 - p.sp, period: p.ss * 1.4), - ], - _bx = [ - PulseOscillator(a: -p.dr, b: p.dr * 0.9, period: p.bs * 1.6), - PulseOscillator(a: p.dr * 0.8, b: -p.dr * 0.9, period: p.bs * 1.88), - PulseOscillator(a: -p.dr * 0.6, b: p.dr, period: p.bs * 1.45), - ], - _by = [ - PulseOscillator(a: p.dr * 0.55, b: -p.dr * 0.7, period: p.bs * 1.6), - PulseOscillator(a: -p.dr, b: p.dr * 0.65, period: p.bs * 1.88), - PulseOscillator(a: -p.dr * 0.85, b: p.dr * 0.45, period: p.bs * 1.45), - ], - _bgh = PulseOscillator(a: 1 - p.gh, b: 1 + p.gh, period: p.ghs), - _bop = [ - PulseOscillator(a: 1 - p.op, b: 1, period: p.bs), - PulseOscillator( - a: 1 - p.op, - b: 1, - period: p.bs * 1.32, - delay: p.bs * 0.28, - ), - PulseOscillator( - a: 1 - p.op, - b: 1, - period: p.bs * 0.84, - delay: p.bs * 0.55, - ), - PulseOscillator( - a: 1 - p.op, - b: 1, - period: p.bs * 1.58, - delay: p.bs * 0.83, - ), - ]; - - final List _bw; - final List _bh; - final List _bx; - final List _by; - final PulseOscillator _bgh; - final List _bop; - - /// The bank's 17 oscillators keyed by the source's CSS custom-property - /// name, in the source's declaration order. - /// - /// Exposed so `test/constants/spec_parity_test.dart` can assert the whole - /// table against `pulse...oscillators` in the upstream - /// spec, which carries the same names. - @visibleForTesting - Map get oscillators => { - 'bw1': _bw[0], - 'bh1': _bh[0], - 'bx1': _bx[0], - 'by1': _by[0], - 'bw2': _bw[1], - 'bh2': _bh[1], - 'bx2': _bx[1], - 'by2': _by[1], - 'bw3': _bw[2], - 'bh3': _bh[2], - 'bx3': _bx[2], - 'by3': _by[2], - 'bgh': _bgh, - 'bop-tl': _bop[0], - 'bop-tr': _bop[1], - 'bop-bl': _bop[2], - 'bop-br': _bop[3], - }; - - /// Samples every oscillator at [t] seconds. - PulsePhaseSet sample(double t) => PulsePhaseSet( - bw: [for (final o in _bw) o.sample(t)], - bh: [for (final o in _bh) o.sample(t)], - bx: [for (final o in _bx) o.sample(t)], - by: [for (final o in _by) o.sample(t)], - bgh: _bgh.sample(t), - bopTl: _bop[0].sample(t), - bopTr: _bop[1].sample(t), - bopBl: _bop[2].sample(t), - bopBr: _bop[3].sample(t), - ); -} diff --git a/lib/src/animation/spring_curve.dart b/lib/src/animation/spring_curve.dart index 9c7eecf..d3ace6c 100644 --- a/lib/src/animation/spring_curve.dart +++ b/lib/src/animation/spring_curve.dart @@ -1,44 +1,110 @@ +import 'dart:math' as math; + import 'package:flutter/animation.dart'; -import 'package:flutter/physics.dart'; -/// The easing curve behind the beam's fade-in / fade-out envelope. -/// -/// The envelope is driven by a real spring simulation rather than a cubic -/// bezier so the beam settles with a little momentum instead of decelerating -/// mechanically. The spring is displaced by 1 with no initial velocity and -/// simulated over `t ∈ [0, 1]`: -/// -/// * mass `1.0` -/// * stiffness `180.0` -/// * damping `20.0` +/// A spring described the way Apple's animation APIs describe one — a +/// damping ratio and a response — as a [Curve] over the time it takes to +/// settle. /// -/// Those give a damping ratio of `ζ = damping / (2·√(mass·stiffness)) ≈ 0.745`, -/// i.e. a lightly under-damped spring: the value rises past its target, peaks -/// at about `1.03` near `t ≈ 0.35`, and oscillates back down. Callers that -/// feed the result to an opacity must clamp it (see `BeamClock.fadeOpacity`). +/// * [dampingRatio] (ζ): `1` settles without overshoot (SwiftUI's `.smooth`); +/// below 1 the value overshoots and rings back, lower being bouncier. +/// * [response] (seconds): the period of the spring's undamped oscillation — +/// its perceptual duration. /// -/// The simulation has not fully settled at `t = 1`, so the residual is -/// distributed linearly across the curve; that keeps `transform(1) == 1` -/// exactly while leaving the shape untouched. -final class FadeSpringCurve extends Curve { - /// Creates the fade envelope curve. The curve is stateless — prefer the - /// shared [instance]. - const FadeSpringCurve(); - - /// The shared instance of the curve. - static const FadeSpringCurve instance = FadeSpringCurve(); - - static final SpringSimulation _simulation = SpringSimulation( - // mass, stiffness, damping — see the class doc. - SpringDescription(mass: 1, stiffness: 180, damping: 20), - 0, - 1, - 0, +/// The curve's `[0, 1]` spans [settlingSeconds], the time until what is left +/// of the motion is imperceptible, so running it over exactly that long plays +/// the spring in real time. It starts from rest — easing in as well as out — +/// and reaches exactly 1 at `t = 1`. +final class BeamSpringCurve extends Curve { + /// A spring with damping ratio [dampingRatio] (critically damped at 1, or + /// at most 0.9 for a bounce) and [response] seconds. + const BeamSpringCurve({required this.dampingRatio, required this.response}) + : assert( + dampingRatio == 1 || (dampingRatio > 0 && dampingRatio <= 0.9), + 'dampingRatio must be 1 or in (0, 0.9]', + ), + assert(response > 0, 'response must be positive'); + + /// The fade-in envelope: critically damped, so an opacity glides up to 1 + /// and never overshoots it. + static const BeamSpringCurve fadeIn = BeamSpringCurve( + dampingRatio: 1, + response: 0.45, + ); + + /// The fade-out envelope: critically damped with a longer response than + /// [fadeIn], so the light leaves a little more gently than it arrives and + /// settles into nothing instead of stopping. + static const BeamSpringCurve fadeOut = BeamSpringCurve( + dampingRatio: 1, + response: 0.55, ); - /// How far short of 1 the simulation is when `t` reaches 1. - static final double _endCorrection = 1 - _simulation.x(1); + /// The rise of a pulse or flash accent: a light bounce, so the boost pops + /// past its peak and settles back. + static const BeamSpringCurve pop = BeamSpringCurve( + dampingRatio: 0.75, + response: 0.3, + ); + + /// Damping ratio ζ — 1 is critical damping (no overshoot). + final double dampingRatio; + + /// Response in seconds — the undamped period `2π / ω₀`. + final double response; + + /// How long the spring takes to settle: the duration to run the curve over + /// so it plays in real time. + double get settlingSeconds => + _settlePhase(dampingRatio) * response / (2 * math.pi); + + @override + double transformInternal(double t) { + final settle = _settlePhase(dampingRatio); + return _position(dampingRatio, t * settle) / + _position(dampingRatio, settle); + } + + @override + bool operator ==(Object other) => + other is BeamSpringCurve && + other.dampingRatio == dampingRatio && + other.response == response; @override - double transformInternal(double t) => _simulation.x(t) + t * _endCorrection; + int get hashCode => Object.hash(dampingRatio, response); + + @override + String toString() => + 'BeamSpringCurve(dampingRatio: $dampingRatio, response: ${response}s)'; +} + +/// `ω₀·t` at which a critically damped spring's remaining distance +/// `(1 + u)·e^(−u)` falls to 1% of its travel. A critically damped approach is +/// monotone, so nothing worth waiting for is left after it. +const double _criticalSettlePhase = 6.6383521; + +/// The remaining distance an underdamped spring settles to: tighter than the +/// critical 1%, since the curve is normalised by its value at the settle +/// phase and the overshoot has to survive that division. +const double _overshootSettleTolerance = 0.001; + +/// The phase `u = ω₀·t` at which a spring with damping ratio [zeta] has +/// settled. +double _settlePhase(double zeta) { + if (zeta >= 1) return _criticalSettlePhase; + return math.log( + 1 / (_overshootSettleTolerance * math.sqrt(1 - zeta * zeta)), + ) / + zeta; +} + +/// The position of a unit spring released from rest at 0 toward 1, at phase +/// `u = ω₀·t`: the closed-form damped oscillator. +double _position(double zeta, double u) { + if (zeta >= 1) return 1 - (1 + u) * math.exp(-u); + final damped = math.sqrt(1 - zeta * zeta); + return 1 - + math.exp(-zeta * u) * + (math.cos(damped * u) + (zeta / damped) * math.sin(damped * u)); } diff --git a/lib/src/beam_sync.dart b/lib/src/beam_sync.dart index 78f6b77..3410313 100644 --- a/lib/src/beam_sync.dart +++ b/lib/src/beam_sync.dart @@ -1,8 +1,13 @@ +/// @docImport 'package:flutter/scheduler.dart'; +/// @docImport 'border_beam.dart'; +library; + import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; import 'animation/beam_clock.dart'; import 'models/beam_options.dart'; +import 'models/model_validation.dart'; /// Runs every [BorderBeam] below it off one shared clock, so a group of /// beams animates in lockstep. @@ -18,18 +23,18 @@ import 'models/beam_options.dart'; /// child: Row( /// children: [ /// for (final card in cards) -/// BorderBeam.rotate(child: card), +/// BorderBeam(child: card), /// ], /// ), /// ) /// ``` /// -/// Beams stay individually configurable — palette, variant, shape, and +/// Beams stay individually configurable — effect, palette, shape, and /// `BeamTiming.phaseOffset` are still per beam, so a group can run evenly /// spaced around the cycle rather than perfectly on top of each other: /// /// ```dart -/// BorderBeam.rotate( +/// BorderBeam( /// timing: BeamTiming(phaseOffset: i / cards.length), /// child: card, /// ) @@ -37,8 +42,9 @@ import 'models/beam_options.dart'; /// /// The group owns playback. A synced beam does not start, stop, pause, or /// fade on its own, so `BeamPlayback`'s `active`, `autoPlay`, `startAfter`, -/// `duration`, and `repeat` are ignored below a [BeamSync] — use [active] -/// and [speed] here instead. A `BorderBeamController` is playback control +/// `duration`, `repeat`, `fadeCurve`, and `pauseWhenOffscreen` are ignored +/// below a [BeamSync], as is `BeamTiming.speed` — use [active] and [speed] +/// here instead. A `BorderBeamController` is playback control /// for one beam and asserts if it meets a [BeamSync]. /// /// Reduced motion is necessarily group-owned too: one shared clock cannot @@ -53,32 +59,25 @@ class BeamSync extends StatefulWidget { this.active = true, this.speed = 1, this.reducedMotion = BeamReducedMotion.staticFrame, - }); + }) : assert( + speed > 0 && speed < double.infinity, + 'BeamSync.speed must be finite and positive', + ); /// The subtree whose beams share the clock. final Widget child; - /// Whether the group is playing. Toggling fades every beam in (0.6s) or - /// out (0.5s) together. + /// Whether the group is playing. Toggling fades every beam in (about 0.5s) + /// or out (about 0.6s) together. final bool active; - /// Playback rate for the group; must be positive. + /// Playback rate for the group; must be finite and positive. Default 1. final double speed; /// How the whole group responds to the platform reduced-motion request. + /// Default [BeamReducedMotion.staticFrame]. final BeamReducedMotion reducedMotion; - /// The shared clock for [context], or null when there is no enclosing - /// [BeamSync]. Internal — do not call from application code. - static BeamClock? clockOf(BuildContext context) => - context.dependOnInheritedWidgetOfExactType()?.clock; - - /// The reduced-motion policy owned by the nearest group, or null when the - /// beam is not synchronized. - static BeamReducedMotion? reducedMotionOf(BuildContext context) => context - .dependOnInheritedWidgetOfExactType() - ?.reducedMotion; - @override State createState() => _BeamSyncState(); @@ -95,16 +94,18 @@ class BeamSync extends StatefulWidget { class _BeamSyncState extends State with SingleTickerProviderStateMixin { late final BeamClock _clock = BeamClock(createTicker: createTicker) - ..speed = widget.speed; + ..speed = validateSpeed(widget.speed, 'BeamSync.speed'); bool _started = false; bool _reduced = false; + // The constructor only asserts, so the rate is checked here as well, where + // release builds run it before it reaches the shared clock. void _applySpeed() { final factor = _reduced && widget.reducedMotion == BeamReducedMotion.slow - ? 0.25 + ? slowMotionFactor : 1.0; - _clock.speed = widget.speed * factor; + _clock.speed = validateSpeed(widget.speed, 'BeamSync.speed') * factor; } // Puts the group's clock back in motion. A clock that is mid-fade-out is @@ -179,8 +180,10 @@ class _BeamSyncState extends State ); } -/// Carries a [BeamSync]'s shared clock down the tree. Internal — read it -/// through [BeamSync.clockOf]. +/// Carries a [BeamSync]'s shared clock down the tree. +/// +/// Package-internal: the library exports only [BeamSync], so these lookups +/// stay out of the public API. [BorderBeam] is their only caller. class BeamSyncScope extends InheritedWidget { /// Creates the scope for [clock]. const BeamSyncScope({ @@ -190,6 +193,17 @@ class BeamSyncScope extends InheritedWidget { required super.child, }); + /// The shared clock for [context], or null when there is no enclosing + /// [BeamSync]. + static BeamClock? clockOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.clock; + + /// The reduced-motion policy owned by the nearest group, or null when the + /// beam is not synchronized. + static BeamReducedMotion? reducedMotionOf(BuildContext context) => context + .dependOnInheritedWidgetOfExactType() + ?.reducedMotion; + /// The clock every beam in this subtree runs on. final BeamClock clock; diff --git a/lib/src/border_beam.dart b/lib/src/border_beam.dart index c07dc6e..9a6981f 100644 --- a/lib/src/border_beam.dart +++ b/lib/src/border_beam.dart @@ -1,14 +1,18 @@ import 'dart:async'; -import 'dart:math' as math; import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +// Material supplies the ambient `Theme` brightness a beam's surface tuning +// follows (`BeamTheme.auto`). +import 'package:material_ui/material_ui.dart'; import 'animation/beam_clock.dart'; import 'animation/beam_phases.dart'; import 'beam_sync.dart'; import 'border_beam_controller.dart'; import 'border_beam_theme.dart'; +import 'effects/beam_effect.dart'; +import 'effects/effect_emitters.dart' show conicFraction; import 'models/beam_colors.dart'; import 'models/beam_config.dart'; import 'models/beam_options.dart'; @@ -17,25 +21,20 @@ import 'models/beam_shape.dart'; import 'models/beam_style.dart'; import 'models/beam_theme.dart'; import 'models/beam_timing.dart'; -import 'models/beam_variant.dart'; import 'models/model_validation.dart'; -import 'painting/beam_painter.dart'; -import 'painting/variant_strategy.dart'; +import 'render/beam_outline.dart'; +import 'render/beam_painter.dart'; +import 'render/beam_program.dart'; +import 'render/beam_renderer.dart'; /// An animated glow around [child]'s border. /// -/// A faithful Flutter port of the border-beam React library. Pick a variant -/// through the named constructors — or pass one to the generic constructor -/// when the choice is made at runtime: -/// -/// - [BorderBeam.rotate] — full border traveling beam (cards, surfaces). -/// - [BorderBeam.small] — compact traveling beam (buttons, icons). -/// - [BorderBeam.line] — beam traveling along the bottom edge (inputs). -/// - [BorderBeam.pulseInside] — contained breathing glow. -/// - [BorderBeam.pulseOutside] — outward-blooming halo behind the child. +/// Pick what the light does with [effect] — a travelling beam, a streak on +/// one edge, or a breathing pulse: /// /// ```dart -/// BorderBeam.rotate( +/// BorderBeam( +/// effect: const BeamEffect.rotate(), /// colors: BeamColors.ocean, /// borderRadius: 16, /// child: Card(child: content), @@ -47,7 +46,7 @@ import 'painting/variant_strategy.dart'; /// /// ```dart /// BorderBeam( -/// variant: variant, +/// effect: const BeamEffect.line(), /// style: const BeamStyle(colors: BeamColors.sunset, strength: 0.8), /// shape: const BeamShape.all(24, superellipse: true), /// timing: const BeamTiming(cycleGap: Duration(seconds: 1)), @@ -55,18 +54,21 @@ import 'painting/variant_strategy.dart'; /// ) /// ``` /// -/// A field left null falls through to the nearest [BorderBeamTheme], then to -/// the variant's own preset — so app-wide defaults live in one place. +/// A field left null — [effect] included — falls through to the nearest +/// [BorderBeamTheme], then to the effect's own default. /// -/// The beam layers are purely decorative: they never intercept pointer -/// events and only paint — [child] is laid out and hit-tested normally. +/// The beam is drawn by one fragment shader in a single draw call over the +/// child: no offscreen layers, no blurs, no clips. It never intercepts +/// pointer events and adds no semantics — [child] is laid out and hit-tested +/// normally. /// /// ## Scheduling /// /// Without a [controller], the beam plays by itself: `playback.autoPlay` /// starts it (after `playback.startAfter`, if given) and `playback.duration` /// bounds the total play time (null loops forever). Toggling [active] fades -/// the beam in (0.6s) and out (0.5s) with spring-eased envelopes; +/// the beam in (about 0.5s) and out (about 0.6s) on critically damped +/// springs; /// [onActivate]/[onDeactivate] fire when the fades complete. /// /// With a [BorderBeamController] attached, the controller owns playback @@ -74,19 +76,17 @@ import 'painting/variant_strategy.dart'; /// (on the widget or on a [BorderBeamTheme]), and the controller's own /// `speed` replaces `timing.speed`. /// -/// ## pulse-outside requirements +/// ## Light outside the bounds /// -/// [BorderBeam.pulseOutside] paints its glow *behind* the child and *outside* -/// its bounds. The child must be opaque (so only the outward spill shows), -/// should carry its own 1px border for a defined idle edge, and needs -/// clip-free room around it (padding in the parent; no tight [ClipRRect]). +/// Light that reaches outward — rotate's `comet`, a positive +/// `shape.ringOffset` — paints past the child's bounds. Give them clip-free +/// room (padding in the parent; no tight [ClipRRect] above the beam). class BorderBeam extends StatefulWidget { - /// Creates a beam of any [variant], for when the variant is picked at - /// runtime. The named constructors are the readable form when it is not. + /// Creates a beam around [child]. const BorderBeam({ super.key, - required this.variant, required this.child, + this.effect, this.colors, this.active, this.borderRadius, @@ -122,7 +122,7 @@ class BorderBeam extends StatefulWidget { /// ``` const BorderBeam.overlay({ Key? key, - BeamVariant variant = BeamVariant.rotate, + BeamEffect? effect, BeamColors? colors, bool? active, double? borderRadius, @@ -139,7 +139,7 @@ class BorderBeam extends StatefulWidget { VoidCallback? onDeactivate, }) : this( key: key, - variant: variant, + effect: effect, child: const SizedBox.expand(), colors: colors, active: active, @@ -157,207 +157,9 @@ class BorderBeam extends StatefulWidget { onDeactivate: onDeactivate, ); - /// Full border traveling beam (React `md`). The default look, tuned for - /// cards and larger surfaces. - const BorderBeam.rotate({ - Key? key, - required Widget child, - BeamColors? colors, - bool? active, - double? borderRadius, - BeamStyle? style, - BeamShape? shape, - BeamTiming? timing, - BeamPlayback? playback, - BorderBeamController? controller, - double? progress, - Offset? follow, - ValueListenable? strengthListenable, - ValueListenable? speedListenable, - VoidCallback? onActivate, - VoidCallback? onDeactivate, - }) : this( - key: key, - variant: BeamVariant.rotate, - child: child, - colors: colors, - active: active, - borderRadius: borderRadius, - style: style, - shape: shape, - timing: timing, - playback: playback, - controller: controller, - progress: progress, - follow: follow, - strengthListenable: strengthListenable, - speedListenable: speedListenable, - onActivate: onActivate, - onDeactivate: onDeactivate, - ); - - /// Compact traveling beam for small elements (React `sm`) — icon buttons, - /// chips. Defaults to a 32px radius. - const BorderBeam.small({ - Key? key, - required Widget child, - BeamColors? colors, - bool? active, - double? borderRadius, - BeamStyle? style, - BeamShape? shape, - BeamTiming? timing, - BeamPlayback? playback, - BorderBeamController? controller, - double? progress, - Offset? follow, - ValueListenable? strengthListenable, - ValueListenable? speedListenable, - VoidCallback? onActivate, - VoidCallback? onDeactivate, - }) : this( - key: key, - variant: BeamVariant.small, - child: child, - colors: colors, - active: active, - borderRadius: borderRadius, - style: style, - shape: shape, - timing: timing, - playback: playback, - controller: controller, - progress: progress, - follow: follow, - strengthListenable: strengthListenable, - speedListenable: speedListenable, - onActivate: onActivate, - onDeactivate: onDeactivate, - ); - - /// Bottom-edge traveling beam (React `line`) — search bars, text inputs. - /// The hue animation range is capped at 13°, as in the source. - const BorderBeam.line({ - Key? key, - required Widget child, - BeamColors? colors, - bool? active, - double? borderRadius, - BeamStyle? style, - BeamShape? shape, - BeamTiming? timing, - BeamPlayback? playback, - BorderBeamController? controller, - double? progress, - Offset? follow, - ValueListenable? strengthListenable, - ValueListenable? speedListenable, - VoidCallback? onActivate, - VoidCallback? onDeactivate, - }) : this( - key: key, - variant: BeamVariant.line, - child: child, - colors: colors, - active: active, - borderRadius: borderRadius, - style: style, - shape: shape, - timing: timing, - playback: playback, - controller: controller, - progress: progress, - follow: follow, - strengthListenable: strengthListenable, - speedListenable: speedListenable, - onActivate: onActivate, - onDeactivate: onDeactivate, - ); - - /// Contained breathing glow (React `pulse-inner`) — working states, - /// subscribe buttons. - const BorderBeam.pulseInside({ - Key? key, - required Widget child, - BeamColors? colors, - bool? active, - double? borderRadius, - BeamStyle? style, - BeamShape? shape, - BeamTiming? timing, - BeamPlayback? playback, - BorderBeamController? controller, - double? progress, - Offset? follow, - ValueListenable? strengthListenable, - ValueListenable? speedListenable, - VoidCallback? onActivate, - VoidCallback? onDeactivate, - }) : this( - key: key, - variant: BeamVariant.pulseInside, - child: child, - colors: colors, - active: active, - borderRadius: borderRadius, - style: style, - shape: shape, - timing: timing, - playback: playback, - controller: controller, - progress: progress, - follow: follow, - strengthListenable: strengthListenable, - speedListenable: speedListenable, - onActivate: onActivate, - onDeactivate: onDeactivate, - ); - - /// Outward-blooming breathing halo (React `pulse-outside`). - /// - /// The glow paints behind and outside the child — see the class docs for - /// the opaque-child / border / overflow-room requirements. `BeamStyle`'s - /// `coreBlur`, `bloomBlur`, `glowBrightness`, and `glowSaturation` port the - /// source's consumer tuning hooks for this variant. - const BorderBeam.pulseOutside({ - Key? key, - required Widget child, - BeamColors? colors, - bool? active, - double? borderRadius, - BeamStyle? style, - BeamShape? shape, - BeamTiming? timing, - BeamPlayback? playback, - BorderBeamController? controller, - double? progress, - Offset? follow, - ValueListenable? strengthListenable, - ValueListenable? speedListenable, - VoidCallback? onActivate, - VoidCallback? onDeactivate, - }) : this( - key: key, - variant: BeamVariant.pulseOutside, - child: child, - colors: colors, - active: active, - borderRadius: borderRadius, - style: style, - shape: shape, - timing: timing, - playback: playback, - controller: controller, - progress: progress, - follow: follow, - strengthListenable: strengthListenable, - speedListenable: speedListenable, - onActivate: onActivate, - onDeactivate: onDeactivate, - ); - - /// Which effect this beam paints. - final BeamVariant variant; + /// What the light does. Null inherits the [BorderBeamTheme]'s effect, and + /// then [BeamEffect.rotate]. + final BeamEffect? effect; /// The wrapped content. Laid out and hit-tested normally. final Widget child; @@ -372,34 +174,35 @@ class BorderBeam extends StatefulWidget { /// here wins over it. Match your child's decoration radius. final double? borderRadius; - /// Colors, theme adaptation, and every filter/opacity tuning hook. + /// Colours, surface brightness, strength, glow, and hue drift. final BeamStyle? style; - /// Corner radii, ring width, and corner family. + /// Corner radii, corner family, stroke width, segment, and dashes. final BeamShape? shape; - /// Cycle length, rest between sweeps, playback rate, and hue periods. + /// Cycle length, rest between sweeps, playback rate, direction, and the + /// hue drift period. final BeamTiming? timing; /// Play state and scheduling. Ignored while a [controller] is attached. final BeamPlayback? playback; /// Optional playback controller. When set it owns playback exclusively — - /// `playback.startAfter`/`duration` must be null and [active] is ignored. + /// `playback.startAfter`/`duration` must be null, and [active] and + /// `playback.autoPlay` are ignored. Not allowed below a [BeamSync]. final BorderBeamController? controller; /// Drives the beam's travel from a value instead of the clock, 0–1. /// /// The sweep sits where this says rather than running with time, which - /// turns the traveling variants into readouts: [BorderBeam.rotate] becomes - /// a glowing progress ring, [BorderBeam.line] a progress bar. The clock - /// keeps running underneath — the fade envelope, the hue shift, and the - /// line variant's breathe and spike tracks are all still alive, so the - /// beam looks lit rather than frozen. + /// turns the travelling effects into readouts: [BeamEffect.rotate] becomes + /// a glowing progress ring, [BeamEffect.line] a progress bar. The clock + /// keeps running underneath — the fade, the hue drift, and the line's + /// spikes are all still alive, so the beam looks lit rather than frozen. /// /// Changing it repaints without re-resolving the beam's configuration, so /// it is cheap to drive from an animation. Null hands the travel back to - /// the clock; the pulse variants have no travel to drive. + /// the clock; the ambient effects have no travel to drive. final double? progress; /// Pulls the traveling beam toward a point in the child's box, given in @@ -420,24 +223,25 @@ class BorderBeam extends StatefulWidget { /// _follow = Offset(local.dx / box.size.width, local.dy / box.size.height); /// }), /// onExit: (_) => setState(() => _follow = null), - /// child: BorderBeam.rotate(follow: _follow, child: card), + /// child: BorderBeam(follow: _follow, child: card), /// ) /// ``` /// - /// [progress] wins over it, and the pulse variants ignore both. + /// [progress] wins over it, and the ambient effects ignore both. final Offset? follow; - /// Scales every layer's opacity each frame, without rebuilding. + /// Scales the beam's opacity each frame, without rebuilding. /// /// The live twin of `BeamStyle.strength`: point it at a mic level, a /// download rate, or any other signal and the beam breathes with it. Values - /// above 1 brighten up to the clamp every layer opacity already carries. + /// above 1 brighten, saturating at full opacity. final ValueListenable? strengthListenable; /// Drives the playback rate each frame, without rebuilding. /// /// The live twin of `BeamTiming.speed`, and it wins over both that and a - /// [controller]'s rate while it is set. Values must stay positive. + /// [controller]'s rate while it is set. Values must stay positive. Ignored + /// below a [BeamSync], whose own `speed` sets the group's rate. final ValueListenable? speedListenable; /// Called when the fade-in completes. @@ -461,6 +265,15 @@ class BorderBeam extends StatefulWidget { ? playback : (playback ?? const BeamPlayback()).copyWith(active: active); + /// Loads the beam shader ahead of the first beam. + /// + /// Optional: a beam loads it on demand and its fade-in hides the few + /// milliseconds that takes. Await this in `main` (after + /// `WidgetsFlutterBinding.ensureInitialized()`) to have the very first + /// frame of every beam ready — and in tests, before pumping a beam whose + /// pixels you check. + static Future precache() => BeamProgram.load(); + @override State createState() => _BorderBeamState(); @@ -468,7 +281,9 @@ class BorderBeam extends StatefulWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties - ..add(EnumProperty('variant', variant)) + ..add( + DiagnosticsProperty('effect', effect, defaultValue: null), + ) ..add(DiagnosticsProperty('style', _styleInput)) ..add(DiagnosticsProperty('shape', _shapeInput)) ..add(DiagnosticsProperty('timing', timing)) @@ -499,10 +314,11 @@ class BorderBeam extends StatefulWidget { } } -// The cycle length a resolved timing implies for a variant. -double _cycleSecondsOf(BeamTiming timing, BeamVariant variant) => - (timing.cycle ?? variant.defaultCycleDuration).inMicroseconds / - Duration.microsecondsPerSecond; +// The rest between sweeps a resolved timing implies for an effect. +double _gapSecondsOf(BeamTiming timing, BeamEffect effect) => effect.travels + ? (timing.cycleGap ?? effect.defaultCycleGap).inMicroseconds / + Duration.microsecondsPerSecond + : 0; // The timing fields the painted config is built from — everything except // `speed`, which is applied to the clock and never reaches BeamConfig. @@ -513,19 +329,17 @@ BeamTiming _configTiming(BeamTiming timing) => BeamTiming( cycleGap: timing.cycleGap, direction: timing.direction, phaseOffset: timing.phaseOffset, - beamCount: timing.beamCount, huePeriod: timing.huePeriod, - bloomHuePeriod: timing.bloomHuePeriod, - breatheFactor: timing.breatheFactor, - spikeFactor: timing.spikeFactor, - spike2Factor: timing.spike2Factor, ); -// BeamReducedMotion.slow runs the clock at a quarter rate. -const double _slowMotionFactor = 0.25; +// The assertion a BorderBeamController meets under a BeamSync. +const String _controllerUnderSyncMessage = + 'A BorderBeam under a BeamSync runs on the group clock, so it cannot ' + 'also take a BorderBeamController — a controller owns a clock of its ' + 'own. Drive the group through BeamSync, or move the beam out of it.'; // How far outside the viewport a beam keeps running before its clock is -// paused, matching the root margin the source's IntersectionObserver uses. +// paused: far enough that a beam scrolling into view is already running. const double _offscreenMarginPx = 256; // How long the follow easing takes to cover most of the distance to the @@ -554,8 +368,8 @@ const double _followResponseSeconds = 0.15; ); } -// TickerProviderStateMixin (not Single-): a variant change rebuilds the -// clock, creating a second ticker over this State's lifetime. +// TickerProviderStateMixin (not Single-): leaving a BeamSync creates a fresh +// clock, and with it a second ticker over this State's lifetime. class _BorderBeamState extends State with TickerProviderStateMixin { // Exactly one of these is set: a beam owns a clock unless a BeamSync hands // it the group's. @@ -589,7 +403,11 @@ class _BorderBeamState extends State with TickerProviderStateMixin { /// Whether this beam runs on a [BeamSync] group clock. bool get _synced => _sharedClock != null; - BeamVariantStrategy get _strategy => strategyFor(widget.variant); + // The effect in force: the widget's, else the theme's, else rotate. + BeamEffect _effect = const BeamEffect.rotate(); + + // Paints frames with the shared shader; owns this beam's FragmentShader. + final BeamRenderer _renderer = BeamRenderer(); bool get _active => _playback.active ?? true; bool get _autoPlay => _playback.autoPlay ?? true; @@ -598,12 +416,19 @@ class _BorderBeamState extends State with TickerProviderStateMixin { // is never started at all. bool get _frozen => _playback.debugFrozenAt != null; + // Whether the pinned frame holds the clock still. Only on a beam that owns + // its playback: a controller's clock runs on the controller's say alone. + bool get _frozenHoldsClock => _frozen && widget.controller == null; + bool _autoPlayScheduled = false; bool _hasStarted = false; BeamReducedMotion? _reducedApplied; // Set only when reduced motion paused the clock, so turning reduced motion // back off never overrides a pause the controller asked for. bool _pausedForReducedMotion = false; + // The same for `debugFrozenAt`: set when pinning the frame stopped a + // running clock, so unpinning resumes only what pinning paused. + bool _pausedForFrozen = false; // The same idea for the offscreen pause: set only when this beam stopped // the clock because nobody could see it, so resuming never overrides a // pause a controller or reduced motion asked for. @@ -618,18 +443,22 @@ class _BorderBeamState extends State with TickerProviderStateMixin { @override void initState() { super.initState(); + BeamProgram.load(); _createOwnClock(); // The theme is not reachable yet; the widget's own values carry the beam // until didChangeDependencies resolves them properly, before first build. + _effect = widget.effect ?? const BeamEffect.rotate(); _timing = widget.timing ?? const BeamTiming(); _playback = widget._playbackInput ?? const BeamPlayback(); validateBeamTiming(_timing); validateRepeat(_playback.repeat); - _cycleSeconds = _cycleSecondsOf(_timing, widget.variant); + _cycleSeconds = BeamConfig.cycleSecondsFor(_timing, _effect); + widget.controller + ?..attach(_clock) + ..addListener(_onControllerCommand); + widget.speedListenable?.addListener(_applySpeed); _applySpeed(); _applyFadeCurve(); - widget.controller?.attach(_clock); - widget.speedListenable?.addListener(_applySpeed); } // Resolves the scheduling inputs against the enclosing BorderBeamTheme; @@ -648,18 +477,18 @@ class _BorderBeamState extends State with TickerProviderStateMixin { final timing = (data.timing ?? const BeamTiming()).merge(widget.timing); validateBeamTiming(timing); validateRepeat(playback.repeat); + final previousEffect = _effect; final previousCycle = _cycleSeconds; - final previousGap = - (_timing.cycleGap ?? Duration.zero).inMicroseconds / - Duration.microsecondsPerSecond; + final previousGap = _gapSecondsOf(_timing, _effect); final previousPhase = _timing.phaseOffset ?? 0; + _effect = widget.effect ?? data.effect ?? const BeamEffect.rotate(); _playback = playback; _timing = timing; - _cycleSeconds = _cycleSecondsOf(timing, widget.variant); - final nextGap = - (timing.cycleGap ?? Duration.zero).inMicroseconds / - Duration.microsecondsPerSecond; - if (retime) { + _cycleSeconds = BeamConfig.cycleSecondsFor(timing, _effect); + final nextGap = _gapSecondsOf(timing, _effect); + // A different effect is a different animation: there is no phase of the + // old one to hold. + if (retime && _effect == previousEffect) { _retimeToNewCycle( previousCycle, _cycleSeconds, @@ -694,11 +523,41 @@ class _BorderBeamState extends State with TickerProviderStateMixin { _timing.speed ?? 1; final factor = _reducedApplied == BeamReducedMotion.slow - ? _slowMotionFactor + ? slowMotionFactor : 1.0; _clock.speed = base * factor; } + // A controller command can set the clock running, but reduced motion still + // decides whether it moves. Under staticFrame or hide the clock is held at + // full opacity instead (the still frame, or nothing), as a beam that owns + // its playback would be, and leaving reduced motion lets it run on from + // there. A fade-out is left to run down, so stop() still ends the beam. + void _onControllerCommand() { + _applySpeed(); + if (_synced || !_motionFrozen) return; + if (_clock.isRunning && _clock.stage != BeamFadeStage.fadingOut) { + _clock.showStatic(); + _pausedForReducedMotion = true; + } + _rebuildStillFrame(); + } + + // Under staticFrame a controller beam shows its still frame while its clock + // is visible, which build reads. Commands and fades change that without a + // rebuild of their own. + void _rebuildStillFrame() { + if (!mounted || _reducedApplied != BeamReducedMotion.staticFrame) return; + if (SchedulerBinding.instance.schedulerPhase == + SchedulerPhase.persistentCallbacks) { + SchedulerBinding.instance.addPostFrameCallback((_) { + if (mounted) setState(() {}); + }); + return; + } + setState(() {}); + } + void _scheduleAutoplayStart() { _startTimer?.cancel(); _startTimer = null; @@ -749,6 +608,7 @@ class _BorderBeamState extends State with TickerProviderStateMixin { final wasActive = previous.active ?? true; final wasAutoPlay = previous.autoPlay ?? true; final activeChanged = wasActive != _active; + _applyFrozenChange(wasFrozen: previous.debugFrozenAt != null); if (_synced || widget.controller != null) { _startTimer?.cancel(); @@ -791,6 +651,45 @@ class _BorderBeamState extends State with TickerProviderStateMixin { } } + // `debugFrozenAt` pins the painted frame, so a clock left running under it + // would spend every frame on pixels nobody sees. Unpinning hands the beam + // back to its schedule: what pinning paused resumes, and a beam that never + // got to start starts now. + // + // A controller's clock is the controller's alone: pinning changes what is + // painted, never whether that clock runs, so it neither pauses a running + // one nor resumes one the controller paused. + void _applyFrozenChange({required bool wasFrozen}) { + if (wasFrozen == _frozen || _synced) return; + if (widget.controller != null) { + // A pause pinning put on before the controller took over is the + // controller's to lift now. + _pausedForFrozen = false; + return; + } + if (_frozen) { + _startTimer?.cancel(); + _startTimer = null; + if (_clock.isRunning) { + _clock.pause(); + _pausedForFrozen = true; + } + return; + } + if (_pausedForFrozen) { + _pausedForFrozen = false; + if (_motionFrozen) { + // Reduced motion arrived while the frame was pinned; it owns the + // pause now. + _pausedForReducedMotion = true; + } else if (!_pausedForOffscreen) { + _clock.resume(); + } + return; + } + if (widget.controller == null && !_hasStarted) _scheduleAutoplayStart(); + } + @override void didChangeDependencies() { super.didChangeDependencies(); @@ -799,7 +698,7 @@ class _BorderBeamState extends State with TickerProviderStateMixin { // is delivered, as is the enclosing BeamSync. final first = !_autoPlayScheduled; final previousPlayback = _playback; - _adoptSharedClock(BeamSync.clockOf(context)); + _adoptSharedClock(BeamSyncScope.clockOf(context)); _resolveScheduling(retime: !first); if (first) { _autoPlayScheduled = true; @@ -817,12 +716,17 @@ class _BorderBeamState extends State with TickerProviderStateMixin { if (shared == _sharedClock) return; assert( shared == null || widget.controller == null, - 'A BorderBeam under a BeamSync runs on the group clock, so it cannot ' - 'also take a BorderBeamController — a controller owns a clock of its ' - 'own. Drive the group through BeamSync, or move the beam out of it.', + _controllerUnderSyncMessage, ); _detachTickListener(); _detachResetListener(); + // A controller only ever drives this beam's own clock. + widget.controller?.detach(_clock); + // Pauses this beam put on the clock it is leaving mean nothing on the + // next one. + _pausedForReducedMotion = false; + _pausedForOffscreen = false; + _pausedForFrozen = false; if (shared != null) { _startTimer?.cancel(); _startTimer = null; @@ -834,6 +738,7 @@ class _BorderBeamState extends State with TickerProviderStateMixin { } else { _sharedClock = null; _createOwnClock(); + widget.controller?.attach(_clock); _applySpeed(); _applyFadeCurve(); if (widget.controller == null && _autoPlay && _active) _start(); @@ -852,6 +757,11 @@ class _BorderBeamState extends State with TickerProviderStateMixin { if (_pausedForReducedMotion) { _pausedForReducedMotion = false; if (_clock.isVisible) { + if (_frozenHoldsClock) { + // The pinned frame holds the clock now; unpinning resumes it. + _pausedForFrozen = true; + return; + } _clock.resume(); // Motion is allowed again, but visibility may not be — re-check // rather than leaving an offscreen beam ticking. @@ -873,7 +783,6 @@ class _BorderBeamState extends State with TickerProviderStateMixin { void _createOwnClock() { _ownClock = BeamClock( createTicker: createTicker, - maxFps: _strategy.preferredFps, onFadeComplete: _onFadeComplete, ); // A replacement clock starts its own timeline at zero, so it takes the @@ -927,12 +836,14 @@ class _BorderBeamState extends State with TickerProviderStateMixin { _resolver?.breatheTimeOffset = seconds; } - // A cycle-duration change mid-run must not snap the beam. Rescaling - // elapsed time by the cycle ratio holds every cycle-derived track at its - // current fraction; shifting the hue clock back by the same amount holds - // the fixed-period hue tracks, which do not scale with the cycle. A - // cycle-gap change needs none of this: the sweep keeps its position and the - // rest simply appears at the next cycle end. + // A cycle or cycle-gap change mid-run must not snap the beam. Moving the + // clock to where the new timing puts the sweep's current position holds + // the sweep (for a gap change alone that is a re-cut of the elapsed time + // into the new periods); shifting the hue clock back by the same amount + // holds the fixed-period hue tracks, which do not scale with the cycle. + // + // A group clock is shared, so retiming it would move every member: a + // synced beam shifts its own tracks onto the new timing instead. void _retimeToNewCycle( double oldCycle, double newCycle, { @@ -941,11 +852,8 @@ class _BorderBeamState extends State with TickerProviderStateMixin { required double oldPhase, required double newPhase, }) { - if (!_clock.isVisible || oldCycle <= 0 || oldCycle == newCycle) return; - if (widget.variant.isPulse) { - oldGap = 0; - newGap = 0; - } + if (!_clock.isVisible || oldCycle <= 0) return; + if (oldCycle == newCycle && oldGap == newGap) return; final before = _clock.elapsedSeconds; final oldPeriod = oldCycle + oldGap; final newPeriod = newCycle + newGap; @@ -966,6 +874,13 @@ class _BorderBeamState extends State with TickerProviderStateMixin { // reports. var target = completed * newPeriod + newLocal - newPhase * newCycle - travel; + if (_synced) { + _setTravelTimeOffset(travel + target - before); + _setBreatheTimeOffset( + (before + _breatheTimeOffset) * newCycle / oldCycle - before, + ); + return; + } // A follow hand-back leaves a negative travel offset behind, so backing // it out can put the target at or below zero even though the phase it // names is perfectly valid. Every track the target feeds is periodic, so @@ -980,8 +895,8 @@ class _BorderBeamState extends State with TickerProviderStateMixin { final after = _clock.elapsedSeconds; // The fixed-period hue tracks keep the timeline they had. _setHueTimeOffset(_hueTimeOffset + before - after); - // The line variant's breathe and spike tracks scale with the cycle, so - // what holds their phase is the pure ratio rescale — not the target + // The ambient track (BeamFramePhases.cycles) scales with the cycle, so + // what holds its phase is the pure ratio rescale — not the target // above, which is bent by the gap, the phase offset, the hand-back, and // any whole-period lift. Put them back on the rescaled timeline. _setBreatheTimeOffset( @@ -1016,6 +931,7 @@ class _BorderBeamState extends State with TickerProviderStateMixin { } void _onFadeComplete(bool active) { + if (widget.controller != null && !_synced) _rebuildStillFrame(); if (active) { widget.onActivate?.call(); } else { @@ -1028,7 +944,7 @@ class _BorderBeamState extends State with TickerProviderStateMixin { BeamReducedMotion? get _reduced { if (!(MediaQuery.maybeDisableAnimationsOf(context) ?? false)) return null; final mode = - BeamSync.reducedMotionOf(context) ?? + BeamSyncScope.reducedMotionOf(context) ?? _playback.reducedMotion ?? BeamReducedMotion.staticFrame; return mode == BeamReducedMotion.animate ? null : mode; @@ -1091,27 +1007,51 @@ class _BorderBeamState extends State with TickerProviderStateMixin { if (resolver.finishedAt(clock.elapsedSeconds)) clock.deactivate(); } + // `progress` as the sweep reads it: clamped to 0–1, and NaN treated as + // unset rather than handed to the shader. + double? get _progressInput { + final progress = widget.progress; + if (progress == null || progress.isNaN) return null; + return progress.clamp(0.0, 1.0); + } + // The perimeter position the pointer is asking for, as sweep progress. double? _followTarget() { final follow = widget.follow; final config = _config; - if (follow == null || config == null) return null; - switch (widget.variant) { - case BeamVariant.rotate || BeamVariant.small: - // Progress 0 sits at 12 o'clock and runs clockwise, so the angle to - // the point is measured from straight up. - final angle = - math.atan2(follow.dy - 0.5, follow.dx - 0.5) + math.pi / 2; - return (angle / (2 * math.pi)) % 1.0; - case BeamVariant.line: - // The beam travels one edge, so only the coordinate along it counts. - final along = switch (config.edge) { + if (follow == null || !follow.isFinite || config == null) return null; + final box = context.findRenderObject(); + if (box is! RenderBox || !box.hasSize || box.size.isEmpty) return null; + final size = box.size; + final point = Offset(follow.dx * size.width, follow.dy * size.height); + switch (config.effect) { + case RotateEffect(): + final rect = (Offset.zero & size).inflate(config.ringOffset); + final outline = BeamOutline( + rect, + config.borderRadius, + superellipse: config.superellipse, + ); + final segment = config.segment?.resolve(outline); + if (segment == null) { + // A rotating beam sweeps around the centre: its travel is the + // pointer's angle. + return conicFraction(point, rect.center); + } + final u = outline.nearestFraction(point); + final span = BeamOutline.wrapFraction(segment.to - segment.from); + if (span <= 0) return u; + final along = BeamOutline.wrapFraction(u - segment.from); + return (along / span).clamp(0.0, 1.0); + case LineEffect(:final edge): + // The streak rides one edge in reading order, so only the coordinate + // along it counts. + return switch (edge) { BeamEdge.top || BeamEdge.bottom => follow.dx, BeamEdge.left || BeamEdge.right => follow.dy, - }; - return along.clamp(0.0, 1.0); - case BeamVariant.pulseInside || BeamVariant.pulseOutside: - // Breathing has no travel to steer. + }.clamp(0.0, 1.0); + case PulseEffect(): + // Ambient light has no travel to steer. return null; } } @@ -1121,9 +1061,12 @@ class _BorderBeamState extends State with TickerProviderStateMixin { final resolver = _resolver; if (target == null || resolver == null) return; final from = _followValue ?? _timedProgress(resolver); - // Shortest way round the contour: the beam never takes the long way to a - // point just behind it. - final delta = ((target - from) + 0.5) % 1.0 - 0.5; + // A full-ring rotate loops, so it takes the shortest way round and never + // the long way to a point just behind it. Every other sweep runs from one + // end to the other and must not wrap through its ends. + final config = _config; + final loops = config?.effect is RotateEffect && config?.segment == null; + final delta = loops ? ((target - from) + 0.5) % 1.0 - 0.5 : target - from; final step = _smoothDamp( current: from, target: from + delta, @@ -1132,8 +1075,8 @@ class _BorderBeamState extends State with TickerProviderStateMixin { response: _followResponseSeconds, ); _followVelocity = step.velocity; - _followValue = step.value % 1.0; - if (widget.progress == null) _driven.value = _followValue; + _followValue = loops ? step.value % 1.0 : step.value.clamp(0.0, 1.0); + if (_progressInput == null) _driven.value = _followValue; } double _timedProgress(BeamPhaseResolver resolver) => @@ -1146,15 +1089,12 @@ class _BorderBeamState extends State with TickerProviderStateMixin { final held = _followValue; _followValue = null; _followVelocity = 0; - _driven.value = widget.progress; + _driven.value = _progressInput; final resolver = _resolver; - if (held == null || resolver == null || _cycleSeconds <= 0) return; - final phases = resolver.sample(_clock.elapsedSeconds, 1); - var delta = held - phases.travelProgress; - // Travel time always runs forward; a mirrored cycle spends it backwards. - if (phases.reversedNow) delta = -delta; - delta = ((delta + 0.5) % 1.0) - 0.5; - _setTravelTimeOffset(_travelTimeOffset + delta * _cycleSeconds); + if (held == null || resolver == null) return; + _setTravelTimeOffset( + resolver.travelOffsetHolding(_clock.elapsedSeconds, held), + ); } // ─── Offscreen pause ──────────────────────────────────────────────────── @@ -1232,8 +1172,13 @@ class _BorderBeamState extends State with TickerProviderStateMixin { _pausedForOffscreen = false; // Reduced motion outranks visibility: a beam that must not move stays // still whether or not it is on screen. - if (_motionFrozen || _pausedForReducedMotion) return; - if (_clock.isVisible) _clock.resume(); + if (_motionFrozen || _pausedForReducedMotion || !_clock.isVisible) return; + if (_frozenHoldsClock) { + // The pinned frame holds the clock now; unpinning resumes it. + _pausedForFrozen = true; + return; + } + _clock.resume(); } // ─── Lifecycle ────────────────────────────────────────────────────────── @@ -1244,29 +1189,21 @@ class _BorderBeamState extends State with TickerProviderStateMixin { final previousPlayback = _playback; final controllerChanged = oldWidget.controller != widget.controller; if (controllerChanged) { - oldWidget.controller?.detach(_clock); - widget.controller?.attach(_clock); + assert( + !_synced || widget.controller == null, + _controllerUnderSyncMessage, + ); + oldWidget.controller + ?..removeListener(_onControllerCommand) + ..detach(_clock); + if (!_synced) widget.controller?.attach(_clock); + widget.controller?.addListener(_onControllerCommand); } if (oldWidget.speedListenable != widget.speedListenable) { oldWidget.speedListenable?.removeListener(_applySpeed); widget.speedListenable?.addListener(_applySpeed); } - final variantChanged = oldWidget.variant != widget.variant; - _resolveScheduling(retime: !variantChanged); - if (variantChanged && !_synced) { - // The fps cap is variant-bound; rebuild the clock. - final wasVisible = _clock.isVisible; - widget.controller?.detach(_clock); - _detachTickListener(); - _detachResetListener(); - _ownClock!.dispose(); - _createOwnClock(); - _applySpeed(); - _applyFadeCurve(); - widget.controller?.attach(_clock); - _syncTickListener(); - if (wasVisible && widget.controller == null && _active) _start(); - } + _resolveScheduling(retime: true); _applyReducedMotionChange(); _applySchedulingTransition( previousPlayback, @@ -1280,10 +1217,27 @@ class _BorderBeamState extends State with TickerProviderStateMixin { } } + // A beam leaving the tree lets go of its controller now rather than at the + // end of the frame, so a beam mounted in its place within the same frame + // can take the controller over. + @override + void deactivate() { + widget.controller?.detach(_clock); + super.deactivate(); + } + + // Moved under a GlobalKey: the controller comes back with the beam. + @override + void activate() { + super.activate(); + if (!_synced) widget.controller?.attach(_clock); + } + @override void dispose() { _startTimer?.cancel(); _durationStartedAt = null; + widget.controller?.removeListener(_onControllerCommand); widget.speedListenable?.removeListener(_applySpeed); _scrollPosition?.removeListener(_onScrollChanged); _scrollPosition = null; @@ -1293,6 +1247,7 @@ class _BorderBeamState extends State with TickerProviderStateMixin { widget.controller?.detach(_clock); _ownClock?.dispose(); _driven.dispose(); + _renderer.dispose(); super.dispose(); } @@ -1304,18 +1259,11 @@ class _BorderBeamState extends State with TickerProviderStateMixin { ) { final brightness = (style.theme ?? BeamTheme.auto).resolve(ambient); final timing = _configTiming(_timing); - final key = ( - widget.variant, - style, - shape, - timing, - brightness, - textDirection, - ); + final key = (_effect, style, shape, timing, brightness, textDirection); if (_config == null || key != _configKey) { _configKey = key; _config = BeamConfig.resolve( - variant: widget.variant, + effect: _effect, palette: (style.colors ?? BeamColors.colorful).resolve(), brightness: brightness, style: style, @@ -1323,7 +1271,7 @@ class _BorderBeamState extends State with TickerProviderStateMixin { timing: timing, textDirection: textDirection, ); - // A config change rebuilds the resolver, and both time offsets are + // A config change rebuilds the resolver, and the time offsets are // timeline state the beam has already committed to: dropping them would // snap the hue back and throw away a follow hand-back. _resolver = BeamPhaseResolver(_config!) @@ -1346,7 +1294,6 @@ class _BorderBeamState extends State with TickerProviderStateMixin { Theme.of(context).brightness, Directionality.maybeOf(context) ?? TextDirection.ltr, ); - final strategy = _strategy; final playing = (widget.controller != null || _synced) ? _clock.isVisible : _active && _autoPlay; @@ -1357,32 +1304,20 @@ class _BorderBeamState extends State with TickerProviderStateMixin { // An explicit progress owns the sweep; a follow gesture only steers what // the clock would otherwise drive. - _driven.value = widget.progress?.clamp(0.0, 1.0) ?? _followValue; + _driven.value = _progressInput ?? _followValue; return RepaintBoundary( child: CustomPaint( - painter: !hidden && widget.variant == BeamVariant.pulseOutside - ? BeamPainter( - clock: _clock, - config: config, - resolver: _resolver!, - strategy: strategy, - behind: true, - staticMode: staticMode, - progress: _driven, - strength: widget.strengthListenable, - frozenAt: _playback.debugFrozenAt, - ) - : null, foregroundPainter: hidden ? null : BeamPainter( + renderer: _renderer, clock: _clock, config: config, resolver: _resolver!, - strategy: strategy, - behind: false, staticMode: staticMode, + devicePixelRatio: + MediaQuery.maybeDevicePixelRatioOf(context) ?? 1, progress: _driven, strength: widget.strengthListenable, frozenAt: _playback.debugFrozenAt, diff --git a/lib/src/border_beam_controller.dart b/lib/src/border_beam_controller.dart index 095387a..302a411 100644 --- a/lib/src/border_beam_controller.dart +++ b/lib/src/border_beam_controller.dart @@ -1,17 +1,22 @@ +/// @docImport 'border_beam.dart'; +library; + import 'package:flutter/foundation.dart'; import 'animation/beam_clock.dart'; +import 'models/model_validation.dart'; /// Programmatic playback control for a [BorderBeam]. /// /// When a controller is attached the widget gives up scheduling entirely: -/// `startAfter`, `duration`, and `autoPlay` must not be set, the beam starts -/// hidden, and playback is driven exclusively through this API: +/// `startAfter` and `duration` must not be set, `active` and `autoPlay` are +/// ignored, the beam starts hidden, and playback is driven exclusively +/// through this API: /// /// ```dart /// final controller = BorderBeamController(); /// -/// BorderBeam.rotate(controller: controller, child: card); +/// BorderBeam(controller: controller, child: card); /// /// controller.start(); // fade in, begin animating /// controller.pause(); // freeze the current frame @@ -19,6 +24,15 @@ import 'animation/beam_clock.dart'; /// controller.speed = 2.0; // double-time /// controller.stop(); // fade out, halt /// ``` +/// +/// One controller drives one beam at a time, and a beam below a `BeamSync` +/// cannot take one — the group owns its playback. +/// +/// The controller notifies its listeners when one of its own methods is +/// called, not when the beam changes state by itself (a fade-out finishing, +/// a `BeamPlayback.repeat` budget running out): read [isActive] and +/// [isRunning] when you need them, or use `BorderBeam.onActivate` and +/// `BorderBeam.onDeactivate`. class BorderBeamController extends ChangeNotifier { BeamClock? _clock; double _speed = 1; @@ -33,18 +47,37 @@ class BorderBeamController extends ChangeNotifier { /// stopped). bool get isRunning => _clock?.isRunning ?? false; - /// Playback rate multiplier (1.0 = normal). Must be positive. + /// Playback rate multiplier (1.0 = normal). Must be finite and positive. + /// + /// Replaces `BeamTiming.speed` while attached. A + /// `BorderBeam.speedListenable` still wins over it, and reduced motion's + /// `BeamReducedMotion.slow` still quarters it. double get speed => _speed; set speed(double value) { - assert(value > 0, 'speed must be positive'); + // Checked in release builds too: the rate multiplies the timeline every + // frame, so a NaN or infinity would reach every phase and the shader. + validateSpeed(value, 'BorderBeamController.speed'); + if (value == _speed) return; _speed = value; - _clock?.speed = value; + // The attached beam listens and works out the rate in force from this. notifyListeners(); } - /// Starts the beam: resets the timeline and fades in. + /// Starts the beam: restarts its timeline from zero and fades it in. + /// + /// Called mid-fade-out, it reverses the fade from the opacity reached + /// instead, keeping the timeline. On a paused beam that is still showing it + /// carries on from the held frame, as [resume] does; on a beam that is + /// already running it does nothing. void start() { - _clock?.activate(); + final clock = _clock; + if (clock != null) { + if (clock.isVisible && clock.stage != BeamFadeStage.fadingOut) { + clock.resume(); + } else { + clock.activate(); + } + } notifyListeners(); } @@ -85,24 +118,36 @@ class BorderBeamController extends ChangeNotifier { notifyListeners(); } - /// Jumps the animation timeline to [position]. + /// Jumps the animation timeline to [position]; a fade in progress carries + /// on as it was. + /// + /// The position lasts only while the beam is showing: [start] begins the + /// timeline at zero. void seek(Duration position) { _clock?.seek(position.inMicroseconds / Duration.microsecondsPerSecond); + notifyListeners(); } +} - /// Called by [BorderBeam] when it starts using this controller. Internal — - /// do not call from application code. +/// Binds a [BorderBeamController] to the clock of the beam it drives. +/// +/// Package-internal: the library exports only [BorderBeamController], so +/// application code never sees these. [BorderBeam] is the only caller. +extension BorderBeamControllerBinding on BorderBeamController { + /// Called by [BorderBeam] when it starts using this controller. + /// + /// The beam applies [speed] to [clock] itself, so it can fold in its own + /// `speedListenable` and reduced-motion rate. void attach(BeamClock clock) { assert( _clock == null || _clock == clock, - 'BorderBeamController is already attached to another BorderBeam', + 'BorderBeamController is already attached to another BorderBeam. A ' + 'controller drives one beam at a time.', ); _clock = clock; - clock.speed = _speed; } - /// Called by [BorderBeam] when it stops using this controller. Internal — - /// do not call from application code. + /// Called by [BorderBeam] when it stops using this controller. void detach(BeamClock clock) { if (_clock == clock) _clock = null; } diff --git a/lib/src/border_beam_theme.dart b/lib/src/border_beam_theme.dart index b601b42..5ba8753 100644 --- a/lib/src/border_beam_theme.dart +++ b/lib/src/border_beam_theme.dart @@ -1,6 +1,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; +import 'effects/beam_effect.dart'; import 'models/beam_playback.dart'; import 'models/beam_shape.dart'; import 'models/beam_style.dart'; @@ -15,19 +16,23 @@ import 'models/beam_timing.dart'; class BorderBeamThemeData { /// Creates theme defaults. Every omitted slot inherits. const BorderBeamThemeData({ + this.effect, this.style, this.shape, this.timing, this.playback, }); - /// Default colors, theme adaptation, and filter hooks. + /// Default effect, used by every beam below that does not choose one. + final BeamEffect? effect; + + /// Default colors, theme adaptation, glow, and colour drift. final BeamStyle? style; - /// Default corner radii, ring width, and corner family. + /// Default corner radii, stroke width, and corner family. final BeamShape? shape; - /// Default cycle length, rest, rate, and hue periods. + /// Default cycle length, rest, rate, and hue period. final BeamTiming? timing; /// Default play state and scheduling. @@ -36,11 +41,13 @@ class BorderBeamThemeData { /// Returns a copy with the given slots replaced. A null argument keeps the /// current slot. BorderBeamThemeData copyWith({ + BeamEffect? effect, BeamStyle? style, BeamShape? shape, BeamTiming? timing, BeamPlayback? playback, }) => BorderBeamThemeData( + effect: effect ?? this.effect, style: style ?? this.style, shape: shape ?? this.shape, timing: timing ?? this.timing, @@ -48,10 +55,12 @@ class BorderBeamThemeData { ); /// Layers [other] over this data, field by field: a field set in [other] - /// wins, every other field falls through to this data. + /// wins, every other field falls through to this data. An effect is one + /// value, so [other]'s replaces this one whole. BorderBeamThemeData merge(BorderBeamThemeData? other) => other == null ? this : BorderBeamThemeData( + effect: other.effect ?? effect, style: style?.merge(other.style) ?? other.style, shape: shape?.merge(other.shape) ?? other.shape, timing: timing?.merge(other.timing) ?? other.timing, @@ -62,17 +71,18 @@ class BorderBeamThemeData { bool operator ==(Object other) => identical(this, other) || other is BorderBeamThemeData && + other.effect == effect && other.style == style && other.shape == shape && other.timing == timing && other.playback == playback; @override - int get hashCode => Object.hash(style, shape, timing, playback); + int get hashCode => Object.hash(effect, style, shape, timing, playback); @override String toString() => - 'BorderBeamThemeData(style: $style, shape: $shape, ' + 'BorderBeamThemeData(effect: $effect, style: $style, shape: $shape, ' 'timing: $timing, playback: $playback)'; } @@ -81,8 +91,9 @@ class BorderBeamThemeData { /// ```dart /// BorderBeamTheme( /// data: const BorderBeamThemeData( +/// effect: BeamEffect.pulse(), /// style: BeamStyle(colors: BeamColors.ocean), -/// shape: BeamShape.circular(20, superellipse: true), +/// shape: BeamShape.all(20, superellipse: true), /// ), /// child: app, /// ) diff --git a/lib/src/constants/line_keyframes.dart b/lib/src/constants/line_keyframes.dart deleted file mode 100644 index 5030994..0000000 --- a/lib/src/constants/line_keyframes.dart +++ /dev/null @@ -1,80 +0,0 @@ -// Verbatim transcription of the line variant keyframe tables from the React -// library (border-beam v1.3.0, src/styles.ts lines ~2105-2149). Each table is -// a list of (t, value) pairs with t in 0–1; interpolation between stops is -// linear (the CSS animations declaring these run with `linear` or -// `ease-in-out` timing — the easing is applied to the WHOLE cycle progress -// before sampling, matching CSS `animation-timing-function` semantics per -// keyframe segment; see LineKeyframeTrack). - -/// A single keyframe stop. -typedef BeamKeyframe = ({double t, double value}); - -/// `beam-travel` — the traveling beam's x position (fraction of width). -const List lineTravelX = [ - (t: 0.0, value: 0.06), - (t: 0.1, value: 0.15), - (t: 0.2, value: 0.25), - (t: 0.3, value: 0.35), - (t: 0.4, value: 0.44), - (t: 0.5, value: 0.5), - (t: 0.6, value: 0.56), - (t: 0.7, value: 0.65), - (t: 0.8, value: 0.75), - (t: 0.9, value: 0.85), - (t: 1.0, value: 0.94), -]; - -/// `beam-travel` — the beam width factor (peaks mid-travel). -const List lineTravelW = [ - (t: 0.0, value: 0.5), - (t: 0.1, value: 0.8), - (t: 0.2, value: 1.1), - (t: 0.3, value: 1.3), - (t: 0.4, value: 1.45), - (t: 0.5, value: 1.5), - (t: 0.6, value: 1.45), - (t: 0.7, value: 1.3), - (t: 0.8, value: 1.1), - (t: 0.9, value: 0.8), - (t: 1.0, value: 0.5), -]; - -/// `beam-edge-fade` — layer opacity, fading the beam out near travel ends. -const List lineEdgeFade = [ - (t: 0.0, value: 0), - (t: 0.125, value: 0), - (t: 0.325, value: 1), - (t: 0.675, value: 1), - (t: 0.875, value: 0), - (t: 1.0, value: 0), -]; - -/// `beam-breathe` — the beam height factor (cycle = duration × 1.3, -/// ease-in-out per segment). -const List lineBreatheH = [ - (t: 0.0, value: 0.8), - (t: 0.25, value: 1.25), - (t: 0.55, value: 0.85), - (t: 0.8, value: 1.3), - (t: 1.0, value: 0.8), -]; - -/// `beam-spike` — first spike scale oscillation (cycle = duration × 1.33, -/// ease-in-out per segment). -const List lineSpike = [ - (t: 0.0, value: 0.8), - (t: 0.25, value: 1.3), - (t: 0.5, value: 0.9), - (t: 0.75, value: 1.4), - (t: 1.0, value: 0.8), -]; - -/// `beam-spike2` — second spike scale oscillation (cycle = duration × 1.7, -/// ease-in-out per segment). -const List lineSpike2 = [ - (t: 0.0, value: 1.2), - (t: 0.25, value: 0.7), - (t: 0.5, value: 1.4), - (t: 0.75, value: 0.8), - (t: 1.0, value: 1.2), -]; diff --git a/lib/src/constants/pulse_constants.dart b/lib/src/constants/pulse_constants.dart deleted file mode 100644 index 6a9a1c2..0000000 --- a/lib/src/constants/pulse_constants.dart +++ /dev/null @@ -1,86 +0,0 @@ -// The pulse variants' painting constants. -// -// Two provenances, kept apart below: -// -// * VERBATIM — transcribed from the React library (border-beam v1.3.0, -// `src/styles.ts`): the pulse-outside outward-glow transform, the -// reference element the glow geometry was authored against, and the -// pulse-inside corner accents. -// * FLUTTER-SIDE TUNING — the demo-hero recipe -// (`.beam-host--pulse-outside-tuned` in the source's demo page), which the -// React library layers on top of its own raw defaults. It is baked in here -// because the pulse-outside look everyone knows from -// beam.jakubantalik.com is the tuned one; every value stays overridable -// through the widget's coreBlur/bloomBlur/glowBrightness/glowSaturation/ -// glowBoost/opacity hooks. - -// ─── Verbatim: pulse-outside geometry ─────────────────────────────────────── - -/// Horizontal factor of the source's constant outward-glow transform -/// (`scale(0.95, 0.9)`). -const double pulseOuterScaleX = 0.95; - -/// Vertical factor of the outward-glow transform. -const double pulseOuterScaleY = 0.9; - -/// Reference child width the glow geometry was authored for. -const double pulseOuterReferenceWidth = 350; - -/// Reference child height the glow geometry was authored for. -const double pulseOuterReferenceHeight = 140; - -/// Lower clamp on the glow's size scale. -const double pulseOuterMinScale = 0.35; - -/// Upper clamp on the glow's size scale. -const double pulseOuterMaxScale = 4; - -/// Damping applied to the size-derived halo unit (`--sub-glow-unit`), which -/// scales reach and blur with the element's size relative to the demo's -/// Subscribe button baseline. -const double pulseOuterGlowUnitDamping = 0.7; - -// ─── Verbatim: pulse-inside corner accents ────────────────────────────────── - -/// Radius of the fixed corner-accent ellipses of the pulse-inside inner -/// layer. -const double pulseInnerCornerRadius = 60; - -/// Dark-theme alpha of a corner accent at full breath. -const double pulseInnerCornerAlphaDark = 0.18; - -/// Light-theme alpha of a corner accent at full breath. -const double pulseInnerCornerAlphaLight = 0.08; - -/// The stop the corner accent has faded out by. -const double pulseInnerCornerEndStop = 0.70; - -/// Blur sigma of the pulse-inside frozen bloom layer. -const double pulseInnerBloomBlurSigma = 8; - -// ─── Flutter-side tuning: the pulse-outside demo recipe ───────────────────── - -/// Prominence boost multiplied into the glow blob geometry. -const double pulseOuterTunedBoost = 1.05; - -/// Multiplier on the glow layers' opacity, brightness, and saturation. -const double pulseOuterTunedGlowMultiplier = 1.71; - -/// Unit-scaled inset the core glow is grown past the child's bounds. -const double pulseOuterTunedCoreInset = 6; - -/// Unit-scaled inset the bloom halo is grown past the child's bounds. -const double pulseOuterTunedBloomInset = 14; - -/// Unit-scaled blur of the core glow — the value that melts the separate -/// blobs into one continuous edge-hugging glow. -const double pulseOuterTunedCoreBlur = 10; - -/// Unit-scaled blur of the ambient bloom halo. -const double pulseOuterTunedBloomBlur = 19; - -/// Default glow brightness before the tuning multiplier. -const double pulseOuterGlowBrightness = 1.3; - -/// Default glow saturation before the tuning multiplier. -const double pulseOuterGlowSaturation = 1.2; diff --git a/lib/src/constants/pulse_params.dart b/lib/src/constants/pulse_params.dart deleted file mode 100644 index 308b1a8..0000000 --- a/lib/src/constants/pulse_params.dart +++ /dev/null @@ -1,79 +0,0 @@ -import 'dart:ui'; - -import '../models/beam_variant.dart'; - -// Verbatim port of `pulseParams` from the React library (border-beam v1.3.0, -// src/styles.ts lines ~925-952). Breathing parameters tuned per variant, -// theme, and cycle duration. - -/// Theme/size/duration-tuned breathing parameters shared by the oscillator -/// table and the frozen bloom alpha. -class PulseParams { - const PulseParams._({ - required this.sp, - required this.dr, - required this.op, - required this.gh, - required this.bs, - required this.ss, - required this.ghs, - required this.huePeriod, - }); - - /// Blob size breathing amplitude (fraction). - final double sp; - - /// Drift amplitude in logical px. - final double dr; - - /// Quadrant opacity breathing depth (0 disables opacity breathing). - final double op; - - /// Global height breathing amplitude (fraction). - final double gh; - - /// Base period for drift/opacity oscillators, seconds. - final double bs; - - /// Base period for size oscillators, seconds. - final double ss; - - /// Period of the global height oscillator, seconds. - final double ghs; - - /// Seconds for one full 360° hue revolution. - final double huePeriod; - - /// Computes the tuned parameters for a pulse [variant], [brightness], and - /// cycle duration in [durationSeconds] (React default 2.3). - factory PulseParams.resolve( - BeamVariant variant, - Brightness brightness, - double durationSeconds, - ) { - final isDark = brightness == Brightness.dark; - final durScale = durationSeconds / 2.3; - if (variant == BeamVariant.pulseInside) { - return PulseParams._( - sp: 0.28, - dr: isDark ? 33 : 40, - op: isDark ? 0.48 : 0.45, - gh: isDark ? 0.34 : 0.22, - bs: (isDark ? 1.9 : 2.6) * durScale, - ss: (isDark ? 2.6 : 4.6) * durScale, - ghs: (isDark ? 2.4 : 5.5) * durScale, - huePeriod: 16, - ); - } - return PulseParams._( - sp: isDark ? 0.28 : 0.36, - dr: isDark ? 14 : 19, - op: isDark ? 0.46 : 0, - gh: isDark ? 0.16 : 0.58, - bs: (isDark ? 2.3 : 3.7) * durScale, - ss: (isDark ? 6.4 : 4.6) * durScale, - ghs: (isDark ? 2.4 : 3.8) * durScale, - huePeriod: 14, - ); - } -} diff --git a/lib/src/constants/pulse_tables.dart b/lib/src/constants/pulse_tables.dart deleted file mode 100644 index ebc7fff..0000000 --- a/lib/src/constants/pulse_tables.dart +++ /dev/null @@ -1,233 +0,0 @@ -import 'dart:ui'; - -import '../models/beam_blob.dart'; - -// Verbatim transcription of the pulse gradient tables from the React library -// (border-beam v1.3.0, src/styles.ts lines ~685-744). Do not tweak values. - -/// Region/quad assignment for each of the 9 palette border blobs when used as -/// the pulse perimeter ring (React `PULSE_RING_MAP`). -const List<({PulseRegion region, PulseQuad quad})> pulseRingMap = [ - (region: PulseRegion.r1, quad: PulseQuad.tl), - (region: PulseRegion.r2, quad: PulseQuad.tl), - (region: PulseRegion.r3, quad: PulseQuad.bl), - (region: PulseRegion.r1, quad: PulseQuad.bl), - (region: PulseRegion.r2, quad: PulseQuad.br), - (region: PulseRegion.r3, quad: PulseQuad.br), - (region: PulseRegion.r1, quad: PulseQuad.tr), - (region: PulseRegion.r2, quad: PulseQuad.tr), - (region: PulseRegion.r3, quad: PulseQuad.tr), -]; - -/// Override ellipse sizes for the pulse-inner `::before` layer's 9 blobs -/// (React `PULSE_INNER_SIZES`). -const List pulseInnerSizes = [ - Size(65, 35), - Size(55, 30), - Size(35, 65), - Size(15, 30), - Size(173, 28), - Size(80, 22), - Size(69, 28), - Size(22, 38), - Size(47, 44), -]; - -/// Pulse-inner bloom table (React `PULSE_INNER_BLOOM`): 7 of the 9 palette -/// colors, expanded, positions inherited from the palette blob. -const List pulseInnerBloom = [ - PulseBlobSpec( - ci: 0, - region: PulseRegion.r1, - quad: PulseQuad.tl, - w: 84, - h: 48, - ), - PulseBlobSpec( - ci: 1, - region: PulseRegion.r2, - quad: PulseQuad.tl, - w: 72, - h: 42, - ), - PulseBlobSpec( - ci: 2, - region: PulseRegion.r3, - quad: PulseQuad.bl, - w: 48, - h: 84, - ), - PulseBlobSpec( - ci: 4, - region: PulseRegion.r2, - quad: PulseQuad.br, - w: 216, - h: 38, - ), - PulseBlobSpec( - ci: 5, - region: PulseRegion.r3, - quad: PulseQuad.br, - w: 102, - h: 31, - ), - PulseBlobSpec( - ci: 6, - region: PulseRegion.r1, - quad: PulseQuad.tr, - w: 89, - h: 38, - ), - PulseBlobSpec( - ci: 8, - region: PulseRegion.r3, - quad: PulseQuad.tr, - w: 62, - h: 58, - ), -]; - -/// Pulse-outside core/stroke table (React `PULSE_OUTER_CORE`): 8 blobs with -/// explicit edge positions. Used for BOTH the crisp stroke ring and the -/// outward core glow. -const List pulseOuterCore = [ - PulseBlobSpec( - ci: 0, - region: PulseRegion.r1, - quad: PulseQuad.tl, - w: 80, - h: 19, - x: 0.27, - y: 0, - ), - PulseBlobSpec( - ci: 6, - region: PulseRegion.r2, - quad: PulseQuad.tr, - w: 74, - h: 11, - x: 0.73, - y: -0.01, - ), - PulseBlobSpec( - ci: 7, - region: PulseRegion.r3, - quad: PulseQuad.tr, - w: 15, - h: 44, - x: 1.0, - y: 0.33, - ), - PulseBlobSpec( - ci: 8, - region: PulseRegion.r1, - quad: PulseQuad.br, - w: 19, - h: 38, - x: 1.01, - y: 0.72, - ), - PulseBlobSpec( - ci: 4, - region: PulseRegion.r2, - quad: PulseQuad.br, - w: 84, - h: 13, - x: 0.67, - y: 1.0, - ), - PulseBlobSpec( - ci: 1, - region: PulseRegion.r3, - quad: PulseQuad.bl, - w: 60, - h: 21, - x: 0.24, - y: 1.01, - ), - PulseBlobSpec( - ci: 2, - region: PulseRegion.r1, - quad: PulseQuad.bl, - w: 17, - h: 40, - x: 0.0, - y: 0.60, - ), - PulseBlobSpec( - ci: 3, - region: PulseRegion.r2, - quad: PulseQuad.tl, - w: 13, - h: 32, - x: -0.01, - y: 0.28, - ), -]; - -/// Pulse-outside bloom halo table (React `PULSE_OUTER_BLOOM`): 7 wider blobs. -const List pulseOuterBloom = [ - PulseBlobSpec( - ci: 0, - region: PulseRegion.r1, - quad: PulseQuad.tl, - w: 110, - h: 30, - x: 0.27, - y: 0.03, - ), - PulseBlobSpec( - ci: 6, - region: PulseRegion.r2, - quad: PulseQuad.tr, - w: 100, - h: 20, - x: 0.73, - y: 0.01, - ), - PulseBlobSpec( - ci: 7, - region: PulseRegion.r3, - quad: PulseQuad.tr, - w: 26, - h: 62, - x: 1.0, - y: 0.33, - ), - PulseBlobSpec( - ci: 8, - region: PulseRegion.r1, - quad: PulseQuad.br, - w: 30, - h: 56, - x: 1.01, - y: 0.72, - ), - PulseBlobSpec( - ci: 4, - region: PulseRegion.r2, - quad: PulseQuad.br, - w: 120, - h: 22, - x: 0.67, - y: 0.99, - ), - PulseBlobSpec( - ci: 1, - region: PulseRegion.r3, - quad: PulseQuad.bl, - w: 88, - h: 32, - x: 0.24, - y: 0.99, - ), - PulseBlobSpec( - ci: 2, - region: PulseRegion.r1, - quad: PulseQuad.bl, - w: 28, - h: 58, - x: 0.0, - y: 0.60, - ), -]; diff --git a/lib/src/constants/rotate_stops.dart b/lib/src/constants/rotate_stops.dart deleted file mode 100644 index 16b24b0..0000000 --- a/lib/src/constants/rotate_stops.dart +++ /dev/null @@ -1,86 +0,0 @@ -// Verbatim transcription of the conic gradient stop/alpha tables of the -// rotate (React `md`) and small (React `sm`) variants, from the React library -// (border-beam v1.3.0, `src/styles.ts` — generateBorderVariantCSS / -// generateSmallVariantCSS, whose window/highlight/bloom tables are identical -// apart from the wider `smallMask` window). Every list is a CSS -// `conic-gradient` colour-stop list flattened into parallel stop and alpha -// lists: `stops[i]` is the CSS stop position 0–1 and `alphas[i]` the alpha of -// the white (dark theme) or black (light theme) colour at it. -// -// The tables are asymmetric in the stop axis: the bright core is followed by -// a short falloff on the leading side and a long soft foot on the trailing -// side, which is what makes the beam read as a head dragging a tail. - -/// `beam-mask` — the rotating soft window that reveals the rotate variant's -/// stroke and inner layers. -const List rotateWindowStops = [ - 0.0, 0.30, 0.36, 0.44, 0.52, 0.80, 0.86, 0.92, 0.95, 1.0, // -]; - -/// Alphas of [rotateWindowStops]. -const List rotateWindowAlphas = [ - 0.0, 0.0, 0.1, 0.35, 1.0, 1.0, 0.35, 0.1, 0.0, 0.0, // -]; - -/// `smallMask` — the wider window the small variant's inner layer uses. -const List smallWindowStops = [ - 0.0, 0.22, 0.28, 0.36, 0.46, 0.82, 0.88, 0.94, 0.97, 1.0, // -]; - -/// Alphas of [smallWindowStops]. -const List smallWindowAlphas = [ - 0.0, 0.0, 0.12, 0.4, 1.0, 1.0, 0.4, 0.12, 0.0, 0.0, // -]; - -/// The stroke's highlight sweep — white on the dark theme, black on the -/// light one. -const List rotateHighlightStops = [ - 0.0, 0.54, 0.57, 0.60, 0.63, 0.66, 0.69, 0.72, 0.75, 0.78, 1.0, // -]; - -/// Dark-theme alphas of [rotateHighlightStops]. -const List rotateHighlightAlphasDark = [ - 0.0, 0.0, 0.1, 0.3, 0.6, 0.75, 0.6, 0.3, 0.1, 0.0, 0.0, // -]; - -/// Light-theme alphas of [rotateHighlightStops]. -const List rotateHighlightAlphasLight = [ - 0.0, 0.0, 0.08, 0.2, 0.4, 0.55, 0.4, 0.2, 0.08, 0.0, 0.0, // -]; - -/// The sharp bloom band, painted into a blurred layer. -const List rotateBloomStops = [ - 0.0, 0.58, 0.62, 0.65, 0.67, 0.69, 0.70, 0.705, 0.715, 0.73, 0.75, 0.78, - 0.82, 1.0, // -]; - -/// Dark-theme alphas of [rotateBloomStops]. -const List rotateBloomAlphasDark = [ - 0.0, 0.0, 0.03, 0.08, 0.2, 0.45, 0.85, 0.85, 0.45, 0.2, 0.08, 0.03, 0.0, - 0.0, // -]; - -/// Light-theme alphas of [rotateBloomStops]. -const List rotateBloomAlphasLight = [ - 0.0, 0.0, 0.02, 0.08, 0.2, 0.4, 0.6, 0.6, 0.4, 0.2, 0.08, 0.02, 0.0, 0.0, // -]; - -/// The blur sigma of the rotate/small bloom layer (CSS `filter: blur(8px)`). -const double rotateBloomBlurSigma = 8; - -/// The inner shadow blur of the rotate variant's inner layer. -const double rotateInnerShadowBlur = 9; - -/// The inner shadow blur of the small variant's inner layer. -const double smallInnerShadowBlur = 5; - -/// The alpha the rotate variant's inner blobs are fixed at (its inner layer -/// is derived from the border blob table at 0.9× size). -const double rotateInnerBlobAlpha = 0.45; - -/// The mono palette's replacement for [rotateInnerBlobAlpha]. -const double rotateInnerBlobAlphaMono = 0.225; - -/// The size factor the rotate variant's inner blobs take from the border -/// table. -const double rotateInnerBlobScale = 0.9; diff --git a/lib/src/constants/theme_presets.dart b/lib/src/constants/theme_presets.dart deleted file mode 100644 index e573879..0000000 --- a/lib/src/constants/theme_presets.dart +++ /dev/null @@ -1,109 +0,0 @@ -import 'dart:ui'; - -import '../models/beam_theme_config.dart'; -import '../models/beam_variant.dart'; - -// Verbatim transcription of `sizeThemePresets` from the React library -// (border-beam v1.3.0, src/styles.ts). Do not tweak values here — visual -// parity with the source depends on them. - -const Color _transparent = Color(0x00000000); - -/// Per-variant, per-brightness theme presets (React `sizeThemePresets`). -const Map -beamThemePresets = { - BeamVariant.small: ( - dark: BeamThemeConfig( - strokeOpacity: 0.46, - innerOpacity: 0.24, - bloomOpacity: 0.38, - innerShadow: Color.fromRGBO(255, 255, 255, 0.3), - saturation: 1.2, - ), - light: BeamThemeConfig( - strokeOpacity: 0.12, - innerOpacity: 0.3, - bloomOpacity: 0.16, - innerShadow: Color.fromRGBO(0, 0, 0, 0.14), - saturation: 1.8, - ), - ), - BeamVariant.rotate: ( - dark: BeamThemeConfig( - strokeOpacity: 0.26, - innerOpacity: 0.42, - bloomOpacity: 0.24, - innerShadow: Color.fromRGBO(255, 255, 255, 0.27), - saturation: 1.2, - ), - light: BeamThemeConfig( - strokeOpacity: 0.12, - innerOpacity: 0.26, - bloomOpacity: 0.34, - innerShadow: Color.fromRGBO(0, 0, 0, 0.14), - saturation: 1.5, - ), - ), - BeamVariant.line: ( - dark: BeamThemeConfig( - strokeOpacity: 1.14, - innerOpacity: 0.7, - bloomOpacity: 0.8, - innerShadow: Color.fromRGBO(255, 255, 255, 0.1), - saturation: 1.2, - ), - light: BeamThemeConfig( - strokeOpacity: 0.16, - innerOpacity: 0.32, - bloomOpacity: 0.3, - innerShadow: Color.fromRGBO(0, 0, 0, 0.14), - saturation: 1.95, - ), - ), - BeamVariant.pulseOutside: ( - dark: BeamThemeConfig( - strokeOpacity: 0.94, - innerOpacity: 0.34, - bloomOpacity: 0.3, - innerShadow: _transparent, - saturation: 1.2, - brightness: 1.9, - // The wrapped child supplies its own 1px border; the beam must not add - // a second hairline on top (see React v1.1.0 changelog). - hairlineOpacity: 0, - ), - light: BeamThemeConfig( - strokeOpacity: 1.96, - innerOpacity: 1.04, - bloomOpacity: 0.42, - innerShadow: _transparent, - saturation: 0.6, - brightness: 1.7, - hairlineOpacity: 0, - ), - ), - BeamVariant.pulseInside: ( - dark: BeamThemeConfig( - strokeOpacity: 1.54, - innerOpacity: 0.44, - bloomOpacity: 0.66, - innerShadow: _transparent, - saturation: 1.2, - brightness: 0.75, - ), - light: BeamThemeConfig( - strokeOpacity: 0.32, - innerOpacity: 0.4, - bloomOpacity: 0.8, - innerShadow: _transparent, - saturation: 0.75, - brightness: 1.3, - ), - ), -}; - -/// Resolves the theme preset for a variant and brightness. -BeamThemeConfig themePresetFor(BeamVariant variant, Brightness brightness) { - final preset = beamThemePresets[variant]!; - return brightness == Brightness.dark ? preset.dark : preset.light; -} diff --git a/lib/src/constants/upstream.dart b/lib/src/constants/upstream.dart deleted file mode 100644 index 2c8eb13..0000000 --- a/lib/src/constants/upstream.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Provenance of the tables in this directory. -// -// Everything under `lib/src/constants/` is a hand transcription of the React -// border-beam library's `src/styles.ts`. The constants below name the exact -// upstream artefact those transcriptions were audited against, so a reader -// (and `test/constants/spec_parity_test.dart`) can tell which upstream -// release the numbers belong to. They are internal — the barrel does not -// export them. - -/// Version of the React `border-beam` library the constant tables are -/// transcribed from, as reported by `sourceLibrary.version` in the upstream -/// machine-readable spec. -/// -/// The upstream npm package is versioned separately and currently reads -/// `1.4.0`; that release is visually identical to `1.3.0` and its spec still -/// declares `1.3.0` as the visual baseline. -const String upstreamLibraryVersion = '1.3.0'; - -/// Schema version of the upstream `spec/beam-spec.json` the parity test -/// reads (`specVersion` in that file). -const String upstreamSpecVersion = '1.0.0'; - -/// Where the upstream source and its generated spec live. -/// -/// `spec/beam-spec.json` under this path is vendored at -/// `test/fixtures/beam-spec.json`; refresh it with `tool/spec/refresh.sh`. -const String upstreamRepository = - 'https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam'; diff --git a/lib/src/effects/beam_effect.dart b/lib/src/effects/beam_effect.dart new file mode 100644 index 0000000..9bbffa3 --- /dev/null +++ b/lib/src/effects/beam_effect.dart @@ -0,0 +1,165 @@ +import 'package:flutter/foundation.dart'; + +import '../models/beam_options.dart'; + +/// What a beam does: how its light is placed along the border and how it +/// moves. +/// +/// Every effect is rendered by the same single-pass shader, so they all cost +/// the same order of GPU time — pick for the look, not for performance. +/// +/// Effects fall into two families: +/// +/// * **Travelling** — [BeamEffect.rotate], [BeamEffect.line]. A position +/// runs along the border once per cycle; these respond to +/// `BeamTiming.direction`, `BeamTiming.cycleGap`, `BorderBeam.progress`, +/// and `BorderBeam.follow`. +/// * **Ambient** — [BeamEffect.pulse]. Light breathes around the whole +/// border; the travel inputs are ignored. +@immutable +sealed class BeamEffect { + const BeamEffect._(); + + /// A beam of light that travels around the whole border, trailing a soft + /// tail and lighting the inside edge as it passes. Cards, panels, surfaces. + /// + /// [length] scales the tail (0.25–2, default 1), [count] puts several beams + /// on the border at once, evenly spaced (1–4), and [comet] adds an outer + /// glow that trails the head outside the border. + const factory BeamEffect.rotate({double length, int count, bool comet}) = + RotateEffect; + + /// A streak that rides one edge, its colours spread across it, with light + /// spiking up from the edge. Inputs, search bars, composers. + const factory BeamEffect.line({BeamEdge edge}) = LineEffect; + + /// Colour breathing inward from the whole border, strongest at the + /// corners. A contained "thinking" state. + const factory BeamEffect.pulse() = PulseEffect; + + /// Every effect with its default parameters, in gallery order. + static const List values = [ + BeamEffect.rotate(), + BeamEffect.line(), + BeamEffect.pulse(), + ]; + + /// A short identifier, e.g. `rotate`. + String get name; + + /// Whether this is a travelling effect (see the class docs). + bool get travels; + + /// The cycle used when `BeamTiming.cycle` is not set. + Duration get defaultCycle; + + /// The hue drift used when `BeamStyle.hueMode` is not set. + BeamHueMode get defaultHueMode => BeamHueMode.pingPong; + + /// The hue drift period used when `BeamTiming.huePeriod` is not set. + Duration get defaultHuePeriod => const Duration(seconds: 12); + + /// The rest between sweeps used when `BeamTiming.cycleGap` is not set. + Duration get defaultCycleGap => Duration.zero; + + @override + String toString() => 'BeamEffect.$name()'; +} + +/// See [BeamEffect.rotate]. +final class RotateEffect extends BeamEffect { + /// Creates a rotating beam. + const RotateEffect({this.length = 1, this.count = 1, this.comet = false}) + : assert(length > 0, 'length must be positive'), + assert(count >= 1 && count <= 4, 'count must be 1–4'), + super._(); + + /// Tail length multiplier (clamped to 0.25–2). + final double length; + + /// How many beams travel the border at once, evenly spaced. + final int count; + + /// Whether a glow trails the head outside the border. + final bool comet; + + @override + String get name => 'rotate'; + + @override + bool get travels => true; + + @override + Duration get defaultCycle => const Duration(milliseconds: 2400); + + @override + bool operator ==(Object other) => + other is RotateEffect && + other.length == length && + other.count == count && + other.comet == comet; + + @override + int get hashCode => Object.hash(RotateEffect, length, count, comet); + + @override + String toString() => + 'BeamEffect.rotate(length: $length, count: $count, comet: $comet)'; +} + +/// See [BeamEffect.line]. +final class LineEffect extends BeamEffect { + /// Creates a line beam on [edge]. + const LineEffect({this.edge = BeamEdge.bottom}) : super._(); + + /// The edge the streak rides. + final BeamEdge edge; + + @override + String get name => 'line'; + + @override + bool get travels => true; + + @override + Duration get defaultCycle => const Duration(milliseconds: 3100); + + @override + Duration get defaultHuePeriod => const Duration(seconds: 8); + + @override + bool operator ==(Object other) => other is LineEffect && other.edge == edge; + + @override + int get hashCode => Object.hash(LineEffect, edge); + + @override + String toString() => 'BeamEffect.line(edge: ${edge.name})'; +} + +/// See [BeamEffect.pulse]. +final class PulseEffect extends BeamEffect { + /// Creates a pulse. + const PulseEffect() : super._(); + + @override + String get name => 'pulse'; + + @override + bool get travels => false; + + @override + Duration get defaultCycle => const Duration(milliseconds: 2300); + + @override + BeamHueMode get defaultHueMode => BeamHueMode.continuous; + + @override + Duration get defaultHuePeriod => const Duration(seconds: 16); + + @override + bool operator ==(Object other) => other is PulseEffect; + + @override + int get hashCode => (PulseEffect).hashCode; +} diff --git a/lib/src/effects/effect_emitters.dart b/lib/src/effects/effect_emitters.dart new file mode 100644 index 0000000..ed75548 --- /dev/null +++ b/lib/src/effects/effect_emitters.dart @@ -0,0 +1,1019 @@ +import 'dart:math' as math; +import 'dart:typed_data'; +import 'dart:ui'; + +import 'package:flutter/animation.dart' show Curves; + +import '../animation/beam_phases.dart'; +import '../look/beam_look.dart'; +import '../look/layer_presets.dart'; +import '../look/line_look.dart'; +import '../look/look_blobs.dart'; +import '../look/palette_tables.dart'; +import '../look/pulse_look.dart'; +import '../look/pulse_tables.dart'; +import '../look/rotate_look.dart'; +import '../models/beam_config.dart'; +import '../models/beam_options.dart'; +import '../models/beam_segment.dart'; +import '../render/beam_frame.dart'; +import '../render/beam_outline.dart'; +import 'beam_effect.dart'; + +/// Everything an effect reads to write one frame. +final class BeamFrame { + /// Creates a frame context. + BeamFrame({ + required this.config, + required this.phases, + required this.outline, + required this.data, + required this.alpha, + }); + + /// The resolved config. + final BeamConfig config; + + /// This frame's phases. + final BeamFramePhases phases; + + /// The outline being lit. + final BeamOutline outline; + + /// The uniforms being written. + final BeamFrameData data; + + /// The frame's overall opacity: fade × strength × any extra. + final double alpha; + + /// The palette's blob tables. + late final BeamLookTables tables = BeamLook.tablesFor(config.palette); + + /// Whether the beam is styled for a dark surface. + bool get dark => config.isDark; + + /// Whether the palette is the greyscale one. + bool get mono => config.palette.mono; + + /// The outline box. + Rect get rect => outline.rect; + + /// Perimeter length, px. + double get length => outline.length; + + /// How much of the glow layers' opacity survives `BeamStyle.glow` (below 1 + /// the glows fade, so 0 leaves the hairline alone). + double get glowOpacity => math.min(config.glow, 1); + + /// How far `BeamStyle.glow` grows the glows. + double get glowSize => math.max(config.glow, 0.05); + + /// How far in from the edge an inner glow fades out: the design's 28 px, + /// grown by `BeamStyle.glow`, but never more than 0.4 of the box, so a + /// chip keeps a clear band through its middle. + double get edgeFade => + math.min(innerEdgeFade * glowSize, rect.shortestSide * 0.4); + + /// Whether the box is small enough for the compact chip treatment. + bool get compact => rect.shortestSide <= compactMaxExtent; + + /// Whether the hue holds still. + bool get staticHue => config.hueMode == BeamHueMode.none; + + /// The ambient clock, in seconds. + double get seconds => phases.cycles * config.cycleSeconds; + + /// A point of the box given as fractions of it. + Offset at(double fx, double fy) => + Offset(rect.left + fx * rect.width, rect.top + fy * rect.height); +} + +/// Writes [frame]'s layers into its data. The data must be reset and carry +/// the outline and the user's segment already. +void emitEffect(BeamFrame frame) { + final effect = frame.config.effect; + switch (effect) { + case RotateEffect(): + _rotate(frame, effect); + case LineEffect(): + _line(frame, effect); + case PulseEffect(): + _pulse(frame); + } +} + +/// Applies [segment] (if any) to [data]'s visible track, with [dashes]. +void applyTrack( + BeamFrameData data, + BeamSegment? segment, + BeamOutline outline, + int dashes, +) { + if (segment == null || outline.length <= 0) { + data.setTrack(0, 0, 0, dashes); + return; + } + final range = segment.resolve(outline); + var span = BeamOutline.wrapFraction(range.to - range.from); + // Ends that meet run the whole way round from the start. The shader + // leaves a whole-turn track unmasked, so the join is never faded. + if (span <= 0) span = 1; + // Negative (or NaN) is a hard cut, as zero is. + final feather = segment.feather > 0 ? segment.feather : 0.0; + data.setTrack( + range.from, + span, + math.min(feather / outline.length, span / 2), + dashes, + ); +} + +/// The visible track as `(start, span)`; the whole border when no segment +/// is set. +({double start, double span}) segmentTrack(BeamFrameData data) => + data.trackSpan <= 0 + ? (start: 0.0, span: 1.0) + : (start: data.trackStart, span: data.trackSpan); + +// ─── Shared pieces ────────────────────────────────────────────────────────── + +/// The conic coordinate of [point] around [centre]: 0 at 12 o'clock, +/// increasing clockwise, in turns. +double conicFraction(Offset point, Offset centre) { + final d = point - centre; + final t = math.atan2(d.dx, -d.dy) / (2 * math.pi); + return t - t.floorToDouble(); +} + +// Scratch lists for table transforms: no allocation per frame. +final Float64List _stops = Float64List(tableStops); +final Float64List _alphas = Float64List(tableStops); +final Float64List _blurStops = Float64List(tableStops); +final Float64List _blurAlphas = Float64List(tableStops); + +double _lookup(List stops, List alphas, int n, double t) { + if (t <= stops[0]) return alphas[0]; + for (var i = 1; i < n; i++) { + if (t <= stops[i]) { + final span = math.max(stops[i] - stops[i - 1], 1e-9); + return alphas[i - 1] + + (alphas[i] - alphas[i - 1]) * (t - stops[i - 1]) / span; + } + } + return alphas[n - 1]; +} + +/// Writes a conic table, its tail scaled by [tail] about the bright core's +/// leading edge, mirrored when [reversed], and blurred around the turn by +/// [blur] turns. +void _conicTable( + BeamFrameData data, + BeamTable table, + List stops, + List alphas, { + double tail = 1, + bool reversed = false, + double shift = 0, + double blur = 0, +}) { + final n = math.min(stops.length, tableStops); + var peak = alphas[0]; + for (var i = 0; i < n; i++) { + peak = math.max(peak, alphas[i]); + } + var head = stops[0]; + for (var i = 0; i < n; i++) { + if (alphas[i] >= peak) head = stops[i]; + } + // The lit band, ignoring the table's 0 and 1 anchors. + var first = 0; + while (first < n - 1 && alphas[first + 1] <= 0) { + first++; + } + var last = n - 1; + while (last > 0 && alphas[last - 1] <= 0) { + last--; + } + var f = tail; + if (f != 1) { + final back = head - stops[first]; + final front = stops[last] - head; + var limit = double.infinity; + if (back > 0) limit = math.min(limit, head / back); + if (front > 0) limit = math.min(limit, (1 - head) / front); + f = f.clamp(0.05, math.max(0.05, limit)); + } + for (var i = 0; i < n; i++) { + final s = (head + (stops[i] - head) * f + shift).clamp(0.0, 1.0); + final j = reversed ? n - 1 - i : i; + _stops[j] = reversed ? 1 - s : s; + _alphas[j] = alphas[i]; + } + if (blur <= 1e-4) { + data.setTable(table, _stops, _alphas, n); + return; + } + // Resample the table convolved with a gaussian of [blur] turns over its + // lit band, widened by three sigmas. + final lo = math.max(0.0, _stops[reversed ? n - 1 - last : first] - 3 * blur); + final hi = math.min(1.0, _stops[reversed ? n - 1 - first : last] + 3 * blur); + const taps = 9; + _blurStops[0] = 0; + _blurAlphas[0] = 0; + final inner = tableStops - 2; + for (var i = 0; i < inner; i++) { + final x = lo + (hi - lo) * i / (inner - 1); + var sum = 0.0; + var weight = 0.0; + for (var k = 0; k < taps; k++) { + final o = (k - (taps - 1) / 2) / ((taps - 1) / 2) * 2.5; + final w = math.exp(-0.5 * o * o); + sum += w * _lookup(_stops, _alphas, n, (x + o * blur).clamp(0.0, 1.0)); + weight += w; + } + _blurStops[i + 1] = x; + _blurAlphas[i + 1] = sum / weight; + } + _blurStops[tableStops - 1] = 1; + _blurAlphas[tableStops - 1] = 0; + data.setTable(table, _blurStops, _blurAlphas, tableStops); +} + +/// Sets a layer's colour filter: the hue drift with the preset's +/// brightness and saturation, or — with the hue held — no filter beyond the +/// static hue base, unless [keepTone] keeps the brightness and saturation. +void _filter( + BeamFrame f, + int k, + BeamLayerPreset preset, { + double? hue, + bool keepTone = false, +}) { + final h = f.staticHue + ? f.config.hueBase + : (hue ?? f.phases.hueDegrees) + f.config.hueBase; + if (f.staticHue && !keepTone) { + f.data.setFilter(k, hue: h); + return; + } + f.data.setFilter( + k, + hue: h, + brightness: preset.brightness, + saturation: preset.saturation, + ); +} + +/// The inner glow's inset shadow for a layer. +void _shadow(BeamFrame f, int k, Color color, double blur) { + if (color.a <= 0) return; + f.data.setShadow(k, color, depth: blur + 1, sigma: blur / 2); +} + +double _ping(double t, double period, double range) { + final c = t / period; + final cycle = c - c.floorToDouble(); + final local = cycle < 0.5 ? cycle / 0.5 : (1 - cycle) / 0.5; + final eased = Curves.easeInOut.transform(local.clamp(0.0, 1.0)); + return -range + 2 * range * eased; +} + +// ─── Rotate ───────────────────────────────────────────────────────────────── + +void _rotate(BeamFrame f, RotateEffect e) { + final d = f.data; + final rect = f.rect; + final dark = f.dark; + final compact = f.compact; + final preset = presetFor( + compact ? compactPresets : rotatePresets, + dark: dark, + ); + final base = f.alpha * (f.mono ? 0.5 : 1); + final reversed = f.phases.reversedNow; + final n = f.config.beamCount; + final tail = e.length.isNaN ? 1.0 : e.length.clamp(0.25, 2.0); + final sigma = rotateBloomBlur * f.glowSize; + + _conicTable( + d, + BeamTable.windowA, + rotateWindowStops, + rotateWindowAlphas, + tail: tail, + reversed: reversed, + ); + if (compact) { + _conicTable( + d, + BeamTable.windowB, + compactWindowStops, + compactWindowAlphas, + tail: tail, + reversed: reversed, + ); + } + _conicTable( + d, + BeamTable.overlayA, + rotateHighlightStops, + dark ? rotateHighlightAlphasDark : rotateHighlightAlphasLight, + tail: tail, + reversed: reversed, + ); + _conicTable( + d, + BeamTable.overlayB, + rotateBloomStops, + dark ? rotateBloomAlphasDark : rotateBloomAlphasLight, + tail: tail * (e.comet ? 1.6 : 1), + reversed: reversed, + blur: sigma * n / math.max(f.length, 1), + ); + final head = reversed ? 1 - rotateHeadStop : rotateHeadStop; + d.setConic(rect.center, _headAngle(f) - head / n, n); + + // Inner glow. + d + ..setLayer( + 0, + BeamGeometry.fill, + opacity: base * preset.innerOpacity * f.glowOpacity, + ) + ..setConicWindow(0, compact ? BeamTable.windowB : BeamTable.windowA); + if (!compact) d.setEdgeFade(0, f.edgeFade); + _shadow( + f, + 0, + preset.innerShadow, + compact ? compactInnerShadowBlur : rotateInnerShadowBlur, + ); + _filter(f, 0, preset); + if (compact) { + for (final b in f.tables.smallInner) { + final c = f.at(b.position.dx, b.position.dy); + d.addSimpleBlob( + 0, + cx: c.dx, + cy: c.dy, + rx: b.size.width, + ry: b.size.height, + color: b.color, + ); + } + } else { + final alpha = f.mono ? rotateInnerBlobAlphaMono : rotateInnerBlobAlpha; + for (final b in f.tables.border) { + final c = f.at(b.position.dx, b.position.dy); + d.addSimpleBlob( + 0, + cx: c.dx, + cy: c.dy, + rx: (b.size.width * rotateInnerBlobScale).roundToDouble(), + ry: (b.size.height * rotateInnerBlobScale).roundToDouble(), + color: b.color.withValues(alpha: alpha), + ); + } + } + + // Hairline stroke. + d + ..setLayer(1, BeamGeometry.ring, opacity: base * preset.strokeOpacity) + ..setConicWindow(1, BeamTable.windowA) + ..setOverlay(1, BeamTable.overlayA, white: dark) + ..setDashed(1); + _filter(f, 1, preset); + for (final b in compact ? f.tables.smallBorder : f.tables.border) { + final c = f.at(b.position.dx, b.position.dy); + d.addSimpleBlob( + 1, + cx: c.dx, + cy: c.dy, + rx: b.size.width, + ry: b.size.height, + color: b.color, + ); + } + + // Bloom: the bright band at the head, blurred — or, as a comet, a glow + // trailing the head outside the border. + d + ..setLayer( + 2, + e.comet ? BeamGeometry.glow : BeamGeometry.blurredRing, + opacity: base * preset.bloomOpacity * f.glowOpacity, + sigma: sigma, + inflate: e.comet ? cometReach * f.glowSize : 0, + ) + ..setOverlay(2, BeamTable.overlayB, white: dark) + ..setDashed(2) + ..setFilter( + 2, + brightness: preset.brightness, + saturation: preset.saturation, + ); +} + +/// The conic angle the head of a travelling beam sits at: the travel itself +/// around the turn, or — on a segment — the point of the track it has +/// reached. +double _headAngle(BeamFrame f) { + final p = f.phases.travelProgress; + final track = segmentTrack(f.data); + if (track.span >= 1) return p; + return conicFraction( + f.outline.pointAt(track.start + track.span * p), + f.rect.center, + ); +} + +// ─── Line ─────────────────────────────────────────────────────────────────── + +void _line(BeamFrame f, LineEffect e) { + final d = f.data; + final dark = f.dark; + final preset = presetFor(linePresets, dark: dark); + final p = f.phases.travelProgress.clamp(0.0, 1.0); + final driven = f.phases.driven; + final x = driven ? p : sampleKeyframes(lineTravelX, p); + final w = driven ? 1.2 : sampleKeyframes(lineTravelW, p); + final fade = driven ? 1.0 : sampleKeyframes(lineEdgeFade, p); + final cyc = f.phases.cycles; + double frac(double v) => v - v.floorToDouble(); + final h = sampleKeyframes( + lineBreatheH, + frac(cyc / lineBreathePeriod), + eased: true, + ); + final s1 = sampleKeyframes( + lineSpike, + frac(cyc / lineSpikePeriod), + eased: true, + ); + final s2 = sampleKeyframes( + lineSpike2, + frac(cyc / lineSpike2Period), + eased: true, + ); + final base = f.alpha * fade; + if (base <= 0) return; + + // Two hue tracks: the stroke and glow swing gently, the bloom wider and + // faster. A static frame has no hue time, and holds both at the palette. + final range = math.min(f.config.hueShift, lineHueCap); + final period = f.config.huePeriodSeconds; + final (strokeHue, bloomHue) = switch ((f.config.hueMode, f.phases.hueTime)) { + (BeamHueMode.none, _) || (BeamHueMode.pingPong, null) => (0.0, 0.0), + (BeamHueMode.continuous, _) => (f.phases.hueDegrees, f.phases.hueDegrees), + (BeamHueMode.pingPong, final double ht) => ( + _ping(ht, period * 1.5, range), + _ping(ht, period, range + lineBloomHueBonus), + ), + }; + + final frame = _LineFrame(f, e.edge); + final bx = x * frame.width; + final tables = f.tables; + + // Inner glow. + d + ..setLayer( + 0, + BeamGeometry.fill, + opacity: base * preset.innerOpacity * f.glowOpacity, + ) + ..setEdgeFade(0, f.edgeFade); + frame.space(0); + frame.window( + 0, + bx, + 0, + lineWindowRadiusX * w, + lineWindowRadiusY * h, + lineWindowMidStop, + lineWindowMidAlpha, + ); + _shadow(f, 0, preset.innerShadow, lineInnerShadowBlur); + _filter(f, 0, preset, hue: strokeHue); + for (final b in tables.lineInner) { + frame.blob( + 0, + bx + b.offsetX, + b.offsetY.abs(), + b.sizeW * w, + b.sizeH * h, + b.color, + ); + } + + // Stroke: the travelling highlight over the streak's blobs. + d + ..setLayer(1, BeamGeometry.ring, opacity: base * preset.strokeOpacity) + ..setDashed(1); + frame.space(1); + frame.window( + 1, + bx, + 0, + lineWindowRadiusX * w, + lineWindowRadiusY * h, + lineWindowMidStop, + lineWindowMidAlpha, + ); + _filter(f, 1, preset, hue: strokeHue); + final hiAlphas = dark ? lineHighlightAlphasDark : lineHighlightAlphasLight; + final hiStops = dark ? lineHighlightStopsDark : lineHighlightStopsLight; + frame.stopBlob( + 1, + bx, + -lineHighlightOffsetY, + (dark ? lineHighlightRadiusXDark : lineHighlightRadiusXLight) * w, + (dark ? lineHighlightRadiusYDark : lineHighlightRadiusYLight) * h, + dark ? const Color(0xFFFFFFFF) : const Color(0xFF000000), + hiAlphas, + hiStops, + ); + for (final b in dark ? tables.lineDark : tables.lineLight) { + frame.blob( + 1, + bx + b.offsetX, + -b.offsetY, + b.sizeW * w, + b.sizeH * h, + b.color, + ); + } + + // Bloom: seven spikes rising from the edge, the travelling dot and its + // ambient glow (or, on a light surface, a soft shadow), seen through a + // tall window that travels with the streak. + final mono = f.mono; + final blur = (mono ? lineBloomBlurMono : lineBloomBlur) * f.glowSize; + d.setLayer( + 2, + BeamGeometry.fill, + opacity: base * preset.bloomOpacity * f.glowOpacity, + ); + frame.space(2, blur: blur); + frame.window( + 2, + bx, + 0, + lineBloomWindowRadiusX * w, + lineBloomWindowRadiusY * h, + lineBloomWindowMidStop, + lineBloomWindowMidAlpha, + ); + _filter(f, 2, preset, hue: bloomHue); + _lineSpikes( + frame, + tables, + dark: dark, + mono: mono, + s1: s1, + s2: s2, + h: h, + w: w, + bx: bx, + ); +} + +void _lineSpikes( + _LineFrame frame, + BeamLookTables tables, { + required bool dark, + required bool mono, + required double s1, + required double s2, + required double h, + required double w, + required double bx, +}) { + final spikeColors = dark ? tables.spike : tables.spikeLt; + final table = dark ? tables.lineBloomDark : tables.lineBloomLight; + Color att(Color c, double k) => + c.a < 1 ? c.withValues(alpha: c.a * k) : c.withValues(alpha: k); + final sc1 = mono + ? att(spikeColors.primary, lineMonoSpike1) + : spikeColors.primary; + final sc1Mid = dark + ? (mono + ? att(spikeColors.primary, lineMonoSpike1MidDark) + : spikeColors.primary) + : (mono + ? att(spikeColors.primary, lineMonoSpike1MidLight) + : spikeColors.primary.withValues(alpha: lineSpike1MidLightAlpha)); + final sc2 = mono + ? att(spikeColors.secondary, lineMonoSpike2) + : spikeColors.secondary; + final sc2Mid = dark + ? spikeColors.secondary.withValues( + alpha: mono ? lineMonoSpike2MidDark : lineSpike2MidDarkAlpha, + ) + : (mono + ? att(spikeColors.secondary, lineMonoSpike2MidLight) + : spikeColors.secondary.withValues(alpha: lineSpike2MidLightAlpha)); + SpikePair pair(int i) => mono + ? SpikePair( + att(table[i].color1, lineMonoTableSpike1), + att(table[i].color2, lineMonoTableSpike2), + ) + : table[i]; + final thinW = mono ? lineMonoThinSpikeWidths : lineThinSpikeWidths; + final thinH = mono ? lineMonoThinSpikeHeights : lineThinSpikeHeights; + final thinLW = mono + ? lineMonoThinSpikeWidthLight92 + : lineThinSpikeWidthLight92; + final wa = frame.width; + + void spike(int i, double rx, double ry, Color c0, Color mid) { + final g = lineSpikes[i]; + frame.stopBlob( + 2, + g.fx * wa, + g.yInset, + rx, + ry, + c0, + [c0.a, mid.a, 0], + [0, g.midStop, g.endStop], + ); + } + + spike(0, thinW[0] * s1, thinH[0] * h, sc1, sc1Mid); + spike(1, lineSpikeWideRadiusX22 * s2, lineSpikeRadiusY22 * h, sc2, sc2Mid); + spike(2, thinW[1] * (2 - s1), thinH[1] * h, pair(0).color1, pair(0).color2); + spike( + 3, + lineSpikeWideRadiusX50 * s2, + lineSpikeRadiusY50 * h, + pair(1).color1, + pair(1).color2, + ); + spike(4, thinW[2] * (2 - s2), thinH[2] * h, pair(2).color1, pair(2).color2); + spike( + 5, + lineSpikeRadiusX78 * s1, + lineSpikeRadiusY78 * h, + pair(3).color1, + pair(3).color2, + ); + spike( + 6, + (dark ? thinW[3] : thinLW) * (2 - s1), + thinH[3] * h, + pair(4).color1, + pair(4).color2, + ); + + const white = Color(0xFFFFFFFF); + const black = Color(0xFF000000); + if (dark) { + frame.stopBlob( + 2, + bx, + -lineDotOffsetY, + lineDotRadiusX * s1, + lineDotRadiusY * s2, + white, + [...(mono ? lineDotAlphasMono : lineDotAlphas), 0], + lineDotStops, + ); + frame.stopBlob( + 2, + bx, + 0, + lineAmbientRadiusX * w, + lineAmbientRadiusY * h, + white, + [...(mono ? lineAmbientAlphasMono : lineAmbientAlphas), 0], + lineAmbientStops, + ); + } else { + frame.stopBlob( + 2, + bx, + 0, + lineShadowRadiusX * w, + lineShadowRadiusY * h, + black, + lineShadowAlphas, + lineShadowStops, + ); + } +} + +/// The frame the line is authored in — the streak riding the bottom edge of +/// a [width] × [height] box, x along the edge and y the depth in from it — +/// mapped onto the real edge so the streak runs in reading order (left to +/// right, top to bottom), or onto the user's segment in path space. +class _LineFrame { + _LineFrame(this.f, this.edge) { + final r = f.rect; + final track = f.data.trackSpan > 0; + path = track; + if (track) { + width = f.data.trackSpan * f.length; + height = r.height; + start = f.data.trackStart * f.length; + } else { + final vertical = edge == BeamEdge.left || edge == BeamEdge.right; + width = vertical ? r.height : r.width; + height = vertical ? r.width : r.height; + } + } + + final BeamFrame f; + final BeamEdge edge; + late final bool path; + late final double width; + late final double height; + double start = 0; + + bool get _swap => !path && (edge == BeamEdge.left || edge == BeamEdge.right); + + /// The canvas point (or path-space point) of authored x along the edge + /// and [depth] in from it. + Offset map(double x, double depth) { + if (path) return Offset(start + x, depth); + final r = f.rect; + return switch (edge) { + BeamEdge.bottom => Offset(r.left + x, r.bottom - depth), + BeamEdge.top => Offset(r.left + x, r.top + depth), + BeamEdge.left => Offset(r.left + depth, r.top + x), + BeamEdge.right => Offset(r.right - depth, r.top + x), + }; + } + + void space(int k, {double blur = 0}) => f.data.setBlobSpace( + k, + blur > 0 + ? (path ? BeamBlobSpace.blurredPath : BeamBlobSpace.blurred) + : (path ? BeamBlobSpace.path : BeamBlobSpace.planar), + blur: blur, + ); + + void window( + int k, + double x, + double depth, + double rx, + double ry, + double mid, + double midAlpha, + ) { + final c = map(x, depth); + f.data.setRadialWindow( + k, + c, + _swap ? ry : rx, + _swap ? rx : ry, + midStop: mid, + midAlpha: midAlpha, + ); + } + + void blob(int k, double x, double depth, double rx, double ry, Color color) { + final c = map(x, depth); + f.data.addSimpleBlob( + k, + cx: c.dx, + cy: c.dy, + rx: _swap ? ry : rx, + ry: _swap ? rx : ry, + color: color, + ); + } + + /// A blob with explicit alpha stops (2–4; the last alpha is 0). + void stopBlob( + int k, + double x, + double depth, + double rx, + double ry, + Color rgb, + List alphas, + List stops, + ) { + final c = map(x, depth); + final n = alphas.length; + double a1; + double p1; + double a2; + double p2; + final end = stops[n - 1]; + if (n >= 4) { + p1 = stops[1]; + a1 = alphas[1]; + p2 = stops[2]; + a2 = alphas[2]; + } else if (n == 3) { + p1 = stops[1]; + a1 = alphas[1]; + p2 = (stops[1] + end) / 2; + a2 = alphas[1] / 2; + } else { + p1 = end / 3; + a1 = alphas[0] * 2 / 3; + p2 = end * 2 / 3; + a2 = alphas[0] / 3; + } + f.data.addBlob( + k, + cx: c.dx, + cy: c.dy, + rx: _swap ? ry : rx, + ry: _swap ? rx : ry, + rgb: rgb, + a0: alphas[0], + p1: p1, + a1: a1, + p2: p2, + a2: a2, + p3: end, + clip: f.data.blobSpaceOf(k).index >= BeamBlobSpace.blurred.index + ? _edgeClip + : null, + ); + } + + // The edge the streak rides: a blurred layer is cut there before its + // blur, so light below the edge never spills back in. + ({int axis, double at, bool keepBelow}) get _edgeClip { + if (path) return (axis: 1, at: 0, keepBelow: false); + final r = f.rect; + return switch (edge) { + BeamEdge.bottom => (axis: 1, at: r.bottom, keepBelow: true), + BeamEdge.top => (axis: 1, at: r.top, keepBelow: false), + BeamEdge.left => (axis: 0, at: r.left, keepBelow: false), + BeamEdge.right => (axis: 0, at: r.right, keepBelow: true), + }; + } +} + +// ─── Pulse ────────────────────────────────────────────────────────────────── + +// One oscillator bank per tuning, rebuilt only when the tuning changes. +final Map<(bool, double), PulseOscillatorBank> _banks = {}; +final PulseFrame _pulseFrame = PulseFrame(); + +PulseOscillatorBank _bankFor(BeamFrame f) => + _banks[(f.dark, f.config.cycleSeconds)] ??= () { + if (_banks.length > 16) _banks.clear(); + return PulseOscillatorBank( + PulseParams.pulse(dark: f.dark, cycleSeconds: f.config.cycleSeconds), + ); + }(); + +double _quad(PulseFrame p, PulseQuad q) => p.bop[q.index]; + +BeamBlob _borderAt(BeamLookTables t, int i) => t.border[i % t.border.length]; + +/// One breathing pulse blob: its group's size and drift, its corner's +/// opacity. +void _pulseBlob( + BeamFrame f, + int k, { + required Rect box, + required Offset position, + required double w, + required double h, + required Color color, + required PulseRegion region, + required PulseQuad quad, + required PulseFrame pulse, +}) { + final r = region.index; + f.data.addSimpleBlob( + k, + cx: box.left + position.dx * box.width + pulse.bx[r], + cy: box.top + position.dy * box.height + pulse.by[r], + rx: w * pulse.bw[r], + ry: h * pulse.bh[r] * pulse.bgh, + color: color, + alpha: _quad(pulse, quad), + ); +} + +/// One static bloom blob at the breathing's average alpha. +void _frozenBlob( + BeamFrame f, + int k, { + required Rect box, + required Offset position, + required double w, + required double h, + required Color color, + required double alpha, +}) { + f.data.addSimpleBlob( + k, + cx: box.left + position.dx * box.width, + cy: box.top + position.dy * box.height, + rx: w, + ry: h, + color: color.withValues(alpha: alpha), + ); +} + +void _pulse(BeamFrame f) { + final d = f.data; + final dark = f.dark; + final preset = presetFor(pulsePresets, dark: dark); + final base = f.alpha * (f.mono ? 0.5 : 1); + final bank = _bankFor(f); + final pulse = _pulseFrame; + bank.sample(f.seconds, pulse); + final border = f.tables.border; + final rect = f.rect; + + // Inner glow: the breathing blobs and the corner accents, faded in from + // the edge. + d + ..setLayer( + 0, + BeamGeometry.fill, + opacity: base * preset.innerOpacity * f.glowOpacity, + ) + ..setEdgeFade(0, f.edgeFade); + _filter(f, 0, preset, keepTone: true); + for (final (i, b) in border.indexed) { + final map = pulseRingMap[i % pulseRingMap.length]; + final size = pulseInnerSizes[i % pulseInnerSizes.length]; + _pulseBlob( + f, + 0, + box: rect, + position: b.position, + w: size.width * f.glowSize, + h: size.height * f.glowSize, + color: b.color, + region: map.region, + quad: map.quad, + pulse: pulse, + ); + } + final corner = dark ? const Color(0xFFFFFFFF) : const Color(0xFF000000); + final cornerAlpha = dark ? pulseCornerAlphaDark : pulseCornerAlphaLight; + for (final (pos, quad) in const [ + (Offset(0, 0), PulseQuad.tl), + (Offset(1, 0), PulseQuad.tr), + (Offset(0, 1), PulseQuad.bl), + (Offset(1, 1), PulseQuad.br), + ]) { + final c = f.at(pos.dx, pos.dy); + d.addSimpleBlob( + 0, + cx: c.dx, + cy: c.dy, + rx: pulseCornerRadius * f.glowSize, + ry: pulseCornerRadius * f.glowSize, + color: corner.withValues(alpha: cornerAlpha * _quad(pulse, quad)), + end: pulseCornerEndStop, + ); + } + + // Stroke: the border blobs breathing on the hairline. + d + ..setLayer(1, BeamGeometry.ring, opacity: base * preset.strokeOpacity) + ..setDashed(1); + _filter(f, 1, preset, keepTone: true); + for (final (i, b) in border.indexed) { + final map = pulseRingMap[i % pulseRingMap.length]; + _pulseBlob( + f, + 1, + box: rect, + position: b.position, + w: b.size.width, + h: b.size.height, + color: b.color, + region: map.region, + quad: map.quad, + pulse: pulse, + ); + } + + // Bloom: the static blobs on the ring, blurred. + d.setLayer( + 2, + BeamGeometry.blurredRing, + opacity: base * preset.bloomOpacity * f.glowOpacity, + sigma: pulseBloomBlur * f.glowSize, + ); + _filter(f, 2, preset, keepTone: true); + for (final spec in pulseInnerBloom) { + final src = _borderAt(f.tables, spec.ci); + _frozenBlob( + f, + 2, + box: rect, + position: src.position, + w: spec.w, + h: spec.h, + color: src.color, + alpha: bank.params.frozenBloomAlpha, + ); + } +} diff --git a/lib/src/look/beam_look.dart b/lib/src/look/beam_look.dart new file mode 100644 index 0000000..f4abf3d --- /dev/null +++ b/lib/src/look/beam_look.dart @@ -0,0 +1,190 @@ +import 'dart:math' as math; +import 'dart:ui'; + +import 'package:flutter/painting.dart' show BorderRadius; + +import '../models/beam_palette.dart'; +import '../render/beam_outline.dart'; +import 'look_blobs.dart'; +import 'palette_tables.dart'; + +/// Resolves a palette to the blob tables every effect draws with. +/// +/// The original palettes carry their own tables. The extras cycle a short +/// colour list over `colorful`'s tables. Every other palette — custom stops, +/// solid, seeded, scheme, blended, scaled — keeps `colorful`'s geometry and +/// takes each blob's colour from the palette at the point of the border the +/// blob sits on. Resolved once per palette and remembered. +abstract final class BeamLook { + static final Expando _memo = Expando( + 'BeamLook', + ); + + /// The tables [palette] is drawn with. + static BeamLookTables tablesFor(BeamPalette palette) { + final own = palette.tables; + if (own != null) return own; + return _memo[palette] ??= _derive(palette); + } + + static BeamLookTables _derive(BeamPalette palette) { + final cycle = palette.tableColors; + if (cycle != null && cycle.isNotEmpty) { + return cycleColors(cycle, colorfulTables); + } + return sampleTables(palette); + } +} + +/// Distributes [colors] over [base]'s tables by index, cycling, and keeps +/// each entry's alpha so the layered depth of the look survives. +BeamLookTables cycleColors(List colors, BeamLookTables base) { + Color pick(int i, Color original) => + colors[i % colors.length].withValues(alpha: original.a); + return BeamLookTables( + border: [ + for (final (i, b) in base.border.indexed) b.withColor(pick(i, b.color)), + ], + spike: SpikeColors( + primary: pick(0, base.spike.primary), + secondary: pick(1, base.spike.secondary), + ), + spikeLt: SpikeColors( + primary: pick(0, base.spikeLt.primary), + secondary: pick(1, base.spikeLt.secondary), + ), + smallBorder: [ + for (final (i, b) in base.smallBorder.indexed) + b.withColor(pick(i, b.color)), + ], + smallInner: [ + for (final (i, b) in base.smallInner.indexed) + b.withColor(pick(i, b.color)), + ], + lineDark: [ + for (final (i, b) in base.lineDark.indexed) b.withColor(pick(i, b.color)), + ], + lineLight: [ + for (final (i, b) in base.lineLight.indexed) + b.withColor(pick(i, b.color)), + ], + lineInner: [ + for (final (i, b) in base.lineInner.indexed) + b.withColor(pick(i, b.color)), + ], + lineBloomDark: [ + for (final (i, s) in base.lineBloomDark.indexed) + SpikePair(pick(i, s.color1), pick(i, s.color2)), + ], + lineBloomLight: [ + for (final (i, s) in base.lineBloomLight.indexed) + SpikePair(pick(i, s.color1), pick(i, s.color2)), + ], + ); +} + +/// Every table colour passed through [f], keeping all geometry. +BeamLookTables mapTableColors(BeamLookTables t, Color Function(Color) f) => + BeamLookTables( + border: [for (final b in t.border) b.withColor(f(b.color))], + spike: SpikeColors( + primary: f(t.spike.primary), + secondary: f(t.spike.secondary), + ), + spikeLt: SpikeColors( + primary: f(t.spikeLt.primary), + secondary: f(t.spikeLt.secondary), + ), + smallBorder: [for (final b in t.smallBorder) b.withColor(f(b.color))], + smallInner: [for (final b in t.smallInner) b.withColor(f(b.color))], + lineDark: [for (final b in t.lineDark) b.withColor(f(b.color))], + lineLight: [for (final b in t.lineLight) b.withColor(f(b.color))], + lineInner: [for (final b in t.lineInner) b.withColor(f(b.color))], + lineBloomDark: [ + for (final s in t.lineBloomDark) SpikePair(f(s.color1), f(s.color2)), + ], + lineBloomLight: [ + for (final s in t.lineBloomLight) SpikePair(f(s.color1), f(s.color2)), + ], + ); + +/// [t] with every alpha multiplied by [factor] (clamped to 0–1). +BeamLookTables scaleTableAlpha(BeamLookTables t, double factor) => + mapTableColors( + t, + (c) => c.withValues(alpha: (c.a * factor).clamp(0.0, 1.0)), + ); + +// The boxes `colorful`'s tables are laid out on: a card and a chip. +final BeamOutline _card = BeamOutline( + const Rect.fromLTWH(0, 0, 350, 140), + const BorderRadius.all(Radius.circular(16)), +); +final BeamOutline _chip = BeamOutline( + const Rect.fromLTWH(0, 0, 70, 36), + const BorderRadius.all(Radius.circular(18)), +); + +// The spike positions along the edge, as fractions of its length. +const List _spikeAt = [0.36, 0.50, 0.64, 0.78, 0.92]; + +/// `colorful`'s tables recoloured from [palette]: each blob takes the +/// palette's colour at the point of the border it sits on (line blobs, which +/// travel with the streak, take it across the streak), keeping `colorful`'s +/// alpha. +BeamLookTables sampleTables(BeamPalette palette) { + const base = colorfulTables; + Color tint(Color c, double u) { + final s = palette.sample(u); + return s.withValues(alpha: (c.a * s.a).clamp(0.0, 1.0)); + } + + Color onCard(BeamBlob b) => tint( + b.color, + _card.nearestFraction(Offset(b.position.dx * 350, b.position.dy * 140)), + ); + Color onChip(BeamBlob b) => tint( + b.color, + _chip.nearestFraction(Offset(b.position.dx * 70, b.position.dy * 36)), + ); + // Across the streak, end to end: each table over its own width, since the + // light-surface streak is wider than the dark one and the inner glow. + List across(List blobs) { + final half = blobs.fold(0.0, (m, b) => math.max(m, b.offsetX.abs())); + return [ + for (final b in blobs) + b.withColor( + tint( + b.color, + half > 0 ? ((b.offsetX + half) / (2 * half)).clamp(0.0, 0.999) : 0, + ), + ), + ]; + } + + SpikePair spike(SpikePair s, double at) => + SpikePair(tint(s.color1, at), tint(s.color2, at)); + + return BeamLookTables( + border: [for (final b in base.border) b.withColor(onCard(b))], + spike: SpikeColors( + primary: tint(base.spike.primary, 0.08), + secondary: tint(base.spike.secondary, 0.22), + ), + spikeLt: SpikeColors( + primary: tint(base.spikeLt.primary, 0.08), + secondary: tint(base.spikeLt.secondary, 0.22), + ), + smallBorder: [for (final b in base.smallBorder) b.withColor(onChip(b))], + smallInner: [for (final b in base.smallInner) b.withColor(onChip(b))], + lineDark: across(base.lineDark), + lineLight: across(base.lineLight), + lineInner: across(base.lineInner), + lineBloomDark: [ + for (final (i, s) in base.lineBloomDark.indexed) spike(s, _spikeAt[i]), + ], + lineBloomLight: [ + for (final (i, s) in base.lineBloomLight.indexed) spike(s, _spikeAt[i]), + ], + ); +} diff --git a/lib/src/constants/extra_palettes.dart b/lib/src/look/extra_palettes.dart similarity index 73% rename from lib/src/constants/extra_palettes.dart rename to lib/src/look/extra_palettes.dart index 10674cb..2133d57 100644 --- a/lib/src/constants/extra_palettes.dart +++ b/lib/src/look/extra_palettes.dart @@ -1,14 +1,9 @@ import 'dart:ui'; -// Flutter-only palette additions — NOT transcriptions of the React source. -// The React library ships four presets (colorful, mono, ocean, sunset), which -// live verbatim in `palettes.dart`. The seven below are original to this -// package: each is a short list of source colors that `BeamColors.custom` -// distributes over the `colorful` preset's blob geometry, so every table -// (border, small, line, bloom) keeps the source library's positions, sizes -// and per-entry alpha — only the hues change. Editing a list here changes -// how the matching `BeamColors` preset looks; it does not affect parity with -// the React source. +// The table colours of the seven extra palettes. Each list is cycled over +// `colorful`'s blob tables (see `cycleColors`), so every table keeps +// `colorful`'s positions, sizes, and per-entry alpha and only the hues +// change. /// Source colors for `BeamColors.aurora` — a northern-lights sweep from /// teal through violet to green. diff --git a/lib/src/look/layer_presets.dart b/lib/src/look/layer_presets.dart new file mode 100644 index 0000000..f7f11ad --- /dev/null +++ b/lib/src/look/layer_presets.dart @@ -0,0 +1,123 @@ +import 'dart:ui'; + +import 'package:flutter/foundation.dart'; + +// How strongly each effect family paints its three layers on a dark and on a +// light surface, and the colour filter (brightness, saturation) its layers +// run through. Opacities may exceed 1 — the product with the fade and the +// palette is clamped when the frame is painted. + +/// One family's layer tuning for one surface brightness. +@immutable +class BeamLayerPreset { + /// Creates a preset. + const BeamLayerPreset({ + required this.strokeOpacity, + required this.innerOpacity, + required this.bloomOpacity, + required this.innerShadow, + required this.saturation, + this.brightness = 1.3, + }); + + /// Opacity of the hairline stroke layer. + final double strokeOpacity; + + /// Opacity of the inner glow layer. + final double innerOpacity; + + /// Opacity of the bloom layer. + final double bloomOpacity; + + /// Colour of the inner glow's inset shadow (transparent for none). + final Color innerShadow; + + /// Saturation of the layers' colour filter. + final double saturation; + + /// Brightness of the layers' colour filter. + final double brightness; +} + +/// A dark/light pair of presets. +typedef BeamLayerPresets = ({BeamLayerPreset dark, BeamLayerPreset light}); + +const Color _transparent = Color(0x00000000); + +/// The travelling beam on a compact chip. +const BeamLayerPresets compactPresets = ( + dark: BeamLayerPreset( + strokeOpacity: 0.46, + innerOpacity: 0.24, + bloomOpacity: 0.38, + innerShadow: Color.fromRGBO(255, 255, 255, 0.3), + saturation: 1.2, + ), + light: BeamLayerPreset( + strokeOpacity: 0.12, + innerOpacity: 0.3, + bloomOpacity: 0.16, + innerShadow: Color.fromRGBO(0, 0, 0, 0.14), + saturation: 1.8, + ), +); + +/// The travelling beam on a card or panel. +const BeamLayerPresets rotatePresets = ( + dark: BeamLayerPreset( + strokeOpacity: 0.26, + innerOpacity: 0.42, + bloomOpacity: 0.24, + innerShadow: Color.fromRGBO(255, 255, 255, 0.27), + saturation: 1.2, + ), + light: BeamLayerPreset( + strokeOpacity: 0.12, + innerOpacity: 0.26, + bloomOpacity: 0.34, + innerShadow: Color.fromRGBO(0, 0, 0, 0.14), + saturation: 1.5, + ), +); + +/// The edge-riding streak. +const BeamLayerPresets linePresets = ( + dark: BeamLayerPreset( + strokeOpacity: 1.14, + innerOpacity: 0.7, + bloomOpacity: 0.8, + innerShadow: Color.fromRGBO(255, 255, 255, 0.1), + saturation: 1.2, + ), + light: BeamLayerPreset( + strokeOpacity: 0.16, + innerOpacity: 0.32, + bloomOpacity: 0.3, + innerShadow: Color.fromRGBO(0, 0, 0, 0.14), + saturation: 1.95, + ), +); + +/// The inward pulse. +const BeamLayerPresets pulsePresets = ( + dark: BeamLayerPreset( + strokeOpacity: 1.54, + innerOpacity: 0.44, + bloomOpacity: 0.66, + innerShadow: _transparent, + saturation: 1.2, + brightness: 0.75, + ), + light: BeamLayerPreset( + strokeOpacity: 0.32, + innerOpacity: 0.4, + bloomOpacity: 0.8, + innerShadow: _transparent, + saturation: 0.75, + brightness: 1.3, + ), +); + +/// Picks the preset for a surface. +BeamLayerPreset presetFor(BeamLayerPresets presets, {required bool dark}) => + dark ? presets.dark : presets.light; diff --git a/lib/src/constants/line_geometry.dart b/lib/src/look/line_look.dart similarity index 63% rename from lib/src/constants/line_geometry.dart rename to lib/src/look/line_look.dart index 34b3c9e..8ed1c2d 100644 --- a/lib/src/constants/line_geometry.dart +++ b/lib/src/look/line_look.dart @@ -1,14 +1,86 @@ -// Verbatim transcription of the line variant's mask and blob geometry from -// the React library (border-beam v1.3.0, `src/styles.ts` — -// generateLineVariantCSS and getLineBloomGradients). Every length is in -// logical px in the authored coordinate space, where the beam rides the -// bottom edge of the box; every stop is a CSS gradient stop 0–1. -// -// The mask/highlight radii are multiplied at paint time by the animated -// width/height factors (`lineW`/`lineH`) and the two spike tracks, which is -// why only the base numbers live here. - -/// Radial window mask radii shared by the inner and stroke layers. +import 'package:flutter/animation.dart' show Curves; + +// The line effect's design: keyframe tables for the travelling streak, its +// radial windows, its stroke highlight, and the seven bloom spikes that rise +// from the edge. Lengths are px in a frame where the streak rides the bottom +// edge; every other edge is that frame turned about the box's centre. + +/// A single keyframe stop. +typedef BeamKeyframe = ({double t, double value}); + +/// The streak's position along the edge (a fraction of its length) through +/// one sweep. +const List lineTravelX = [ + (t: 0.0, value: 0.06), + (t: 0.1, value: 0.15), + (t: 0.2, value: 0.25), + (t: 0.3, value: 0.35), + (t: 0.4, value: 0.44), + (t: 0.5, value: 0.5), + (t: 0.6, value: 0.56), + (t: 0.7, value: 0.65), + (t: 0.8, value: 0.75), + (t: 0.9, value: 0.85), + (t: 1.0, value: 0.94), +]; + +/// The streak's width factor through one sweep (widest mid-run). +const List lineTravelW = [ + (t: 0.0, value: 0.5), + (t: 0.1, value: 0.8), + (t: 0.2, value: 1.1), + (t: 0.3, value: 1.3), + (t: 0.4, value: 1.45), + (t: 0.5, value: 1.5), + (t: 0.6, value: 1.45), + (t: 0.7, value: 1.3), + (t: 0.8, value: 1.1), + (t: 0.9, value: 0.8), + (t: 1.0, value: 0.5), +]; + +/// The streak's opacity through one sweep: it fades out near the ends. +const List lineEdgeFade = [ + (t: 0.0, value: 0), + (t: 0.125, value: 0), + (t: 0.325, value: 1), + (t: 0.675, value: 1), + (t: 0.875, value: 0), + (t: 1.0, value: 0), +]; + +/// The streak's height factor (period = cycle × [lineBreathePeriod], eased +/// per segment). +const List lineBreatheH = [ + (t: 0.0, value: 0.8), + (t: 0.25, value: 1.25), + (t: 0.55, value: 0.85), + (t: 0.8, value: 1.3), + (t: 1.0, value: 0.8), +]; + +/// The first spike scale (period = cycle × [lineSpikePeriod], eased per +/// segment). +const List lineSpike = [ + (t: 0.0, value: 0.8), + (t: 0.25, value: 1.3), + (t: 0.5, value: 0.9), + (t: 0.75, value: 1.4), + (t: 1.0, value: 0.8), +]; + +/// The second spike scale (period = cycle × [lineSpike2Period], eased per +/// segment). +const List lineSpike2 = [ + (t: 0.0, value: 1.2), + (t: 0.25, value: 0.7), + (t: 0.5, value: 1.4), + (t: 0.75, value: 0.8), + (t: 1.0, value: 1.2), +]; + +/// Horizontal radius of the radial window shared by the inner and stroke +/// layers. const double lineWindowRadiusX = 78; /// Vertical radius of [lineWindowRadiusX]'s window. @@ -35,11 +107,11 @@ const double lineBloomWindowMidAlpha = 0.5; /// Inner shadow blur of the line variant's inner layer. const double lineInnerShadowBlur = 9; -/// Bloom blur sigma while the hue animation runs (CSS `blur(8px)`). -const double lineBloomBlurSigma = 8; +/// Blur of the bloom layer, in px. +const double lineBloomBlur = 8; -/// Bloom blur sigma for the mono palette (CSS `blur(6px)`). -const double lineBloomBlurSigmaMono = 6; +/// Blur of the bloom layer for the mono palette, in px. +const double lineBloomBlurMono = 6; // ─── Traveling highlight ──────────────────────────────────────────────────── @@ -72,9 +144,9 @@ const List lineHighlightStopsLight = [0, 0.35, 0.70]; // ─── Bloom spikes ─────────────────────────────────────────────────────────── -/// One bloom spike's fixed geometry: [fx] is its position along the edge as -/// a fraction of the width, [yInset] how far above the edge it is centred, -/// and [midStop]/[endStop] its two gradient stops. +/// One bloom spike's fixed geometry: `fx` is its position along the edge as +/// a fraction of the width, `yInset` how far above the edge it is centred, +/// and `midStop`/`endStop` its two gradient stops. typedef LineSpikeGeometry = ({ double fx, double yInset, @@ -208,3 +280,40 @@ const List lineShadowAlphas = [0.5, 0.18, 0.03, 0.0]; /// Stops of the traveling shadow blob. const List lineShadowStops = [0, 0.30, 0.60, 0.85]; + +/// The streak height track's period, in cycles. +const double lineBreathePeriod = 1.3; + +/// The first spike track's period, in cycles. +const double lineSpikePeriod = 1.33; + +/// The second spike track's period, in cycles. +const double lineSpike2Period = 1.7; + +/// How much wider the bloom's hue swing runs than the stroke's, in degrees. +const double lineBloomHueBonus = 10; + +/// The widest hue swing the line takes, in degrees. +const double lineHueCap = 13; + +/// Samples a keyframe table at cycle progress [t] (0–1), linearly or eased +/// within each segment. +double sampleKeyframes( + List frames, + double t, { + bool eased = false, +}) { + final clamped = t.clamp(0.0, 1.0); + for (var i = 1; i < frames.length; i++) { + final prev = frames[i - 1]; + final next = frames[i]; + if (clamped <= next.t) { + final span = next.t - prev.t; + if (span <= 0) return next.value; + var local = (clamped - prev.t) / span; + if (eased) local = Curves.easeInOut.transform(local); + return prev.value + (next.value - prev.value) * local; + } + } + return frames.last.value; +} diff --git a/lib/src/look/look_blobs.dart b/lib/src/look/look_blobs.dart new file mode 100644 index 0000000..e2b3947 --- /dev/null +++ b/lib/src/look/look_blobs.dart @@ -0,0 +1,202 @@ +import 'dart:ui'; + +import 'package:flutter/foundation.dart'; + +// The building blocks of the beam's look: soft radial colour blobs placed +// around the border, and the tables that place them. + +/// One radial colour blob placed around the border. +/// +/// An ellipse of [size] radii in logical px, centred at [position] — a +/// fraction of the decorated box, so `Offset(0.33, -0.074)` sits a third of +/// the way along the top edge, just above it — fading from [color] at the +/// centre to transparent at the rim. +@immutable +class BeamBlob { + /// Creates a blob. + const BeamBlob({ + required this.color, + required this.position, + required this.size, + }); + + /// The colour at the centre. May carry alpha. + final Color color; + + /// Centre as a fraction of the box (values outside 0–1 are valid). + final Offset position; + + /// Ellipse radii in logical px: horizontal, vertical. + final Size size; + + /// A copy with a different [color], keeping the geometry. + BeamBlob withColor(Color color) => + BeamBlob(color: color, position: position, size: size); + + @override + bool operator ==(Object other) => + identical(this, other) || + other is BeamBlob && + other.color == color && + other.position == position && + other.size == size; + + @override + int get hashCode => Object.hash(color, position, size); + + @override + String toString() => 'BeamBlob($color, $position, $size)'; +} + +/// A blob of the line effect. Line blobs ride the edge with the travelling +/// streak: they sit [offsetX] px along the edge from the streak's centre and +/// [offsetY] px off the edge, and their radii scale with the streak's +/// animated width and height. +@immutable +class LineBlob { + /// Creates a line blob. + const LineBlob({ + required this.color, + required this.sizeW, + required this.sizeH, + required this.offsetX, + required this.offsetY, + }); + + /// Blob colour (may carry alpha). + final Color color; + + /// Base radius along the edge, in px. + final double sizeW; + + /// Base radius across the edge, in px. + final double sizeH; + + /// Offset along the edge from the streak centre, in px. + final double offsetX; + + /// Offset off the edge, in px (positive = outward). + final double offsetY; + + /// A copy with a different [color], keeping the geometry. + LineBlob withColor(Color color) => LineBlob( + color: color, + sizeW: sizeW, + sizeH: sizeH, + offsetX: offsetX, + offsetY: offsetY, + ); + + @override + bool operator ==(Object other) => + identical(this, other) || + other is LineBlob && + other.color == color && + other.sizeW == sizeW && + other.sizeH == sizeH && + other.offsetX == offsetX && + other.offsetY == offsetY; + + @override + int get hashCode => Object.hash(color, sizeW, sizeH, offsetX, offsetY); + + @override + String toString() => + 'LineBlob($color, ${sizeW}x$sizeH, offset $offsetX, $offsetY)'; +} + +/// The two colours of one fixed bloom spike of the line effect: at its +/// centre and at its mid stop. +@immutable +class SpikePair { + /// Creates a spike colour pair. + const SpikePair(this.color1, this.color2); + + /// Colour at the spike centre. + final Color color1; + + /// Colour at the spike's mid stop. + final Color color2; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is SpikePair && other.color1 == color1 && other.color2 == color2; + + @override + int get hashCode => Object.hash(color1, color2); + + @override + String toString() => 'SpikePair($color1, $color2)'; +} + +/// The line effect's two leading spike colours. +@immutable +class SpikeColors { + /// Creates the spike colours. + const SpikeColors({required this.primary, required this.secondary}); + + /// The dominant spike colour. + final Color primary; + + /// The secondary spike colour. + final Color secondary; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is SpikeColors && + other.primary == primary && + other.secondary == secondary; + + @override + int get hashCode => Object.hash(primary, secondary); + + @override + String toString() => 'SpikeColors($primary, $secondary)'; +} + +/// Which size/drift oscillator group (1–3) breathes a pulse blob, so +/// neighbouring blobs never breathe in lockstep. +enum PulseRegion { + /// Group 1. + r1, + + /// Group 2. + r2, + + /// Group 3. + r3, +} + +/// Which corner's opacity oscillator modulates a pulse blob's alpha. +enum PulseQuad { + /// Top-left. + tl, + + /// Top-right. + tr, + + /// Bottom-left. + bl, + + /// Bottom-right. + br, +} + +/// A pulse bloom entry: the colour and position of border blob [ci], drawn +/// with its own ellipse radii [w] × [h]. +@immutable +class PulseBlobSpec { + /// Creates a pulse bloom entry. + const PulseBlobSpec({required this.ci, required this.w, required this.h}); + + /// Index of the colour in the 9-blob border table. + final int ci; + + /// Horizontal radius in px. + final double w; + + /// Vertical radius in px. + final double h; +} diff --git a/lib/src/constants/palettes.dart b/lib/src/look/palette_tables.dart similarity index 96% rename from lib/src/constants/palettes.dart rename to lib/src/look/palette_tables.dart index c8e4857..ab79890 100644 --- a/lib/src/constants/palettes.dart +++ b/lib/src/look/palette_tables.dart @@ -2,18 +2,19 @@ import 'dart:ui'; import 'package:flutter/foundation.dart'; -import '../models/beam_blob.dart'; +import 'look_blobs.dart'; -// Verbatim transcription of the color palette tables from the React library -// (border-beam v1.3.0, src/styles.ts): `colorPalettes`, `smallColorPalettes`, -// `lineColorPalettes`, `lineInnerGradientData`, `lineBloomColors`. -// CSS `pos: '33% -7.4%'` becomes `Offset(0.33, -0.074)`; -// `size: '70px 40px'` becomes `Size(70, 40)`. Do not tweak values. +// The blob tables of the four original palettes — the hand-tuned heart of +// the beam's look. Every effect draws its colour from these: the rotate +// stroke and inner glow, the compact chip tables, the line streak and its +// spikes, and the pulse's glows. Positions are fractions of the box +// (`Offset(0.33, -0.074)` sits a third along the top edge, just above it); +// sizes are ellipse radii in px. -/// The complete gradient-table bundle for one color preset. -class BeamPresetData { +/// Every blob table one palette is drawn with. +class BeamLookTables { /// Creates a preset bundle. - const BeamPresetData({ + const BeamLookTables({ required this.border, required this.spike, required this.spikeLt, @@ -56,14 +57,12 @@ class BeamPresetData { /// 5 fixed bloom spike color pairs, light theme. final List lineBloomLight; - // Structural equality: derived bundles (custom/seed/lerp palettes) are - // built fresh on every resolve, so two bundles carrying the same tables - // must compare equal for `BeamConfig` — and therefore - // `BeamPainter.shouldRepaint` — to see them as the same paint. + // Structural equality: derived tables are built once per palette, and two + // built from equal palettes must compare equal. @override bool operator ==(Object other) => identical(this, other) || - other is BeamPresetData && + other is BeamLookTables && listEquals(other.border, border) && other.spike == spike && other.spikeLt == spikeLt && @@ -92,8 +91,8 @@ class BeamPresetData { // ── colorful ──────────────────────────────────────────────────────────────── -/// Rainbow preset (React `colorful`). The default. -const BeamPresetData colorfulPreset = BeamPresetData( +/// `BeamColors.colorful` — the full spectrum. The default. +const BeamLookTables colorfulTables = BeamLookTables( border: [ BeamBlob( color: Color.fromRGBO(255, 50, 100, 1), @@ -464,9 +463,9 @@ const BeamPresetData colorfulPreset = BeamPresetData( // ── mono ──────────────────────────────────────────────────────────────────── -/// Grayscale preset (React `mono`). Forces static colors and halves layer -/// opacity at paint time. -const BeamPresetData monoPreset = BeamPresetData( +/// `BeamColors.mono` — whites and greys. Holds its hue and halves the layer +/// opacities (the line effect softens its spikes instead). +const BeamLookTables monoTables = BeamLookTables( border: [ BeamBlob( color: Color.fromRGBO(180, 180, 180, 1), @@ -837,8 +836,8 @@ const BeamPresetData monoPreset = BeamPresetData( // ── ocean ─────────────────────────────────────────────────────────────────── -/// Blue/purple preset (React `ocean`). -const BeamPresetData oceanPreset = BeamPresetData( +/// `BeamColors.ocean` — blues and violets. +const BeamLookTables oceanTables = BeamLookTables( border: [ BeamBlob( color: Color.fromRGBO(100, 80, 220, 1), @@ -1206,8 +1205,8 @@ const BeamPresetData oceanPreset = BeamPresetData( // ── sunset ────────────────────────────────────────────────────────────────── -/// Warm orange/red preset (React `sunset`). -const BeamPresetData sunsetPreset = BeamPresetData( +/// `BeamColors.sunset` — reds, oranges, and amber. +const BeamLookTables sunsetTables = BeamLookTables( border: [ BeamBlob( color: Color.fromRGBO(255, 80, 50, 1), diff --git a/lib/src/look/pulse_look.dart b/lib/src/look/pulse_look.dart new file mode 100644 index 0000000..2430495 --- /dev/null +++ b/lib/src/look/pulse_look.dart @@ -0,0 +1,244 @@ +import 'dart:math' as math; + +import 'package:flutter/animation.dart' show Curves; + +// The pulse's breathing: tuned parameters per surface, the 17 +// oscillators they drive, and the geometry constants of its inner glow and +// bloom. + +/// Breathing parameters for one effect and surface, scaled to a cycle. +class PulseParams { + const PulseParams._({ + required this.sp, + required this.dr, + required this.op, + required this.gh, + required this.bs, + required this.ss, + required this.ghs, + }); + + /// The inward pulse's parameters on a [dark] or light surface, for a cycle + /// of [cycleSeconds] (the tuning is authored at 2.3s). + factory PulseParams.pulse({ + required bool dark, + required double cycleSeconds, + }) { + final k = cycleSeconds / 2.3; + return PulseParams._( + sp: 0.28, + dr: dark ? 33 : 40, + op: dark ? 0.48 : 0.45, + gh: dark ? 0.34 : 0.22, + bs: (dark ? 1.9 : 2.6) * k, + ss: (dark ? 2.6 : 4.6) * k, + ghs: (dark ? 2.4 : 5.5) * k, + ); + } + + /// Blob size breathing amplitude (fraction). + final double sp; + + /// Blob drift amplitude in px. + final double dr; + + /// Corner opacity breathing depth (0 holds the corners steady). + final double op; + + /// Global height breathing amplitude (fraction). + final double gh; + + /// Base period of the drift and opacity oscillators, seconds. + final double bs; + + /// Base period of the size oscillators, seconds. + final double ss; + + /// Period of the global height oscillator, seconds. + final double ghs; + + /// The alpha the static bloom blobs hold: the time average of the corner + /// breathing. + double get frozenBloomAlpha => 1 - op * 0.5; +} + +/// The cosine ping-pong: 0 at whole phases, 1 at half phases. +double pingPong(double phase) => (1 - math.cos(2 * math.pi * phase)) / 2; + +/// The share of a breath spent swelling; the rest is the slower fade back. +const double breathRise = 0.4; + +/// A breath at [phase] (in cycles): 0 at the start of each cycle, swelling to +/// 1 over the first [breathRise] of it and fading back over the rest, both on +/// Apple's ease-in-out — so light arrives with intent and leaves gently. +double breath(double phase) { + final p = phase - phase.floorToDouble(); + if (p < breathRise) return Curves.easeInOut.transform(p / breathRise); + return 1 - Curves.easeInOut.transform((p - breathRise) / (1 - breathRise)); +} + +/// One oscillator: ping-pongs from [a] to [b] and back over [period] +/// seconds, delayed by [delay]. +class PulseOscillator { + /// Creates an oscillator. + const PulseOscillator({ + required this.a, + required this.b, + required this.period, + this.delay = 0, + this.breathes = false, + }); + + /// Value at phase 0. + final double a; + + /// Value at the swing's far end: half a period in, or [breathRise] of one + /// when it [breathes]. + final double b; + + /// Full period, seconds. + final double period; + + /// Phase delay, seconds. + final double delay; + + /// Whether it swings on a [breath] — a quicker swell and a slower fade — + /// rather than the even [pingPong]. + final bool breathes; + + /// The value at [t] seconds. + double sample(double t) { + final phase = (t - delay) / period; + return a + (b - a) * (breathes ? breath(phase) : pingPong(phase)); + } +} + +/// One frame of breathing: the three blob size/drift groups, the global +/// height factor, and the four corner opacities. +class PulseFrame { + /// A frame at rest. + PulseFrame(); + + /// Width factors of groups 1–3. + final List bw = [1, 1, 1]; + + /// Height factors of groups 1–3. + final List bh = [1, 1, 1]; + + /// Horizontal drift of groups 1–3, px. + final List bx = [0, 0, 0]; + + /// Vertical drift of groups 1–3, px. + final List by = [0, 0, 0]; + + /// Global height factor. + double bgh = 1; + + /// Corner opacities: top-left, top-right, bottom-left, bottom-right. + final List bop = [1, 1, 1, 1]; +} + +/// The 17 oscillators of one breathing tuning. +class PulseOscillatorBank { + /// Builds the bank for [p]. + PulseOscillatorBank(PulseParams p) + : params = p, + _bw = [ + PulseOscillator(a: 1 - p.sp, b: 1 + p.sp * 1.1, period: p.ss * 0.9), + PulseOscillator(a: 1 + p.sp, b: 1 - p.sp * 0.85, period: p.ss * 1.1), + PulseOscillator( + a: 1 - p.sp * 0.6, + b: 1 + p.sp * 1.15, + period: p.ss * 0.98, + ), + ], + _bh = [ + PulseOscillator( + a: 1 + p.sp * 0.9, + b: 1 - p.sp * 0.85, + period: p.ss * 1.26, + ), + PulseOscillator( + a: 1 - p.sp * 0.8, + b: 1 + p.sp * 1.05, + period: p.ss * 0.81, + ), + PulseOscillator(a: 1 + p.sp * 0.75, b: 1 - p.sp, period: p.ss * 1.4), + ], + _bx = [ + PulseOscillator(a: -p.dr, b: p.dr * 0.9, period: p.bs * 1.6), + PulseOscillator(a: p.dr * 0.8, b: -p.dr * 0.9, period: p.bs * 1.88), + PulseOscillator(a: -p.dr * 0.6, b: p.dr, period: p.bs * 1.45), + ], + _by = [ + PulseOscillator(a: p.dr * 0.55, b: -p.dr * 0.7, period: p.bs * 1.6), + PulseOscillator(a: -p.dr, b: p.dr * 0.65, period: p.bs * 1.88), + PulseOscillator(a: -p.dr * 0.85, b: p.dr * 0.45, period: p.bs * 1.45), + ], + _bgh = PulseOscillator(a: 1 - p.gh, b: 1 + p.gh, period: p.ghs), + _bop = [ + PulseOscillator(a: 1 - p.op, b: 1, period: p.bs, breathes: true), + PulseOscillator( + a: 1 - p.op, + b: 1, + period: p.bs * 1.32, + delay: p.bs * 0.28, + breathes: true, + ), + PulseOscillator( + a: 1 - p.op, + b: 1, + period: p.bs * 0.84, + delay: p.bs * 0.55, + breathes: true, + ), + PulseOscillator( + a: 1 - p.op, + b: 1, + period: p.bs * 1.58, + delay: p.bs * 0.83, + breathes: true, + ), + ]; + + /// The tuning the bank was built for. + final PulseParams params; + + final List _bw; + final List _bh; + final List _bx; + final List _by; + final PulseOscillator _bgh; + final List _bop; + + /// Samples every oscillator at [t] seconds into [out]. + void sample(double t, PulseFrame out) { + for (var i = 0; i < 3; i++) { + out.bw[i] = _bw[i].sample(t); + out.bh[i] = _bh[i].sample(t); + out.bx[i] = _bx[i].sample(t); + out.by[i] = _by[i].sample(t); + } + out.bgh = _bgh.sample(t); + for (var i = 0; i < 4; i++) { + out.bop[i] = _bop[i].sample(t); + } + } +} + +// ─── The inward pulse ────────────────────────────────────────────────────── + +/// Radius of the corner accents of the pulse's inner glow, px. +const double pulseCornerRadius = 60; + +/// Alpha of a corner accent on a dark surface. +const double pulseCornerAlphaDark = 0.18; + +/// Alpha of a corner accent on a light surface. +const double pulseCornerAlphaLight = 0.08; + +/// Where a corner accent has faded out (a fraction of its radius). +const double pulseCornerEndStop = 0.70; + +/// Blur of the pulse's bloom, px. +const double pulseBloomBlur = 8; diff --git a/lib/src/look/pulse_tables.dart b/lib/src/look/pulse_tables.dart new file mode 100644 index 0000000..28fc485 --- /dev/null +++ b/lib/src/look/pulse_tables.dart @@ -0,0 +1,49 @@ +import 'dart:ui'; + +import 'look_blobs.dart'; + +// The pulse's blob tables. Their colours come from a palette's +// 9-blob border table (by index); the geometry here — sizes, and which +// oscillators breathe each blob — is the same for every palette. + +/// Region/quad assignment for each of the 9 palette border blobs when used as +/// the pulse perimeter ring. +const List<({PulseRegion region, PulseQuad quad})> pulseRingMap = [ + (region: PulseRegion.r1, quad: PulseQuad.tl), + (region: PulseRegion.r2, quad: PulseQuad.tl), + (region: PulseRegion.r3, quad: PulseQuad.bl), + (region: PulseRegion.r1, quad: PulseQuad.bl), + (region: PulseRegion.r2, quad: PulseQuad.br), + (region: PulseRegion.r3, quad: PulseQuad.br), + (region: PulseRegion.r1, quad: PulseQuad.tr), + (region: PulseRegion.r2, quad: PulseQuad.tr), + (region: PulseRegion.r3, quad: PulseQuad.tr), +]; + +/// The pulse inner glow's radii for each of the 9 border blobs. +const List pulseInnerSizes = [ + Size(65, 35), + Size(55, 30), + Size(35, 65), + Size(15, 30), + Size(173, 28), + Size(80, 22), + Size(69, 28), + Size(22, 38), + Size(47, 44), +]; + +/// The pulse bloom: 7 of the 9 border colours, larger, at the border blobs' +/// own positions. +/// +/// The bloom holds still: every blob sits at the breathing's average alpha +/// (`PulseParams.frozenBloomAlpha`). +const List pulseInnerBloom = [ + PulseBlobSpec(ci: 0, w: 84, h: 48), + PulseBlobSpec(ci: 1, w: 72, h: 42), + PulseBlobSpec(ci: 2, w: 48, h: 84), + PulseBlobSpec(ci: 4, w: 216, h: 38), + PulseBlobSpec(ci: 5, w: 102, h: 31), + PulseBlobSpec(ci: 6, w: 89, h: 38), + PulseBlobSpec(ci: 8, w: 62, h: 58), +]; diff --git a/lib/src/look/rotate_look.dart b/lib/src/look/rotate_look.dart new file mode 100644 index 0000000..2888db9 --- /dev/null +++ b/lib/src/look/rotate_look.dart @@ -0,0 +1,89 @@ +// The travelling beam's conic tables: each a list of stop positions around +// the turn (0–1, clockwise from the beam's start angle) and the alpha at each +// stop. The bright core is followed by a short falloff on the leading side and +// a long soft foot trailing behind, which is what makes the beam read as a +// head dragging a tail. + +/// The rotating soft window that reveals the stroke and inner glow. +const List rotateWindowStops = [ + 0.0, 0.30, 0.36, 0.44, 0.52, 0.80, 0.86, 0.92, 0.95, 1.0, // +]; + +/// Alphas of [rotateWindowStops]. +const List rotateWindowAlphas = [ + 0.0, 0.0, 0.1, 0.35, 1.0, 1.0, 0.35, 0.1, 0.0, 0.0, // +]; + +/// The wider window a compact chip's inner glow uses. +const List compactWindowStops = [ + 0.0, 0.22, 0.28, 0.36, 0.46, 0.82, 0.88, 0.94, 0.97, 1.0, // +]; + +/// Alphas of [compactWindowStops]. +const List compactWindowAlphas = [ + 0.0, 0.0, 0.12, 0.4, 1.0, 1.0, 0.4, 0.12, 0.0, 0.0, // +]; + +/// The highlight at the head of the stroke — white on a dark surface, black +/// on a light one. +const List rotateHighlightStops = [ + 0.0, 0.54, 0.57, 0.60, 0.63, 0.66, 0.69, 0.72, 0.75, 0.78, 1.0, // +]; + +/// Dark-surface alphas of [rotateHighlightStops]. +const List rotateHighlightAlphasDark = [ + 0.0, 0.0, 0.1, 0.3, 0.6, 0.75, 0.6, 0.3, 0.1, 0.0, 0.0, // +]; + +/// Light-surface alphas of [rotateHighlightStops]. +const List rotateHighlightAlphasLight = [ + 0.0, 0.0, 0.08, 0.2, 0.4, 0.55, 0.4, 0.2, 0.08, 0.0, 0.0, // +]; + +/// The narrow band of the bloom, which is blurred into a soft glow. +const List rotateBloomStops = [ + 0.0, 0.58, 0.62, 0.65, 0.67, 0.69, 0.70, 0.705, 0.715, 0.73, 0.75, 0.78, + 0.82, 1.0, // +]; + +/// Dark-surface alphas of [rotateBloomStops]. +const List rotateBloomAlphasDark = [ + 0.0, 0.0, 0.03, 0.08, 0.2, 0.45, 0.85, 0.85, 0.45, 0.2, 0.08, 0.03, 0.0, + 0.0, // +]; + +/// Light-surface alphas of [rotateBloomStops]. +const List rotateBloomAlphasLight = [ + 0.0, 0.0, 0.02, 0.08, 0.2, 0.4, 0.6, 0.6, 0.4, 0.2, 0.08, 0.02, 0.0, 0.0, // +]; + +/// Where the beam's head sits in the tables: the bloom's peak. +const double rotateHeadStop = 0.7025; + +/// Blur of the bloom band, in px. +const double rotateBloomBlur = 8; + +/// The inner glow's inset shadow blur on a card, in px. +const double rotateInnerShadowBlur = 9; + +/// The inner glow's inset shadow blur on a compact chip, in px. +const double compactInnerShadowBlur = 5; + +/// How far in from the edge the inner glow fades out, in px. +const double innerEdgeFade = 28; + +/// The alpha of the inner glow's blobs, derived from the border table. +const double rotateInnerBlobAlpha = 0.45; + +/// [rotateInnerBlobAlpha] for the mono palette. +const double rotateInnerBlobAlphaMono = 0.225; + +/// The size of the inner glow's blobs relative to the border table's. +const double rotateInnerBlobScale = 0.9; + +/// How far past the border a comet's glow reaches, in px. +const double cometReach = 12; + +/// The shortest side at or below which a box is drawn with the compact +/// chip tables. +const double compactMaxExtent = 56; diff --git a/lib/src/models/beam_blob.dart b/lib/src/models/beam_blob.dart deleted file mode 100644 index b874c59..0000000 --- a/lib/src/models/beam_blob.dart +++ /dev/null @@ -1,240 +0,0 @@ -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; - -/// One radial-gradient color blob positioned around the border. -/// -/// This is the core building block of every beam palette: an ellipse of -/// [size] radii in logical pixels, centered at [position] (expressed as a -/// fraction of the decorated box, so `Offset(0.33, -0.074)` is the CSS -/// position `33% -7.4%`), fading from [color] at the center to transparent -/// at the edge. -@immutable -class BeamBlob { - /// Creates a blob. [position] is fractional (may exceed 0–1 to sit on or - /// beyond the edge); [size] holds the ellipse radii in logical pixels. - const BeamBlob({ - required this.color, - required this.position, - required this.size, - }); - - /// The blob color at the ellipse center. May carry alpha. - final Color color; - - /// Center of the ellipse as a fraction of the painted rect - /// (0,0 = top-left, 1,1 = bottom-right; values outside 0–1 are valid). - final Offset position; - - /// Ellipse radii in logical pixels: [Size.width] is the horizontal radius - /// and [Size.height] the vertical one, matching CSS - /// `radial-gradient(ellipse W H ...)`, whose sizes are radii. Painters - /// pass these straight through as `radiusX`/`radiusY`. - final Size size; - - /// Returns a copy with a different [color], keeping the geometry. - BeamBlob withColor(Color color) => - BeamBlob(color: color, position: position, size: size); - - @override - bool operator ==(Object other) => - identical(this, other) || - other is BeamBlob && - other.color == color && - other.position == position && - other.size == size; - - @override - int get hashCode => Object.hash(color, position, size); - - @override - String toString() => - 'BeamBlob(color: $color, position: $position, ' - 'size: $size)'; -} - -/// A blob used by the line variant. Line blobs ride the bottom edge: their -/// x-position is `beamX + offsetX` px and their y sits at the bottom edge -/// shifted by [offsetY] px, with the ellipse scaled by the animated -/// width/height factors. -@immutable -class LineBlob { - /// Creates a line blob with base ellipse radii and pixel offsets from the - /// traveling beam center. - const LineBlob({ - required this.color, - required this.sizeW, - required this.sizeH, - required this.offsetX, - required this.offsetY, - }); - - /// Blob color (may carry alpha for inner-glow tables). - final Color color; - - /// Base horizontal ellipse radius in px, multiplied by the animated beam - /// width factor and passed to the painter as `radiusX`. - final double sizeW; - - /// Base vertical ellipse radius in px, multiplied by the animated beam - /// height factor and passed to the painter as `radiusY`. - final double sizeH; - - /// Horizontal offset in px from the traveling beam center. - final double offsetX; - - /// Vertical offset in px from the bottom edge (positive = below). - final double offsetY; - - /// Returns a copy with a different [color], keeping the geometry. - LineBlob withColor(Color color) => LineBlob( - color: color, - sizeW: sizeW, - sizeH: sizeH, - offsetX: offsetX, - offsetY: offsetY, - ); - - @override - bool operator ==(Object other) => - identical(this, other) || - other is LineBlob && - other.color == color && - other.sizeW == sizeW && - other.sizeH == sizeH && - other.offsetX == offsetX && - other.offsetY == offsetY; - - @override - int get hashCode => Object.hash(color, sizeW, sizeH, offsetX, offsetY); - - @override - String toString() => - 'LineBlob(color: $color, size: ${sizeW}x$sizeH, ' - 'offset: $offsetX, $offsetY)'; -} - -/// A pair of colors used by one fixed bloom spike of the line variant -/// (center color and mid-stop color). -@immutable -class SpikePair { - /// Creates a spike color pair. - const SpikePair(this.color1, this.color2); - - /// Color at the spike center. - final Color color1; - - /// Color at the spike's mid gradient stop. - final Color color2; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is SpikePair && other.color1 == color1 && other.color2 == color2; - - @override - int get hashCode => Object.hash(color1, color2); - - @override - String toString() => 'SpikePair($color1, $color2)'; -} - -/// Primary/secondary spike colors used by the line variant's traveling -/// accents. -@immutable -class SpikeColors { - /// Creates the spike color pair. - const SpikeColors({required this.primary, required this.secondary}); - - /// The dominant spike color. - final Color primary; - - /// The secondary spike color. - final Color secondary; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is SpikeColors && - other.primary == primary && - other.secondary == secondary; - - @override - int get hashCode => Object.hash(primary, secondary); - - @override - String toString() => - 'SpikeColors(primary: $primary, ' - 'secondary: $secondary)'; -} - -/// Which oscillator group (1–3) scales/drifts a pulse blob. -/// -/// The pulse engine runs three independent size/drift oscillator groups so -/// neighboring blobs never breathe in lockstep. -enum PulseRegion { - /// Oscillator group 1 (`--bw1/--bh1/--bx1/--by1`). - r1, - - /// Oscillator group 2. - r2, - - /// Oscillator group 3. - r3, -} - -/// Which corner opacity oscillator (`--bop-*`) modulates a pulse blob's -/// alpha. -enum PulseQuad { - /// Top-left corner group. - tl, - - /// Top-right corner group. - tr, - - /// Bottom-left corner group. - bl, - - /// Bottom-right corner group. - br, -} - -/// A pulse-table entry: references a palette blob by index [ci] and assigns -/// it an oscillator [region], a [quad] opacity group, an override ellipse -/// size, and (for the outer tables) an explicit fractional position. -class PulseBlobSpec { - /// Creates a pulse blob spec. [x]/[y] are fractional positions; when null - /// the referenced palette blob's own position is used. - const PulseBlobSpec({ - required this.ci, - required this.region, - required this.quad, - required this.w, - required this.h, - this.x, - this.y, - }); - - /// Index of the color in the palette's 9-blob border table. - final int ci; - - /// Size/drift oscillator group. - final PulseRegion region; - - /// Corner opacity oscillator group. - final PulseQuad quad; - - /// Base ellipse width in px. - final double w; - - /// Base ellipse height in px. - final double h; - - /// Fractional x position override (e.g. 1.01 = CSS `101%`), or null to use - /// the palette blob's position. - final double? x; - - /// Fractional y position override, or null to use the palette blob's - /// position. - final double? y; -} diff --git a/lib/src/models/beam_colors.dart b/lib/src/models/beam_colors.dart index 717aba8..6b0f8b6 100644 --- a/lib/src/models/beam_colors.dart +++ b/lib/src/models/beam_colors.dart @@ -2,13 +2,14 @@ import 'dart:collection'; import 'dart:ui'; import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart' show ColorScheme; import 'package:flutter/painting.dart' show HSLColor; +// `BeamColors.fromScheme` takes a Material `ColorScheme`. +import 'package:material_ui/material_ui.dart' show ColorScheme; -import '../constants/extra_palettes.dart'; -import '../constants/palettes.dart'; -import 'beam_blob.dart'; +import '../look/beam_look.dart'; +import '../render/color_math.dart'; import 'beam_palette.dart'; +import 'beam_presets.dart'; import 'model_validation.dart'; /// How [BeamColors.fromSeed] spreads one brand color into a multi-color @@ -16,141 +17,84 @@ import 'model_validation.dart'; /// /// Every harmony works in HSL and keeps the derived colors inside the /// lightness band a glow reads well in, so a very dark or very light seed -/// still produces visible beams. +/// still produces a visible beam. enum BeamSeedHarmony { /// Four neighbours of the seed hue (0°, +25°, −25°, +50°). The calmest /// option: the palette still reads as one color. analogous, /// Four colors split across the seed hue and its opposite (0°, +15°, - /// +180°, +195°) — maximum contrast between the two halves of the beam. + /// +180°, +195°) — maximum contrast between the two halves of the border. complementary, /// Three colors evenly spaced around the wheel (0°, +120°, +240°). triadic, /// Four tints of the seed hue, stepping through the lightness band with - /// falling saturation. Keeps a single-hue brand look. + /// saturation falling toward the floor. Keeps a single-hue brand look. monochrome, } -/// The color scheme of a beam. +/// The colors of a beam: a ring of color stops around the border. /// -/// Use one of the presets: +/// Stops sit at perimeter positions in `[0, 1)` — 0 at top-centre, +/// increasing clockwise — and blend into each other, the last back into the +/// first, so the ring is seamless. Effects that travel reveal the colors +/// where the beam passes; ambient effects breathe them in place. +/// +/// Use one of the [presets]: /// /// ```dart -/// BorderBeam.rotate(colors: BeamColors.ocean, child: card) +/// BorderBeam(colors: BeamColors.ocean, child: card) /// ``` /// -/// or bring your own colors — [BeamColors.custom] distributes them over a -/// preset's blob geometry so the effect keeps its organic look: +/// or bring your own colors, evenly spaced or at chosen positions: /// /// ```dart -/// BorderBeam.rotate( -/// colors: BeamColors.custom([Colors.pink, Colors.cyan, Colors.amber]), +/// BorderBeam( +/// colors: const BeamColors([Colors.pink, Colors.cyan, Colors.amber]), /// child: card, /// ) /// ``` /// /// [BeamColors.fromSeed] and [BeamColors.fromScheme] derive a palette from a /// single brand color or a Material [ColorScheme]; [BeamColors.lerp] and -/// [scaleAlpha] transform an existing one. For pixel-level control, -/// [BeamColors.spec] accepts explicit blob tables. +/// [scaleAlpha] transform an existing one. /// /// Every variant is a value type: two instances built from equal inputs are -/// `==`, so rebuilding `BeamColors.custom([...])` inline in a `build` method -/// does not force the widget to re-resolve its gradient tables. +/// `==`, so rebuilding `BeamColors([...])` inline in a `build` method does not +/// force the beam to re-resolve its palette. @immutable sealed class BeamColors { const BeamColors._(); - /// Immutable value used by the resolved-palette LRU. - Object get _cacheKey; - - /// Rainbow spectrum. The default. - static const BeamColors colorful = _PresetBeamColors(colorfulPreset); - - /// Grayscale. Hue animation is disabled and layer opacity halved, matching - /// the source library's mono treatment. - static const BeamColors mono = _PresetBeamColors(monoPreset, isMono: true); - - /// Blue and purple tones. - static const BeamColors ocean = _PresetBeamColors(oceanPreset); - - /// Warm orange, yellow, and red tones. - static const BeamColors sunset = _PresetBeamColors(sunsetPreset); - - // ─── Flutter-only presets ───────────────────────────────────────────────── - // Each distributes a short color list (`extra_palettes.dart`) over the - // `colorful` blob geometry, exactly as `BeamColors.custom` does. - - /// Northern lights: teal, violet, green and glacier blue. - static const BeamColors aurora = _CustomBeamColors(auroraColors); - - /// Fully saturated magenta, cyan and lime — the loudest preset. - static const BeamColors neon = _CustomBeamColors(neonColors); - - /// Pastel pink, lavender and peach. - static const BeamColors candy = _CustomBeamColors(candyColors); - - /// Deep red, orange and gold — the hot end of a fire. - static const BeamColors ember = _CustomBeamColors(emberColors); - - /// Pale blue, white and cyan. - static const BeamColors ice = _CustomBeamColors(iceColors); + // ─── Factories ──────────────────────────────────────────────────────────── - /// Warm monochrome: amber, gold and bronze. + /// A ring of [colors] at [stops]. /// - /// Like [mono] it pins the hue — a hue sweep over a single-hue metal reads - /// as the metal changing material — so `gold` resolves with - /// `forcesStaticColors: true`. Unlike [mono] it keeps full layer opacity: - /// the ×0.5 multiplier exists to stop a *grayscale* beam blowing out, and - /// halving a warm amber only makes it muddy. - static const BeamColors gold = _CustomBeamColors(goldColors, staticHue: true); - - /// Desaturated pastels built for a hue sweep. + /// Give 1–8 colors. [stops] places each one: the same length as [colors], + /// ascending, each in `[0, 1)`. Omitted, the colors are spaced evenly from + /// top-centre (0, 1/n, 2/n, …). Alpha is honoured: a translucent stop + /// glows more faintly. /// - /// The colors are deliberately low-contrast; the iridescence comes from - /// pairing them with a fast continuous hue drift: - /// - /// ```dart - /// BorderBeam.rotate( - /// colors: BeamColors.holographic, - /// style: const BeamStyle(hueMode: BeamHueMode.continuous), - /// timing: const BeamTiming(huePeriod: Duration(seconds: 3)), - /// child: card, - /// ) - /// ``` - static const BeamColors holographic = _CustomBeamColors(holographicColors); + /// The lists are checked when the palette is first resolved — in release + /// builds too — and a bad one throws an [ArgumentError]. + const factory BeamColors(List colors, {List? stops}) = + _StopBeamColors; - // ─── Factories ──────────────────────────────────────────────────────────── + /// A single [color] all the way round. + const factory BeamColors.solid(Color color) = _SolidBeamColors; - /// Distributes [colors] over [base]'s blob geometry (cycling when fewer - /// colors than blob slots are given). - /// - /// The list must not be empty. Alpha channels of the base tables (inner - /// glows, bloom spikes) are preserved and applied to your colors, so the - /// layered depth of the effect is kept. - /// - /// [base] chooses which resolved tables supply that geometry and alpha - /// structure — any [BeamColors] is accepted, including another custom - /// palette. Only the tables are taken: a mono [base] does not make the - /// result mono. - const factory BeamColors.custom(List colors, {BeamColors base}) = - _CustomBeamColors; - - /// Derives a multi-blob palette from a single brand color. + /// Derives a palette from a single brand color. /// /// [harmony] picks how the seed hue is spread (see [BeamSeedHarmony]). /// The derived colors are lifted into a readable glow band — lightness /// 0.55–0.70, saturation at least 0.55 — so a black, white or gray seed - /// still yields visible, distinguishable blobs. - /// - /// The palette *geometry* always comes from the [colorful] preset; only - /// the colors are derived. + /// still yields visible, distinguishable colors. They are spaced evenly + /// around the border. /// /// ```dart - /// BorderBeam.rotate( + /// BorderBeam( /// colors: const BeamColors.fromSeed(Color(0xFF18A8F0)), /// child: card, /// ) @@ -159,58 +103,151 @@ sealed class BeamColors { _SeedBeamColors; /// Builds a palette from a Material [ColorScheme]'s primary, secondary and - /// tertiary roles. + /// tertiary roles, spaced evenly around the border. /// /// Roles that are near-duplicates of an earlier one are dropped, so a /// scheme whose secondary matches its primary yields a two-color palette - /// rather than a doubled one. Geometry comes from the [colorful] preset. - factory BeamColors.fromScheme(ColorScheme scheme) => _CustomBeamColors( + /// rather than a doubled one. + factory BeamColors.fromScheme(ColorScheme scheme) => _StopBeamColors( _dedupe([scheme.primary, scheme.secondary, scheme.tertiary]), ); /// Blends two color choices. /// - /// The result resolves to a palette whose every table entry is the - /// [Color.lerp] of the corresponding entries of [a] and [b] at [t]. - /// Positions and sizes come from [a]; where [b]'s table is shorter its - /// colors cycle. `forcesStaticColors` and the mono treatment come from - /// whichever end is nearer, and the opacity multiplier is interpolated. - /// - /// [t] is not clamped — values outside 0–1 extrapolate, as with - /// [Color.lerp]. + /// Both palettes are sampled at eight evenly spaced positions around the + /// border and each pair is mixed gamma-aware at [t], which is clamped to + /// 0–1. At exactly 0 or 1 the result is [a] or [b] unchanged. The hue is + /// fixed when the nearer end's is. const factory BeamColors.lerp(BeamColors a, BeamColors b, double t) = _LerpBeamColors; - /// Advanced: full per-blob control. + // ─── Presets ────────────────────────────────────────────────────────────── + + /// Orange, magenta, violet, blue, green, and hot pink — the full spectrum. + /// The default. + static const BeamColors colorful = _PresetBeamColors( + 'colorful', + colorfulPalette, + ); + + /// Whites and greys. The hue never drifts. + static const BeamColors mono = _PresetBeamColors('mono', monoPalette); + + /// Blues and violets. + static const BeamColors ocean = _PresetBeamColors('ocean', oceanPalette); + + /// Reds, oranges, and amber. + static const BeamColors sunset = _PresetBeamColors('sunset', sunsetPalette); + + /// Northern lights: teal, violet, and green. + static const BeamColors aurora = _PresetBeamColors('aurora', auroraPalette); + + /// Fully saturated magenta, lime, and cyan — the loudest preset. + static const BeamColors neon = _PresetBeamColors('neon', neonPalette); + + /// Pastel pink, lavender, and peach. + static const BeamColors candy = _PresetBeamColors('candy', candyPalette); + + /// Deep red, orange, and gold — the hot end of a fire. + static const BeamColors ember = _PresetBeamColors('ember', emberPalette); + + /// Pale blue, white, and cyan. + static const BeamColors ice = _PresetBeamColors('ice', icePalette); + + /// Warm monochrome: amber, gold, and bronze. /// - /// [border] replaces the 9-blob border table (any length ≥ 1) used by the - /// rotate stroke and as the pulse color source; each [BeamBlob.size] holds - /// the ellipse *radii*, not its diameters. Tables not provided - /// ([smallBorder], [lineBlobs]) are derived by cycling the border colors - /// over the default geometry. - const factory BeamColors.spec({ - required List border, - List? smallBorder, - List? lineBlobs, - }) = _SpecBeamColors; + /// Like [mono] it pins the hue — a hue sweep over a single-hue metal reads + /// as the metal changing material. + static const BeamColors gold = _PresetBeamColors('gold', goldPalette); + + /// Desaturated pastels built for a hue sweep. + /// + /// The colors are deliberately low-contrast; the iridescence comes from + /// pairing them with a fast continuous hue drift: + /// + /// ```dart + /// BorderBeam( + /// colors: BeamColors.holographic, + /// style: const BeamStyle(hueMode: BeamHueMode.continuous), + /// timing: const BeamTiming(huePeriod: Duration(seconds: 3)), + /// child: card, + /// ) + /// ``` + static const BeamColors holographic = _PresetBeamColors( + 'holographic', + holographicPalette, + ); + + /// Teal, aqua, and mint — shallow tropical water. + static const BeamColors lagoon = _PresetBeamColors('lagoon', lagoonPalette); + + /// Indigo, violet, and rose — the sky after sundown. + static const BeamColors dusk = _PresetBeamColors('dusk', duskPalette); + + /// Emerald, lime, and teal. + static const BeamColors forest = _PresetBeamColors('forest', forestPalette); + + /// Pink, coral, and mauve. + static const BeamColors rose = _PresetBeamColors('rose', rosePalette); + + /// Deep violet, electric blue, and magenta. + static const BeamColors cosmic = _PresetBeamColors('cosmic', cosmicPalette); + + /// Lime, yellow, and tangerine. + static const BeamColors citrus = _PresetBeamColors('citrus', citrusPalette); + + /// Cerulean, periwinkle, and a white-blue. + static const BeamColors sky = _PresetBeamColors('sky', skyPalette); + + /// Lilac, lavender, and a soft pink. + static const BeamColors lavender = _PresetBeamColors( + 'lavender', + lavenderPalette, + ); + + /// Every preset by name, in gallery order: the four originals, then the + /// rest. + static const Map presets = { + 'colorful': colorful, + 'mono': mono, + 'ocean': ocean, + 'sunset': sunset, + 'aurora': aurora, + 'neon': neon, + 'candy': candy, + 'ember': ember, + 'ice': ice, + 'gold': gold, + 'holographic': holographic, + 'lagoon': lagoon, + 'dusk': dusk, + 'forest': forest, + 'rose': rose, + 'cosmic': cosmic, + 'citrus': citrus, + 'sky': sky, + 'lavender': lavender, + }; // ─── Transforms ─────────────────────────────────────────────────────────── - /// Multiplies every table entry's alpha by [factor], clamping the result - /// to 0–1. + /// Multiplies every stop's alpha by [factor], clamping the result to 0–1. /// - /// This dims the palette itself rather than the layer opacity, so the - /// relative depth of the inner/stroke/bloom tables is preserved. [factor] + /// This dims the palette itself rather than the beam's overall strength, + /// so stops that were already fainter stay relatively fainter. [factor] /// must not be negative. BeamColors scaleAlpha(double factor) => _ScaledBeamColors(this, factor); // ─── Resolution ─────────────────────────────────────────────────────────── - /// Resolves this color choice to concrete gradient tables. + /// Immutable value used by the resolved-palette LRU. + Object get _cacheKey; + + /// Resolves this color choice to concrete stops. /// /// The result is memoized by *value*: two separately constructed but equal /// instances return the identical [BeamPalette], which is what lets a - /// config compare palettes cheaply. The memo is a bounded LRU, so a + /// beam compare palettes cheaply. The memo is a bounded LRU, so a /// long-lived app cycling through many palettes cannot grow it without /// limit; an evicted palette is simply rebuilt, and compares equal to the /// one it replaces. @@ -225,7 +262,7 @@ sealed class BeamColors { /// How many distinct color choices keep a resolved palette. Comfortably /// above the handful a screen uses at once, small enough that the retained -/// tables stay negligible. +/// stops stay negligible. const int _paletteCacheCapacity = 32; // Insertion-ordered, so the first key is the least recently used: a hit @@ -234,7 +271,7 @@ final LinkedHashMap _paletteCache = LinkedHashMap(); BeamPalette _resolveCached(BeamColors colors) { - // User-provided tables may come from growable lists. Never put the public + // User-provided colors may come from growable lists. Never put the public // value object itself in a hash map: mutating one of those source lists // would change its hash while it was resident and make the entry // unreachable. Each implementation supplies an immutable snapshot of the @@ -268,138 +305,20 @@ class _ListKey { int get hashCode => Object.hashAll(values); } -// The presets bypass the LRU: they are canonicalized const instances, so an -// identity-keyed Expando memoizes them for the life of the isolate without -// hashing a color table or competing with user palettes for a cache slot. -final Expando _presetPaletteCache = Expando( - 'BeamColors.preset', -); - -// ─── Table helpers ────────────────────────────────────────────────────────── - -/// Distributes [colors] over [base]'s blob geometry, cycling when there are -/// fewer colors than blob slots and preserving each table entry's alpha so -/// the layered depth of the effect survives the substitution. -BeamPresetData _distribute(List colors, BeamPresetData base) { - Color pick(int i, Color original) { - final c = colors[i % colors.length]; - // Keep the preset's alpha so inner/bloom layering depth is preserved. - return c.withValues(alpha: original.a); - } - - return BeamPresetData( - border: [ - for (final (i, b) in base.border.indexed) b.withColor(pick(i, b.color)), - ], - spike: SpikeColors( - primary: pick(0, base.spike.primary), - secondary: pick(1, base.spike.secondary), - ), - spikeLt: SpikeColors( - primary: pick(0, base.spikeLt.primary), - secondary: pick(1, base.spikeLt.secondary), - ), - smallBorder: [ - for (final (i, b) in base.smallBorder.indexed) - b.withColor(pick(i, b.color)), - ], - smallInner: [ - for (final (i, b) in base.smallInner.indexed) - b.withColor(pick(i, b.color)), - ], - lineDark: [ - for (final (i, b) in base.lineDark.indexed) b.withColor(pick(i, b.color)), - ], - lineLight: [ - for (final (i, b) in base.lineLight.indexed) - b.withColor(pick(i, b.color)), - ], - lineInner: [ - for (final (i, b) in base.lineInner.indexed) - b.withColor(pick(i, b.color)), - ], - lineBloomDark: [ - for (final (i, s) in base.lineBloomDark.indexed) - SpikePair(pick(i, s.color1), pick(i, s.color2)), - ], - lineBloomLight: [ - for (final (i, s) in base.lineBloomLight.indexed) - SpikePair(pick(i, s.color1), pick(i, s.color2)), - ], - ); -} - -/// Rebuilds [data] with every table color passed through [f], keeping all -/// geometry. -BeamPresetData _mapColors(BeamPresetData data, Color Function(Color) f) => - BeamPresetData( - border: [for (final b in data.border) b.withColor(f(b.color))], - spike: SpikeColors( - primary: f(data.spike.primary), - secondary: f(data.spike.secondary), - ), - spikeLt: SpikeColors( - primary: f(data.spikeLt.primary), - secondary: f(data.spikeLt.secondary), - ), - smallBorder: [for (final b in data.smallBorder) b.withColor(f(b.color))], - smallInner: [for (final b in data.smallInner) b.withColor(f(b.color))], - lineDark: [for (final b in data.lineDark) b.withColor(f(b.color))], - lineLight: [for (final b in data.lineLight) b.withColor(f(b.color))], - lineInner: [for (final b in data.lineInner) b.withColor(f(b.color))], - lineBloomDark: [ - for (final s in data.lineBloomDark) SpikePair(f(s.color1), f(s.color2)), - ], - lineBloomLight: [ - for (final s in data.lineBloomLight) - SpikePair(f(s.color1), f(s.color2)), - ], - ); - -/// Pairs [a]'s tables with [b]'s and combines their colors through [mix], -/// keeping [a]'s geometry. Where [b]'s table is shorter its entries cycle; -/// where it is empty, [a]'s color passes through untouched. -BeamPresetData _zipColors( - BeamPresetData a, - BeamPresetData b, - Color Function(Color, Color) mix, -) { - Color at(List other, int i, Color own, Color Function(T) color) => - other.isEmpty ? own : mix(own, color(other[i % other.length])); - - List blobs(List xa, List xb) => [ - for (final (i, blob) in xa.indexed) - blob.withColor(at(xb, i, blob.color, (o) => o.color)), - ]; - List lines(List xa, List xb) => [ - for (final (i, blob) in xa.indexed) - blob.withColor(at(xb, i, blob.color, (o) => o.color)), - ]; - List pairs(List xa, List xb) => [ - for (final (i, s) in xa.indexed) - SpikePair( - at(xb, i, s.color1, (o) => o.color1), - at(xb, i, s.color2, (o) => o.color2), - ), - ]; - - return BeamPresetData( - border: blobs(a.border, b.border), - spike: SpikeColors( - primary: mix(a.spike.primary, b.spike.primary), - secondary: mix(a.spike.secondary, b.spike.secondary), - ), - spikeLt: SpikeColors( - primary: mix(a.spikeLt.primary, b.spikeLt.primary), - secondary: mix(a.spikeLt.secondary, b.spikeLt.secondary), - ), - smallBorder: blobs(a.smallBorder, b.smallBorder), - smallInner: blobs(a.smallInner, b.smallInner), - lineDark: lines(a.lineDark, b.lineDark), - lineLight: lines(a.lineLight, b.lineLight), - lineInner: lines(a.lineInner, b.lineInner), - lineBloomDark: pairs(a.lineBloomDark, b.lineBloomDark), - lineBloomLight: pairs(a.lineBloomLight, b.lineBloomLight), +/// A validated palette built from caller-owned lists, snapshotted so a later +/// mutation of those lists cannot change it. +BeamPalette _paletteOf( + List colors, + List? stops, + String name, { + bool fixedHue = false, +}) { + final resolvedStops = stops ?? BeamPalette.evenStops(colors.length); + validatePalette(colors, resolvedStops, name); + return BeamPalette( + colors: List.unmodifiable(colors), + stops: List.unmodifiable(resolvedStops), + fixedHue: fixedHue, ); } @@ -428,8 +347,8 @@ List _dedupe(List colors) { /// as a smudge on a dark surface. const double _seedMinLightness = 0.55; -/// Highest lightness a derived seed color may take — above this the blobs -/// wash out against a light surface. +/// Highest lightness a derived seed color may take — above this the glow +/// washes out against a light surface. const double _seedMaxLightness = 0.70; /// Saturation floor, so an achromatic seed still produces hue separation. @@ -470,7 +389,7 @@ List _seedColors(Color seed, BeamSeedHarmony harmony) { HSLColor.fromAHSL( 1, hue, - clampDouble(saturation * (1 - 0.1 * i), 0, 1), + clampDouble(saturation * (1 - 0.1 * i), _seedMinSaturation, 1), lerpDouble(_seedMinLightness, _seedMaxLightness, i / 3)!, ).toColor(), ], @@ -480,80 +399,89 @@ List _seedColors(Color seed, BeamSeedHarmony harmony) { // ─── Implementations ──────────────────────────────────────────────────────── class _PresetBeamColors extends BeamColors { - const _PresetBeamColors(this.preset, {this.isMono = false}) : super._(); + const _PresetBeamColors(this.name, this.palette) : super._(); - final BeamPresetData preset; - final bool isMono; + final String name; + final BeamPalette palette; @override - Object get _cacheKey => (#preset, preset, isMono); + Object get _cacheKey => (#preset, name); + // A preset's palette is a canonical const: no memo needed. @override - BeamPalette resolve() => _presetPaletteCache[this] ??= _buildPalette(); + BeamPalette resolve() => palette; @override - BeamPalette _buildPalette() => BeamPalette( - data: preset, - forcesStaticColors: isMono, - opacityMultiplier: isMono ? 0.5 : 1.0, - monoTreatment: isMono, - ); + BeamPalette _buildPalette() => palette; @override bool operator ==(Object other) => identical(this, other) || other is _PresetBeamColors && - identical(other.preset, preset) && - other.isMono == isMono; + other.name == name && + identical(other.palette, palette); @override - int get hashCode => Object.hash(identityHashCode(preset), isMono); + int get hashCode => Object.hash(_PresetBeamColors, name); @override - String toString() => 'BeamColors(preset, isMono: $isMono)'; + String toString() => 'BeamColors.$name'; } -class _CustomBeamColors extends BeamColors { - const _CustomBeamColors( - this.colors, { - this.base = BeamColors.colorful, - this.staticHue = false, - }) : super._(); +class _StopBeamColors extends BeamColors { + const _StopBeamColors(this.colors, {this.stops}) : super._(); final List colors; - final BeamColors base; - - // Set only by the built-in single-hue presets; `BeamColors.custom` never - // exposes it, because pinning the hue of a palette the caller chose would - // silently ignore their `hueMode`. - final bool staticHue; + final List? stops; @override Object get _cacheKey => - (#custom, _ListKey(colors), base._cacheKey, staticHue); + (#stops, _ListKey(colors), stops == null ? null : _ListKey(stops!)); @override - BeamPalette _buildPalette() { - validateColorTable(colors.length, 'BeamColors.custom colors'); - return BeamPalette( - data: _distribute(colors, base.resolve().data), - forcesStaticColors: staticHue, - ); - } + BeamPalette _buildPalette() => _paletteOf(colors, stops, 'BeamColors'); @override bool operator ==(Object other) => identical(this, other) || - other is _CustomBeamColors && + other is _StopBeamColors && listEquals(other.colors, colors) && - other.base == base && - other.staticHue == staticHue; + listEquals(other.stops, stops); @override - int get hashCode => Object.hash(Object.hashAll(colors), base, staticHue); + int get hashCode => Object.hash( + Object.hashAll(colors), + stops == null ? null : Object.hashAll(stops!), + ); @override - String toString() => 'BeamColors.custom($colors)'; + String toString() => stops == null + ? 'BeamColors($colors)' + : 'BeamColors($colors, stops: $stops)'; +} + +class _SolidBeamColors extends BeamColors { + const _SolidBeamColors(this.color) : super._(); + + final Color color; + + @override + Object get _cacheKey => (#solid, color); + + @override + BeamPalette _buildPalette() => + BeamPalette(colors: List.unmodifiable([color]), stops: const [0]); + + @override + bool operator ==(Object other) => + identical(this, other) || + other is _SolidBeamColors && other.color == color; + + @override + int get hashCode => Object.hash(_SolidBeamColors, color); + + @override + String toString() => 'BeamColors.solid($color)'; } class _SeedBeamColors extends BeamColors { @@ -567,9 +495,8 @@ class _SeedBeamColors extends BeamColors { Object get _cacheKey => (#seed, seed, harmony); @override - BeamPalette _buildPalette() => BeamPalette( - data: _distribute(_seedColors(seed, harmony), colorfulPreset), - ); + BeamPalette _buildPalette() => + _paletteOf(_seedColors(seed, harmony), null, 'BeamColors.fromSeed'); @override bool operator ==(Object other) => @@ -592,6 +519,9 @@ class _LerpBeamColors extends BeamColors { final BeamColors b; final double t; + /// How many positions both ends are sampled at. + static const int _samples = maxPaletteStops; + @override Object get _cacheKey => (#lerp, a._cacheKey, b._cacheKey, t); @@ -599,16 +529,16 @@ class _LerpBeamColors extends BeamColors { BeamPalette _buildPalette() { final pa = a.resolve(); final pb = b.resolve(); - final nearer = t < 0.5 ? pa : pb; + final f = t.isNaN ? 0.0 : clampDouble(t, 0, 1); + if (f == 0) return pa; + if (f == 1) return pb; + final stops = BeamPalette.evenStops(_samples); return BeamPalette( - data: _zipColors(pa.data, pb.data, (x, y) => Color.lerp(x, y, t)!), - forcesStaticColors: nearer.forcesStaticColors, - opacityMultiplier: lerpDouble( - pa.opacityMultiplier, - pb.opacityMultiplier, - t, - )!, - monoTreatment: nearer.monoTreatment, + colors: List.unmodifiable([ + for (final u in stops) mixColor(pa.sample(u), pb.sample(u), f), + ]), + stops: stops, + fixedHue: (f < 0.5 ? pa : pb).fixedHue, ); } @@ -635,16 +565,28 @@ class _ScaledBeamColors extends BeamColors { @override BeamPalette _buildPalette() { - assert(factor >= 0, 'BeamColors.scaleAlpha requires a non-negative factor'); + if (!(factor >= 0)) { + throw ArgumentError.value( + factor, + 'BeamColors.scaleAlpha factor', + 'must not be negative', + ); + } final base = source.resolve(); + // A palette drawn with its own tables keeps them, scaled; the rest are + // sampled from the scaled stops. + final ownTables = base.tables != null || base.tableColors != null; return BeamPalette( - data: _mapColors( - base.data, - (c) => c.withValues(alpha: clampDouble(c.a * factor, 0, 1)), - ), - forcesStaticColors: base.forcesStaticColors, - opacityMultiplier: base.opacityMultiplier, - monoTreatment: base.monoTreatment, + colors: List.unmodifiable([ + for (final c in base.colors) + c.withValues(alpha: clampDouble(c.a * factor, 0, 1)), + ]), + stops: base.stops, + fixedHue: base.fixedHue, + tables: ownTables + ? scaleTableAlpha(BeamLook.tablesFor(base), factor) + : null, + mono: base.mono, ); } @@ -661,84 +603,3 @@ class _ScaledBeamColors extends BeamColors { @override String toString() => '$source.scaleAlpha($factor)'; } - -class _SpecBeamColors extends BeamColors { - const _SpecBeamColors({ - required this.border, - this.smallBorder, - this.lineBlobs, - }) : super._(); - - final List border; - final List? smallBorder; - final List? lineBlobs; - - @override - Object get _cacheKey => ( - #spec, - _ListKey(border), - smallBorder == null ? null : _ListKey(smallBorder!), - lineBlobs == null ? null : _ListKey(lineBlobs!), - ); - - @override - BeamPalette _buildPalette() { - validateColorTable(border.length, 'BeamColors.spec border'); - // The caller keeps their list, and a growable one they mutate later would - // otherwise change the palette this cache holds under a key that no - // longer matches it. Every table that reaches BeamPresetData is a - // snapshot of its own — the unmodifiable cache key alone does not make - // the resolved palette immutable. - final borderTable = List.unmodifiable(border); - final smallTable = smallBorder == null - ? null - : List.unmodifiable(smallBorder!); - final lineTable = lineBlobs == null - ? null - : List.unmodifiable(lineBlobs!); - // Derive any missing tables by cycling the provided border colors over - // the default geometry. - final derived = _distribute([ - for (final b in borderTable) b.color, - ], colorfulPreset); - return BeamPalette( - data: BeamPresetData( - border: borderTable, - spike: derived.spike, - spikeLt: derived.spikeLt, - smallBorder: smallTable ?? derived.smallBorder, - smallInner: smallTable != null - ? [ - for (final b in smallTable) - b.withColor(b.color.withValues(alpha: b.color.a * 0.45)), - ] - : derived.smallInner, - lineDark: lineTable ?? derived.lineDark, - lineLight: lineTable ?? derived.lineLight, - lineInner: derived.lineInner, - lineBloomDark: derived.lineBloomDark, - lineBloomLight: derived.lineBloomLight, - ), - ); - } - - @override - bool operator ==(Object other) => - identical(this, other) || - other is _SpecBeamColors && - listEquals(other.border, border) && - listEquals(other.smallBorder, smallBorder) && - listEquals(other.lineBlobs, lineBlobs); - - @override - int get hashCode => Object.hash( - Object.hashAll(border), - smallBorder == null ? null : Object.hashAll(smallBorder!), - lineBlobs == null ? null : Object.hashAll(lineBlobs!), - ); - - @override - String toString() => - 'BeamColors.spec(border: ${border.length} blobs, ' - 'smallBorder: ${smallBorder?.length}, lineBlobs: ${lineBlobs?.length})'; -} diff --git a/lib/src/models/beam_config.dart b/lib/src/models/beam_config.dart index 01ecf78..9957e35 100644 --- a/lib/src/models/beam_config.dart +++ b/lib/src/models/beam_config.dart @@ -1,93 +1,56 @@ -import 'dart:ui'; +import 'dart:math' as math; +import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; +import '../effects/beam_effect.dart'; import 'beam_options.dart'; import 'beam_palette.dart'; import 'beam_segment.dart'; import 'beam_shape.dart'; import 'beam_style.dart'; -import 'beam_theme_config.dart'; import 'beam_timing.dart'; -import 'beam_variant.dart'; -import 'model_validation.dart'; -// The line variant's breathe/spike tracks run at multiples of the cycle. -const double _defaultBreatheFactor = 1.3; -const double _defaultSpikeFactor = 1.33; -const double _defaultSpike2Factor = 1.7; - -// The window BeamStyle.renderScale is clamped to: below a quarter the -// magnification is coarse enough to read as a blur, and above 1 the beam -// would be painted larger than the box it fills. -const double _minRenderScale = 0.25; -const double _maxRenderScale = 1; - -double _seconds(Duration d) => - d.inMicroseconds / Duration.microsecondsPerSecond; - -/// The fully-resolved, frame-invariant configuration handed to the painter. +/// Everything a beam needs to paint, with every inherited value settled. /// -/// Built once by the widget whenever its inputs change; painting then only -/// depends on this config plus the animated frame phases. +/// Built by [BeamConfig.resolve] from the merged value objects. Value-equal, +/// so the painter repaints only when something that changes pixels changed. +/// Playback rate (`BeamTiming.speed`) is applied to the clock and is +/// deliberately not part of the config: a rate change never re-resolves it. +@immutable class BeamConfig { /// Creates a resolved config. Prefer [BeamConfig.resolve]. const BeamConfig({ - required this.variant, + required this.effect, required this.palette, - required this.theme, required this.brightness, - required this.borderRadius, - required this.borderWidth, - required this.useSuperellipse, required this.strength, - required this.brightnessFactor, - required this.saturation, - required this.hueRange, + required this.glow, + required this.hueMode, + required this.hueShift, required this.hueBase, - required this.staticColors, + required this.borderRadius, + required this.superellipse, + required this.borderWidth, + required this.ringOffset, + required this.segment, + required this.dashes, required this.cycleSeconds, - required this.hueMode, + required this.gapSeconds, + required this.direction, + required this.phaseOffset, required this.huePeriodSeconds, - required this.bloomHuePeriodSeconds, - this.gapSeconds = 0, - this.breatheFactor = _defaultBreatheFactor, - this.spikeFactor = _defaultSpikeFactor, - this.spike2Factor = _defaultSpike2Factor, - this.strokeOpacityFactor = 1, - this.innerOpacityFactor = 1, - this.bloomOpacityFactor = 1, - this.glowBoost = 1, - this.coreBlur, - this.bloomBlur, - this.glowBrightness, - this.glowSaturation, - this.tailLength = 1, - this.glowSpread = 1, - this.comet = false, - this.sparkle = 0, - this.segments, - this.innerSizeScale = 1, - this.renderScale = 1, - this.pulseOutsideTuning = BeamPulseOutsideTuning.demo, - this.edge = BeamEdge.bottom, - this.ringOffset = 0, - this.contour, - this.segment, - this.wrapCorners = false, - this.direction = BeamDirection.forward, - this.phaseOffset = 0, - this.beamCount = 1, }); - /// Resolves the beam value objects against the variant/theme presets, - /// mirroring the React component's computed values. + /// Resolves the value objects (already merged theme-under-widget) for + /// [effect]. [palette] and [brightness] are settled by the caller, which + /// owns the ambient theme; [textDirection] resolves `shape.radius`. /// - /// [palette] is the resolved form of `style.colors` and [brightness] the - /// resolved form of `style.theme` — both are settled by the widget, which - /// owns the ambient theme. [textDirection] resolves `shape.radius`. + /// A NaN or infinite style or shape number is treated as unset — the + /// shader is never handed a non-finite value — except that `strength` + /// clamps an infinity to its 0–1 range like any other value. factory BeamConfig.resolve({ - required BeamVariant variant, + required BeamEffect effect, required BeamPalette palette, required Brightness brightness, BeamStyle style = const BeamStyle(), @@ -95,377 +58,176 @@ class BeamConfig { BeamTiming timing = const BeamTiming(), TextDirection textDirection = TextDirection.ltr, }) { - validateBeamTiming(timing); - final theme = - style.themeConfig ?? BeamThemeConfig.presetFor(variant, brightness); - final cycleSeconds = _seconds(timing.cycle ?? variant.defaultCycleDuration); - final hueRange = style.hueRange ?? 30; + double seconds(Duration? d, Duration fallback) => + (d ?? fallback).inMicroseconds / Duration.microsecondsPerSecond; + double finite(double? value, double fallback) => + value != null && value.isFinite ? value : fallback; + final strength = style.strength; + final cycle = cycleSecondsFor(timing, effect); + final hueMode = palette.fixedHue + ? BeamHueMode.none + : (style.hueMode ?? effect.defaultHueMode); return BeamConfig( - variant: variant, + effect: effect, palette: palette, - theme: theme, brightness: brightness, - borderRadius: - shape.radius?.resolve(textDirection) ?? - BorderRadius.circular(variant.defaultBorderRadius), - borderWidth: shape.borderWidth ?? variant.defaultBorderWidth, - useSuperellipse: shape.superellipse ?? false, - strength: (style.strength ?? 1).clamp(0.0, 1.0), - brightnessFactor: style.brightness ?? theme.brightness ?? 1.3, - saturation: style.saturation ?? theme.saturation, - // The line variant caps the hue range at 13°, as in the source. - hueRange: variant == BeamVariant.line - ? (hueRange > 13 ? 13.0 : hueRange) - : hueRange, - hueMode: - style.hueMode ?? - (variant.isPulse ? BeamHueMode.continuous : BeamHueMode.pingPong), - hueBase: style.hueBase ?? 0, - staticColors: (style.staticColors ?? false) || palette.forcesStaticColors, - cycleSeconds: cycleSeconds, - gapSeconds: _seconds(timing.cycleGap ?? Duration.zero), - huePeriodSeconds: _seconds(timing.huePeriod ?? variant.defaultHuePeriod), - bloomHuePeriodSeconds: _seconds( - timing.bloomHuePeriod ?? variant.defaultBloomHuePeriod, - ), - breatheFactor: timing.breatheFactor ?? _defaultBreatheFactor, - spikeFactor: timing.spikeFactor ?? _defaultSpikeFactor, - spike2Factor: timing.spike2Factor ?? _defaultSpike2Factor, - strokeOpacityFactor: style.strokeOpacityFactor ?? 1, - innerOpacityFactor: style.innerOpacityFactor ?? 1, - bloomOpacityFactor: style.bloomOpacityFactor ?? 1, - glowBoost: style.glowBoost ?? 1, - coreBlur: style.coreBlur, - bloomBlur: style.bloomBlur, - glowBrightness: style.glowBrightness, - glowSaturation: style.glowSaturation, - tailLength: style.tailLength ?? 1, - glowSpread: style.glowSpread ?? 1, - comet: style.comet ?? false, - sparkle: (style.sparkle ?? 0).clamp(0.0, 1.0), - segments: style.segments, - innerSizeScale: style.innerSizeScale ?? 1, - renderScale: (style.renderScale ?? 1).clamp( - _minRenderScale, - _maxRenderScale, - ), - pulseOutsideTuning: - style.pulseOutsideTuning ?? BeamPulseOutsideTuning.demo, - edge: shape.edge ?? BeamEdge.bottom, - ringOffset: shape.ringOffset ?? 0, - contour: shape.contour, + strength: strength == null || strength.isNaN + ? 1 + : strength.clamp(0.0, 1.0), + glow: math.max(finite(style.glow, 1), 0), + hueMode: hueMode, + hueShift: finite(style.hueShift, 30), + hueBase: finite(style.hueBase, 0), + borderRadius: shape.resolveRadius(textDirection), + superellipse: shape.superellipse ?? false, + borderWidth: math.max(finite(shape.borderWidth, 1), 0), + ringOffset: finite(shape.ringOffset, 0), segment: shape.segment, - wrapCorners: shape.wrapCorners ?? false, + dashes: math.max(shape.dashes ?? 0, 0), + cycleSeconds: cycle, + gapSeconds: math.max(seconds(timing.cycleGap, effect.defaultCycleGap), 0), direction: timing.direction ?? BeamDirection.forward, phaseOffset: timing.phaseOffset ?? 0, - beamCount: timing.beamCount ?? 1, + huePeriodSeconds: math.max( + seconds(timing.huePeriod, effect.defaultHuePeriod), + 0.1, + ), ); } - /// Which effect to paint. - final BeamVariant variant; + /// The shortest cycle a beam runs, in seconds: a shorter `BeamTiming.cycle` + /// runs at this length. + static const double minCycleSeconds = 0.05; - /// Resolved gradient tables and mono modifiers. + /// The cycle, in seconds, [timing] gives [effect]: its own or the effect's + /// default, floored at [minCycleSeconds] — the [cycleSeconds] a config + /// resolved from them carries. + /// + /// Whatever schedules against the cycle outside a config (a running + /// clock's retime, for one) reads it here, so it measures the cycle the + /// beam actually runs rather than the one it was asked for. + static double cycleSecondsFor(BeamTiming timing, BeamEffect effect) => + math.max( + (timing.cycle ?? effect.defaultCycle).inMicroseconds / + Duration.microsecondsPerSecond, + minCycleSeconds, + ); + + /// What the beam does. + final BeamEffect effect; + + /// Resolved colour stops. final BeamPalette palette; - /// Theme preset (layer opacities, inset shadow, defaults). - final BeamThemeConfig theme; - - /// Resolved brightness (dark/light) the preset was chosen for. + /// Whether the beam is styled for a dark or a light surface. final Brightness brightness; - /// Corner radii of the beam shape in logical px — per corner, already - /// resolved against the ambient text direction. - final BorderRadius borderRadius; - - /// Stroke ring thickness in logical px. - final double borderWidth; - - /// Whether to shape the beam as a rounded superellipse (squircle). - final bool useSuperellipse; - - /// Global effect opacity multiplier, clamped 0–1. + /// Overall opacity, 0–1. final double strength; - /// Brightness filter multiplier. - final double brightnessFactor; - - /// Saturation filter multiplier. - final double saturation; + /// Glow size and intensity multiplier. + final double glow; - /// Hue animation amplitude in degrees (rotate/small/line ping-pong). - final double hueRange; - - /// Whether the hue swings across ±[hueRange] or revolves continuously. + /// How the palette's hue drifts over time. final BeamHueMode hueMode; - /// Static hue offset in degrees added to the animated hue. - final double hueBase; - - /// Whether hue animation is disabled. - final bool staticColors; - - /// Seconds per animation cycle. - final double cycleSeconds; - - /// Seconds the beam rests at the end of its travel between sweeps. - final double gapSeconds; - - /// Seconds for one full period of the hue track. - final double huePeriodSeconds; - - /// Seconds for one full period of the line bloom's hue track. - final double bloomHuePeriodSeconds; - - /// The line beam's height-breathe period as a multiple of [cycleSeconds]. - final double breatheFactor; - - /// The line beam's first spike period as a multiple of [cycleSeconds]. - final double spikeFactor; - - /// The line beam's second spike period as a multiple of [cycleSeconds]. - final double spike2Factor; - - /// Stroke ring opacity multiplier hook (React `--beam-stroke-opacity`). - final double strokeOpacityFactor; - - /// Inner glow opacity multiplier hook (React `--beam-inner-opacity`). - final double innerOpacityFactor; - - /// Bloom opacity multiplier hook (React `--beam-bloom-opacity`). - final double bloomOpacityFactor; - - /// Pulse glow prominence multiplier (React `--pulse-glow-boost`). - final double glowBoost; - - /// Pulse-outside core blur override in px (React `--beam-core-blur`). - final double? coreBlur; - - /// Pulse-outside bloom blur override in px (React `--beam-bloom-blur`). - final double? bloomBlur; + /// ± degrees of the ping-pong hue drift. + final double hueShift; - /// Pulse-outside glow brightness override (React `--beam-glow-brightness`). - final double? glowBrightness; - - /// Pulse-outside glow saturation override (React `--beam-glow-saturate`). - final double? glowSaturation; - - /// Multiplier on the angular width of the traveling window — the length of - /// the beam's tail. - final double tailLength; - - /// Multiplier on how far the bloom and halo layers reach past the ring. - final double glowSpread; - - /// Whether a soft halo trails the traveling head outside the ring. - final bool comet; - - /// Density 0–1 of the twinkles scattered at the traveling beam's head. - final double sparkle; - - /// Number of dashes the ring is broken into, or null for a solid ring. - final int? segments; - - /// Multiplier on the pulse-inside inner wash's blobs and corner accents. - final double innerSizeScale; + /// Static hue rotation in degrees. + final double hueBase; - /// The fraction of the box the beam is painted at before being magnified - /// back to fill it, clamped to 0.25–1. - final double renderScale; + /// Corner radii, resolved for the ambient text direction. + final BorderRadius borderRadius; - /// Which pulse-outside glow geometry to paint. - final BeamPulseOutsideTuning pulseOutsideTuning; + /// Whether corners are superellipse curves. + final bool superellipse; - /// Which edge the line variant's beam travels along. - final BeamEdge edge; + /// Stroke width in logical px. + final double borderWidth; - /// Logical px the ring sits outside (+) or inside (−) the child's bounds. + /// How far the outline sits outside (positive) or inside the child. final double ringOffset; - /// An arbitrary contour replacing the rounded rectangle, or null to build - /// the contour from [borderRadius] and [useSuperellipse]. - final BeamContour? contour; - - /// The visible clockwise portion of the contour, or null for the full ring. + /// The visible part of the border, or null for all of it. final BeamSegment? segment; - /// Whether line blobs bend through corners in border-path space. - final bool wrapCorners; + /// Number of dashes (below 2: a solid border). + final int dashes; + + /// One cycle, in seconds. + final double cycleSeconds; + + /// Rest between sweeps of a travelling effect, in seconds. + final double gapSeconds; - /// Which way the beam travels around the contour. + /// Travel direction. final BeamDirection direction; - /// Fraction of a cycle, 0–1, the timeline starts at. + /// Phase offset as a fraction of a cycle. final double phaseOffset; - /// How many beams travel the contour at once, spaced equally along the - /// cycle. - final int beamCount; + /// Hue drift period, in seconds. + final double huePeriodSeconds; - /// This config re-authored for a box [factor] the size of the real one. - /// - /// Only the lengths measured against the box travel with it — the corner - /// radii, the ring's thickness, and its offset. Everything the palettes fix - /// in absolute px (blob sizes, blur radii, corner accents) deliberately - /// stays put: painting those at [factor] and magnifying the result back is - /// exactly what makes a palette authored for a card read on a screen-sized - /// box. [renderScale] is spent by the copy, so a painter cannot scale - /// twice. - BeamConfig scaledBy(double factor) => BeamConfig( - variant: variant, - palette: palette, - theme: theme, - brightness: brightness, - borderRadius: borderRadius * factor, - borderWidth: borderWidth * factor, - useSuperellipse: useSuperellipse, - strength: strength, - brightnessFactor: brightnessFactor, - saturation: saturation, - hueRange: hueRange, - hueBase: hueBase, - staticColors: staticColors, - cycleSeconds: cycleSeconds, - hueMode: hueMode, - huePeriodSeconds: huePeriodSeconds, - bloomHuePeriodSeconds: bloomHuePeriodSeconds, - gapSeconds: gapSeconds, - breatheFactor: breatheFactor, - spikeFactor: spikeFactor, - spike2Factor: spike2Factor, - strokeOpacityFactor: strokeOpacityFactor, - innerOpacityFactor: innerOpacityFactor, - bloomOpacityFactor: bloomOpacityFactor, - glowBoost: glowBoost, - coreBlur: coreBlur, - bloomBlur: bloomBlur, - glowBrightness: glowBrightness, - glowSaturation: glowSaturation, - tailLength: tailLength, - glowSpread: glowSpread, - comet: comet, - sparkle: sparkle, - segments: segments, - innerSizeScale: innerSizeScale, - renderScale: 1, - pulseOutsideTuning: pulseOutsideTuning, - edge: edge, - ringOffset: ringOffset * factor, - contour: contour, - segment: segment?.scaledBy(factor), - wrapCorners: wrapCorners, - direction: direction, - phaseOffset: phaseOffset, - beamCount: beamCount, - ); + /// Whether this is a dark-surface beam. + bool get isDark => brightness == Brightness.dark; + + /// How many beams travel the border at once. + int get beamCount => switch (effect) { + RotateEffect(:final count) => count.clamp(1, 4), + _ => 1, + }; - /// Two configs are equal when every painted value is, which is what lets - /// `BeamPainter.shouldRepaint` compare configs rather than identities. - /// - /// [palette] compares by identity: `BeamColors.resolve` memoizes one - /// palette per color instance, so equal color choices reaching one widget - /// resolve to the identical palette. @override bool operator ==(Object other) => identical(this, other) || other is BeamConfig && - other.variant == variant && + other.effect == effect && other.palette == palette && - other.theme == theme && other.brightness == brightness && - other.borderRadius == borderRadius && - other.borderWidth == borderWidth && - other.useSuperellipse == useSuperellipse && other.strength == strength && - other.brightnessFactor == brightnessFactor && - other.saturation == saturation && - other.hueRange == hueRange && + other.glow == glow && other.hueMode == hueMode && + other.hueShift == hueShift && other.hueBase == hueBase && - other.staticColors == staticColors && - other.cycleSeconds == cycleSeconds && - other.gapSeconds == gapSeconds && - other.huePeriodSeconds == huePeriodSeconds && - other.bloomHuePeriodSeconds == bloomHuePeriodSeconds && - other.breatheFactor == breatheFactor && - other.spikeFactor == spikeFactor && - other.spike2Factor == spike2Factor && - other.strokeOpacityFactor == strokeOpacityFactor && - other.innerOpacityFactor == innerOpacityFactor && - other.bloomOpacityFactor == bloomOpacityFactor && - other.glowBoost == glowBoost && - other.coreBlur == coreBlur && - other.bloomBlur == bloomBlur && - other.glowBrightness == glowBrightness && - other.glowSaturation == glowSaturation && - other.tailLength == tailLength && - other.glowSpread == glowSpread && - other.comet == comet && - other.sparkle == sparkle && - other.segments == segments && - other.innerSizeScale == innerSizeScale && - other.renderScale == renderScale && - other.pulseOutsideTuning == pulseOutsideTuning && - other.edge == edge && + other.borderRadius == borderRadius && + other.superellipse == superellipse && + other.borderWidth == borderWidth && other.ringOffset == ringOffset && - other.contour == contour && other.segment == segment && - other.wrapCorners == wrapCorners && + other.dashes == dashes && + other.cycleSeconds == cycleSeconds && + other.gapSeconds == gapSeconds && other.direction == direction && other.phaseOffset == phaseOffset && - other.beamCount == beamCount; + other.huePeriodSeconds == huePeriodSeconds; @override - int get hashCode => Object.hashAll([ - variant, + int get hashCode => Object.hash( + effect, palette, - theme, brightness, - borderRadius, - borderWidth, - useSuperellipse, strength, - brightnessFactor, - saturation, - hueRange, + glow, hueMode, + hueShift, hueBase, - staticColors, - cycleSeconds, - gapSeconds, - huePeriodSeconds, - bloomHuePeriodSeconds, - breatheFactor, - spikeFactor, - spike2Factor, - strokeOpacityFactor, - innerOpacityFactor, - bloomOpacityFactor, - glowBoost, - coreBlur, - bloomBlur, - glowBrightness, - glowSaturation, - tailLength, - glowSpread, - comet, - sparkle, - segments, - innerSizeScale, - renderScale, - pulseOutsideTuning, - edge, + borderRadius, + superellipse, + borderWidth, ringOffset, - contour, segment, - wrapCorners, + dashes, + cycleSeconds, + gapSeconds, direction, phaseOffset, - beamCount, - ]); + huePeriodSeconds, + ); @override String toString() => - 'BeamConfig($variant, $brightness, radius: $borderRadius, ' - 'cycle: ${cycleSeconds}s, gap: ${gapSeconds}s, strength: $strength)'; + 'BeamConfig($effect, $brightness, radius: $borderRadius, ' + 'cycle: ${cycleSeconds}s)'; } diff --git a/lib/src/models/beam_options.dart b/lib/src/models/beam_options.dart index a6e9cc4..ac8fdbb 100644 --- a/lib/src/models/beam_options.dart +++ b/lib/src/models/beam_options.dart @@ -1,44 +1,24 @@ -import 'dart:ui'; - import 'package:flutter/foundation.dart'; -/// The shape of a beam's hue track: a swing back and forth, or one -/// continuous revolution. +/// How a beam's colours drift over time. enum BeamHueMode { - /// The hue swings from `-hueRange` to `+hueRange` and back over one hue - /// period — the traveling variants' default. + /// The hue swings from `-hueShift` to `+hueShift` and back over one hue + /// period — the default of `BeamEffect.rotate` and `BeamEffect.line`. pingPong, /// The hue advances through a full 360° revolution over one hue period, - /// never reversing — the pulse variants' default. + /// never reversing — the default of `BeamEffect.pulse`. continuous, -} -/// Which set of glow geometry the pulse-outside variant paints. -/// -/// The two differ only in how far the outward glow is grown past the child -/// and how heavily it is blurred; every other part of the variant is shared. -enum BeamPulseOutsideTuning { - /// The demo-hero recipe the source's demo page layers over its own - /// defaults: insets and blurs scaled by the element's size, melting the - /// separate blobs into one continuous edge-hugging glow. - /// - /// The default, because it is the pulse-outside look the library is known - /// for. - demo, - - /// The React library's own defaults: fixed insets and a per-brightness - /// blur, with no size-derived unit. - /// - /// Reach for it through `BeamStyle.pulseOutsideStock`, which also rolls - /// back the demo recipe's prominence and opacity multipliers. - stock, + /// The colours never drift: the palette is painted as given (rotated by + /// `BeamStyle.hueBase`, if set). + none, } -/// Which way a beam travels around its contour. +/// Which way a travelling effect moves. enum BeamDirection { - /// Clockwise for the rotate and small variants, left-to-right for the line - /// variant. + /// Clockwise around the border, or left-to-right (top-to-bottom on a side + /// edge) for `BeamEffect.line`. forward, /// The mirror of [forward]: counter-clockwise, or right-to-left. @@ -49,18 +29,19 @@ enum BeamDirection { bounce, } -/// Which edge of the box the line variant's beam rides. +/// An edge of the beam's box — the edge `BeamEffect.line` rides, or the edge +/// a `BeamAnchor.edge` sits on. enum BeamEdge { - /// The top edge, travelling horizontally. + /// The top edge. top, - /// The right edge, travelling vertically. + /// The right edge. right, - /// The bottom edge, travelling horizontally — the line variant's default. + /// The bottom edge — `BeamEffect.line`'s default. bottom, - /// The left edge, travelling vertically. + /// The left edge. left, } @@ -81,13 +62,16 @@ enum BeamReducedMotion { slow, } +/// The rate [BeamReducedMotion.slow] scales a beam's speed by. +const double slowMotionFactor = 0.25; + /// How many cycles a beam runs before it stops. /// /// A beam that reaches its last cycle fades out the way an inactive one /// does, rather than cutting off mid-sweep. /// /// ```dart -/// BorderBeam.rotate( +/// BorderBeam( /// playback: const BeamPlayback(repeat: BeamRepeat.count(3)), /// child: card, /// ) @@ -119,72 +103,3 @@ class BeamRepeat { String toString() => cycles == null ? 'BeamRepeat.forever()' : 'BeamRepeat.count($cycles)'; } - -/// An arbitrary outer contour for the beam to travel, replacing the rounded -/// rectangle built from `BeamShape.radius`. -/// -/// The beam's ring, its masks, and the path the traveling head follows are -/// all built from [build], so any closed path works — a notched card, a -/// speech bubble, a hand-drawn blob. -/// -/// A contour is a value: `BeamConfig` keys its cache on it, so **every -/// implementer must override `==` and `hashCode`**. A contour that compares -/// by identity re-resolves the config on every rebuild. [BeamPathContour] -/// shows the pattern — it compares on an explicit key, because two closures -/// that draw the same path are never equal to each other. -@immutable -abstract class BeamContour { - /// Allows subclasses to be const. - const BeamContour(); - - /// Builds the contour path for a beam occupying [rect]. - /// - /// Called with the beam's own bounds, already grown or shrunk by - /// `BeamShape.ringOffset`. Return a closed path in the same coordinate - /// space. - Path build(Rect rect); -} - -/// A [BeamContour] that delegates to a builder function, comparing on an -/// explicit [key]. -/// -/// ```dart -/// BeamShape( -/// contour: BeamPathContour( -/// (rect) => Path()..addOval(rect), -/// key: 'oval', -/// ), -/// ) -/// ``` -class BeamPathContour extends BeamContour { - /// Creates a contour that calls [builder], and compares equal to another - /// [BeamPathContour] carrying an equal [key]. - const BeamPathContour(this.builder, {required this.key}); - - /// Draws the contour for the beam's bounds. - final Path Function(Rect rect) builder; - - /// The value this contour compares and hashes on. - /// - /// Two contours built from the same drawing take the same key — Dart - /// closures compare by identity, so an inline builder would otherwise make - /// every rebuild a new value. Any value-equal object works: a string, an - /// enum, or a `Record` of the parameters the builder closes over. - final Object key; - - @override - Path build(Rect rect) => builder(rect); - - @override - bool operator ==(Object other) => - identical(this, other) || - other is BeamPathContour && - other.runtimeType == runtimeType && - other.key == key; - - @override - int get hashCode => Object.hash(runtimeType, key); - - @override - String toString() => 'BeamPathContour($key)'; -} diff --git a/lib/src/models/beam_palette.dart b/lib/src/models/beam_palette.dart index ed58946..001fe2b 100644 --- a/lib/src/models/beam_palette.dart +++ b/lib/src/models/beam_palette.dart @@ -1,54 +1,108 @@ -import '../constants/palettes.dart'; +import 'dart:ui'; -/// A fully-resolved palette: the gradient-table bundle plus the paint-time -/// modifiers a color choice implies. +import 'package:flutter/foundation.dart'; + +import '../look/palette_tables.dart'; +import '../render/color_math.dart'; + +/// The most colour stops a palette may carry. +/// +/// A design limit, checked when a palette resolves. Palette stops never +/// reach the shader: the effects draw a palette through blob tables sampled +/// from it (`BeamLook.tablesFor`). +const int maxPaletteStops = 8; + +/// A resolved palette: a ring of colour stops around the border. /// -/// Produced by [BeamColors.resolve] — strategies read tables from [data] and -/// apply [opacityMultiplier] / [monoTreatment]. +/// Produced by `BeamColors.resolve`. Each stop sits at a perimeter coordinate +/// `u` in `[0, 1)` — 0 at top-centre, increasing clockwise by arc length. +/// Between stops the colour blends gamma-aware, and past the last stop it +/// blends back into the first across top-centre, so the ring is seamless. +@immutable class BeamPalette { - /// Creates a resolved palette. + /// Creates a palette from [colors] at [stops]. + /// + /// Both lists must have the same length (1–[maxPaletteStops]), and [stops] + /// must ascend within `[0, 1)`. The lists are stored as given — pass + /// unmodifiable ones. const BeamPalette({ - required this.data, - this.forcesStaticColors = false, - this.opacityMultiplier = 1.0, - this.monoTreatment = false, + required this.colors, + required this.stops, + this.fixedHue = false, + this.tables, + this.tableColors, + this.mono = false, }); - /// The gradient tables (border blobs, small tables, line tables, spikes). - final BeamPresetData data; + /// The stop colours, in stop order. Alpha is the stop's strength. + final List colors; - /// Whether hue animation must be disabled (mono preset). - final bool forcesStaticColors; + /// The perimeter coordinate of each colour, ascending, each in `[0, 1)`. + final List stops; - /// Layer opacity multiplier (0.5 for mono on rotate/small/pulse variants; - /// the line variant ignores this and uses [monoTreatment] instead). - final double opacityMultiplier; + /// Whether the hue must never drift (the mono and gold presets): a hue + /// sweep over a grey or a single-hue metal reads as the material changing. + final bool fixedHue; - /// Whether the line variant applies its grayscale spike attenuation - /// (alpha rescale, wider/shorter spikes, extra bloom blur). - final bool monoTreatment; + /// The blob tables this palette is drawn with, or null to derive them + /// (see `BeamLook.tablesFor`). + final BeamLookTables? tables; + + /// Colours to cycle over `colorful`'s blob tables instead of sampling + /// [colors] into them, or null. + final List? tableColors; + + /// Whether this is the greyscale palette: its layers paint at half + /// opacity (the line effect softens its spikes instead), since white light + /// reads far brighter than coloured light at the same alpha. + final bool mono; + + /// The number of stops. + int get length => colors.length; + + /// The colour at perimeter coordinate [u] (wrapped into `[0, 1)`), blended + /// gamma-aware between the stops either side of it — how a palette without + /// tables of its own is sampled into `colorful`'s blob geometry. + Color sample(double u) => + samplePalette(colors, stops, u - u.floorToDouble(), wrap: true); + + /// [count] stop positions evenly spaced around the ring, starting at 0. + static List evenStops(int count) => + List.unmodifiable([for (var i = 0; i < count; i++) i / count]); - /// Two palettes are equal when their tables and paint-time modifiers are. - /// - /// [BeamColors.resolve] hands out one palette per distinct color choice, - /// so this normally short-circuits on identity; the structural path - /// covers palettes rebuilt after a cache eviction. @override bool operator ==(Object other) => identical(this, other) || other is BeamPalette && - other.data == data && - other.forcesStaticColors == forcesStaticColors && - other.opacityMultiplier == opacityMultiplier && - other.monoTreatment == monoTreatment; + other.fixedHue == fixedHue && + other.mono == mono && + other.tables == tables && + listEquals(other.tableColors, tableColors) && + listEquals(other.colors, colors) && + listEquals(other.stops, stops); @override - int get hashCode => - Object.hash(data, forcesStaticColors, opacityMultiplier, monoTreatment); + int get hashCode => Object.hash( + Object.hashAll(colors), + Object.hashAll(stops), + fixedHue, + mono, + tables, + tableColors == null ? null : Object.hashAll(tableColors!), + ); + // Tables are dozens of blobs, so they print as an identity: their hash is + // structural, so equal tables print alike and different ones apart. @override - String toString() => - 'BeamPalette(forcesStaticColors: $forcesStaticColors, ' - 'opacityMultiplier: $opacityMultiplier, ' - 'monoTreatment: $monoTreatment)'; + String toString() { + final fields = [ + 'colors: $colors', + 'stops: $stops', + 'fixedHue: $fixedHue', + 'mono: $mono', + if (tables != null) 'tables: ${describeIdentity(tables)}', + if (tableColors != null) 'tableColors: $tableColors', + ]; + return 'BeamPalette(${fields.join(', ')})'; + } } diff --git a/lib/src/models/beam_playback.dart b/lib/src/models/beam_playback.dart index 01d5037..84a9854 100644 --- a/lib/src/models/beam_playback.dart +++ b/lib/src/models/beam_playback.dart @@ -16,7 +16,8 @@ import 'beam_options.dart'; /// ignored. /// /// ```dart -/// BorderBeam.pulseInside( +/// BorderBeam( +/// effect: const BeamEffect.pulse(), /// playback: BeamPlayback( /// active: isWorking, /// startAfter: const Duration(milliseconds: 500), @@ -41,13 +42,13 @@ class BeamPlayback { /// The web platform's `ease` timing function, as a [Curve]. /// - /// The fades default to a spring, which carries a little momentum. Hand - /// this to [fadeCurve] to get the CSS transition the source library's own - /// page fades with instead. + /// The fades default to critically damped springs, which ease in and + /// settle without overshoot. Hand this to [fadeCurve] to get the CSS + /// transition the source library's own page fades with instead. static const Curve cssEase = Cubic(0.25, 0.1, 0.25, 1); - /// Declarative play state: toggling fades the beam in (0.6s) and out - /// (0.5s). Default true. + /// Declarative play state: toggling fades the beam in (about 0.5s) and + /// out (about 0.6s). Default true. final bool? active; /// Whether the beam starts by itself. Default true. @@ -80,8 +81,9 @@ class BeamPlayback { /// there is none. final bool? pauseWhenOffscreen; - /// The easing both fade envelopes run on. Null (the default) uses the - /// spring, which overshoots slightly and settles. + /// The easing both fade envelopes run on. Null (the default) uses + /// critically damped springs — Apple's `.smooth`, with a slightly longer + /// response on the way out — which glide without overshoot. /// /// [cssEase] is the web's own `ease`, for a fade that matches the source /// library exactly. @@ -95,11 +97,17 @@ class BeamPlayback { /// That is what makes a beam screenshottable — golden tests, docs /// captures, design reviews. /// - /// It reads the timeline from activation, so anything past the 0.6s - /// fade-in is a fully-lit frame. The frozen frame is still sampled at the - /// live strength — [BeamStyle.strength] and - /// [BorderBeam.strengthListenable] dim it as they would any other frame, + /// The instant is measured on the timeline from activation, and the + /// fade-in is skipped: the frame is lit as if the beam had long since + /// faded in (a `BeamTiming.cycleGap` rest still dims it). It is sampled at + /// the live strength — `BeamStyle.strength` and + /// `BorderBeam.strengthListenable` dim it as they would any other frame, /// and a strength of 0 paints nothing. + /// + /// Setting it on a running beam stops its clock; clearing it again resumes + /// the clock, or starts a beam that never got to. A beam driven by a + /// `BorderBeamController` is the exception: the frame is pinned, but its + /// clock runs, pauses, and resumes only when the controller says so. final Duration? debugFrozenAt; /// Returns a copy with the given fields replaced. A null argument keeps the diff --git a/lib/src/models/beam_presets.dart b/lib/src/models/beam_presets.dart new file mode 100644 index 0000000..faaa715 --- /dev/null +++ b/lib/src/models/beam_presets.dart @@ -0,0 +1,275 @@ +import 'dart:ui'; + +import '../look/extra_palettes.dart'; +import '../look/palette_tables.dart'; +import 'beam_palette.dart'; + +// The built-in palettes, each a ring of colour stops around the border: +// position 0 is top-centre and positions increase clockwise by arc length. +// +// The stops of the four originals and the seven that follow them were laid +// out from where their blob tables put each colour on a 350 × 140 card; the +// blob tables themselves (`lib/src/look/`) are what the effects draw with. +// The palettes new in 0.2 have stops only, and are drawn by sampling them +// into `colorful`'s blob geometry. Every preset reads as light on both dark +// and light surfaces. + +// ─── Originals ────────────────────────────────────────────────────────────── + +/// `BeamColors.colorful`: orange, magenta, violet, blue, green, and a hot +/// pink across the top — the full spectrum. +const BeamPalette colorfulPalette = BeamPalette( + colors: [ + Color(0xFFFF7828), // orange + Color(0xFFC82BDF), // magenta + Color(0xFF6446FF), // violet + Color(0xFF288CFF), // blue + Color(0xFF2FC568), // green + Color(0xFF288CFF), // blue + Color(0xFFFF3264), // hot pink + ], + stops: [0.161, 0.216, 0.410, 0.482, 0.723, 0.860, 0.938], + tables: colorfulTables, +); + +/// `BeamColors.mono`: whites and greys, with a fixed hue. +const BeamPalette monoPalette = BeamPalette( + colors: [ + Color(0xFFF0F0F0), // near white + Color(0xFF9E9E9E), // mid grey + Color(0xFFD2D2D2), // light grey + Color(0xFFB0B0B0), // grey + ], + stops: [0.161, 0.410, 0.723, 0.938], + fixedHue: true, + tables: monoTables, + mono: true, +); + +/// `BeamColors.ocean`: blues and violets. +const BeamPalette oceanPalette = BeamPalette( + colors: [ + Color(0xFF8C64F0), // lavender + Color(0xFF7754F8), // violet + Color(0xFF7850FF), // violet + Color(0xFF4682FF), // azure + Color(0xFF4B6DCC), // slate blue + Color(0xFF3C78FF), // blue + Color(0xFF6450DC), // indigo + ], + stops: [0.161, 0.216, 0.410, 0.482, 0.723, 0.860, 0.938], + tables: oceanTables, +); + +/// `BeamColors.sunset`: reds, oranges, and amber. +const BeamPalette sunsetPalette = BeamPalette( + colors: [ + Color(0xFFFF3C3C), // red + Color(0xFFFF6C41), // vermilion + Color(0xFFFF6450), // coral + Color(0xFFFFB43C), // amber + Color(0xFFFF8C3A), // orange + Color(0xFFFFA028), // tangerine + Color(0xFFFF5032), // scarlet + ], + stops: [0.161, 0.216, 0.410, 0.482, 0.723, 0.860, 0.938], + tables: sunsetTables, +); + +// ─── Extras ───────────────────────────────────────────────────────────────── + +/// `BeamColors.aurora`: teal, violet, and green — the northern lights. +const BeamPalette auroraPalette = BeamPalette( + colors: [ + Color(0xFF35E08A), // green + Color(0xFF25CFCD), // glacier teal + Color(0xFF1FD9C0), // teal + Color(0xFF7A5CFF), // violet + Color(0xFF34D8A1), // sea green + Color(0xFF7A5CFF), // violet + Color(0xFF1FD9C0), // teal + ], + stops: [0.161, 0.216, 0.410, 0.482, 0.723, 0.860, 0.938], + tableColors: auroraColors, +); + +/// `BeamColors.neon`: fully saturated magenta, lime, and cyan. +const BeamPalette neonPalette = BeamPalette( + colors: [ + Color(0xFFFF00C8), // magenta + Color(0xFFB6FF00), // lime + Color(0xFF00F0FF), // cyan + Color(0xFFB6FF00), // lime + Color(0xFF00F0FF), // cyan + Color(0xFFFF00C8), // magenta + ], + stops: [0.161, 0.216, 0.410, 0.482, 0.860, 0.938], + tableColors: neonColors, +); + +/// `BeamColors.candy`: pastel pink, lavender, and peach. +const BeamPalette candyPalette = BeamPalette( + colors: [ + Color(0xFFFF9EC4), // pink + Color(0xFFEFBFBF), // blush + Color(0xFFC5B3FF), // lavender + Color(0xFFFFC49B), // peach + Color(0xFFFFBDA4), // apricot + Color(0xFFC5B3FF), // lavender + Color(0xFFFF9EC4), // pink + ], + stops: [0.161, 0.216, 0.410, 0.482, 0.723, 0.860, 0.938], + tableColors: candyColors, +); + +/// `BeamColors.ember`: deep red, orange, and gold. +const BeamPalette emberPalette = BeamPalette( + colors: [ + Color(0xFFC1121F), // deep red + Color(0xFFFFAC2D), // amber + Color(0xFFFF6B1A), // orange + Color(0xFFFFC233), // gold + Color(0xFFF4AE30), // amber + Color(0xFFFF6B1A), // orange + Color(0xFFC1121F), // deep red + ], + stops: [0.161, 0.216, 0.410, 0.482, 0.723, 0.860, 0.938], + tableColors: emberColors, +); + +/// `BeamColors.ice`: pale blue, white, and cyan. +const BeamPalette icePalette = BeamPalette( + colors: [ + Color(0xFFBFE9FF), // pale blue + Color(0xFFA3EBFF), // frost + Color(0xFFFFFFFF), // white + Color(0xFF63E2FF), // cyan + Color(0xFF7BE3FF), // light cyan + Color(0xFFFFFFFF), // white + Color(0xFFBFE9FF), // pale blue + ], + stops: [0.161, 0.216, 0.410, 0.482, 0.723, 0.860, 0.938], + tableColors: iceColors, +); + +/// `BeamColors.gold`: amber, gold, and bronze, with a fixed hue. +const BeamPalette goldPalette = BeamPalette( + colors: [ + Color(0xFFFFC24B), // amber + Color(0xFFBE8529), // old gold + Color(0xFFE8A317), // gold + Color(0xFFA9762F), // bronze + Color(0xFFBD8936), // old gold + Color(0xFFE8A317), // gold + Color(0xFFFFC24B), // amber + ], + stops: [0.161, 0.216, 0.410, 0.482, 0.723, 0.860, 0.938], + fixedHue: true, + tableColors: goldColors, +); + +/// `BeamColors.holographic`: desaturated pastels built for a hue sweep. +const BeamPalette holographicPalette = BeamPalette( + colors: [ + Color(0xFFB8E6FF), // sky + Color(0xFFDAF0E1), // mint + Color(0xFFFFE9B8), // cream + Color(0xFFC9B8FF), // lilac + Color(0xFFF5D4E3), // blush + Color(0xFFB8E6FF), // sky + Color(0xFFC9B8FF), // lilac + ], + stops: [0.161, 0.216, 0.410, 0.482, 0.723, 0.860, 0.938], + tableColors: holographicColors, +); + +// ─── New in 0.2 ───────────────────────────────────────────────────────────── + +/// `BeamColors.lagoon`: teal, aqua, and mint — shallow tropical water. +const BeamPalette lagoonPalette = BeamPalette( + colors: [ + Color(0xFF00C2A8), // teal + Color(0xFF2BD9F0), // aqua + Color(0xFF7CF5C8), // mint + Color(0xFF0FA3C2), // deep aqua + ], + stops: [0.08, 0.32, 0.58, 0.82], +); + +/// `BeamColors.dusk`: indigo, violet, and rose — the sky after sundown. +const BeamPalette duskPalette = BeamPalette( + colors: [ + Color(0xFF5B5BF0), // indigo + Color(0xFF9B5CF6), // violet + Color(0xFFF0628F), // rose + Color(0xFFB45CE6), // orchid + ], + stops: [0.12, 0.36, 0.60, 0.84], +); + +/// `BeamColors.forest`: emerald, lime, and teal. +const BeamPalette forestPalette = BeamPalette( + colors: [ + Color(0xFF12C27E), // emerald + Color(0xFF8BD61C), // lime + Color(0xFF17B8A6), // teal + Color(0xFF3DDC6B), // leaf green + ], + stops: [0.10, 0.34, 0.60, 0.82], +); + +/// `BeamColors.rose`: pink, coral, and mauve. +const BeamPalette rosePalette = BeamPalette( + colors: [ + Color(0xFFFF6FB0), // pink + Color(0xFFFF7F66), // coral + Color(0xFFC77DC4), // mauve + Color(0xFFFF5C8D), // rose + ], + stops: [0.14, 0.40, 0.66, 0.88], +); + +/// `BeamColors.cosmic`: deep violet, electric blue, and magenta. +const BeamPalette cosmicPalette = BeamPalette( + colors: [ + Color(0xFF6B2BFF), // deep violet + Color(0xFF2D6BFF), // electric blue + Color(0xFF33A1FF), // bright blue + Color(0xFFF02BD9), // magenta + Color(0xFFA235F5), // purple + ], + stops: [0.06, 0.30, 0.52, 0.74, 0.92], +); + +/// `BeamColors.citrus`: lime, yellow, and tangerine. +const BeamPalette citrusPalette = BeamPalette( + colors: [ + Color(0xFF9EE021), // lime + Color(0xFFFFD000), // lemon + Color(0xFFFF8A1C), // tangerine + Color(0xFFFFB81F), // amber + ], + stops: [0.10, 0.36, 0.62, 0.86], +); + +/// `BeamColors.sky`: cerulean, periwinkle, and a white-blue. +const BeamPalette skyPalette = BeamPalette( + colors: [ + Color(0xFF1E9BFF), // cerulean + Color(0xFF8C9EFF), // periwinkle + Color(0xFFC6E4FF), // white-blue + Color(0xFF3FC3FF), // sky blue + ], + stops: [0.12, 0.38, 0.62, 0.84], +); + +/// `BeamColors.lavender`: lilac, lavender, and a soft pink. +const BeamPalette lavenderPalette = BeamPalette( + colors: [ + Color(0xFFC48DFF), // lilac + Color(0xFFA594FF), // lavender + Color(0xFFFFA6D5), // soft pink + Color(0xFFD69CFF), // orchid + ], + stops: [0.14, 0.40, 0.64, 0.86], +); diff --git a/lib/src/models/beam_segment.dart b/lib/src/models/beam_segment.dart index 12229ce..cf6d0a6 100644 --- a/lib/src/models/beam_segment.dart +++ b/lib/src/models/beam_segment.dart @@ -1,9 +1,9 @@ import 'package:flutter/foundation.dart'; -import '../painting/ring_geometry.dart'; +import '../render/beam_outline.dart'; import 'beam_options.dart'; -/// A corner of a beam contour, in clockwise order. +/// A corner of a beam's outline, in clockwise order. enum BeamCorner { /// The top-left corner. topLeft, @@ -18,7 +18,7 @@ enum BeamCorner { bottomLeft, } -/// A position on a beam's perimeter, resolved against its painted box. +/// A position on a beam's border, resolved against its outline. @immutable sealed class BeamAnchor { /// Creates an anchor at arc-length fraction [t], clockwise from top-center. @@ -50,8 +50,9 @@ sealed class BeamAnchor { /// The center of the left edge's straight run. static const BeamAnchor leftCenter = BeamAnchor.edge(BeamEdge.left); - /// Resolves this anchor to an arc-length fraction on [perimeter]. - double resolve(BeamPerimeter perimeter); + /// Resolves this anchor to a perimeter coordinate in `[0, 1)` on + /// [outline]: an arc-length fraction, clockwise from top-centre. + double resolve(BeamOutline outline); } final class _FractionAnchor extends BeamAnchor { @@ -60,7 +61,7 @@ final class _FractionAnchor extends BeamAnchor { final double t; @override - double resolve(BeamPerimeter perimeter) => t % 1 < 0 ? t % 1 + 1 : t % 1; + double resolve(BeamOutline outline) => BeamOutline.wrapFraction(t); @override bool operator ==(Object other) => @@ -80,7 +81,7 @@ final class _EdgeAnchor extends BeamAnchor { final double t; @override - double resolve(BeamPerimeter perimeter) => perimeter.fractionOfEdge(edge, t); + double resolve(BeamOutline outline) => outline.fractionOfEdge(edge, t); @override bool operator ==(Object other) => @@ -101,8 +102,7 @@ final class _CornerAnchor extends BeamAnchor { final double t; @override - double resolve(BeamPerimeter perimeter) => - perimeter.fractionOfCorner(corner, t); + double resolve(BeamOutline outline) => outline.fractionOfCorner(corner, t); @override bool operator ==(Object other) => @@ -118,16 +118,16 @@ final class _CornerAnchor extends BeamAnchor { /// A clockwise portion of the perimeter over which a beam is visible. /// -/// A segment masks an unchanged full-ring animation: constants and blob -/// positions never move. The traveling beam enters at [start] and leaves at -/// [end], the line variant travels the segment, and pulse blobs outside it -/// are hidden. Ends fade over [feather] logical pixels along the perimeter. +/// A segment masks an unchanged full-border animation: nothing is +/// repositioned to fit it. A travelling beam enters at [start] and leaves at +/// [end], and light outside the segment is hidden. Ends fade over [feather] +/// logical pixels along the border. /// /// A beam covering the lower half of a square runs from right-center, around /// the bottom, to left-center: /// /// ```dart -/// BorderBeam.rotate( +/// BorderBeam( /// shape: const BeamShape(segment: BeamSegment.bottomHalf), /// child: card, /// ) @@ -135,11 +135,8 @@ final class _CornerAnchor extends BeamAnchor { @immutable class BeamSegment { /// Creates the clockwise segment from [start] to [end]. - const BeamSegment({ - required this.start, - required this.end, - this.feather = 32, - }); + const BeamSegment({required this.start, required this.end, this.feather = 32}) + : assert(feather >= 0, 'feather must not be negative'); /// Where the clockwise visible portion begins. final BeamAnchor start; @@ -148,7 +145,8 @@ class BeamSegment { /// when its resolved fraction is smaller than [start]. final BeamAnchor end; - /// Logical pixels over which each end fades; zero makes a hard cut. + /// Logical pixels over which each end fades; zero makes a hard cut. Must + /// not be negative; at most half the segment's length is used. Default 32. final double feather; /// The lower half, from right-center through bottom-center to left-center. @@ -203,9 +201,11 @@ class BeamSegment { end: BeamAnchor.corner(BeamCorner.bottomRight, 1), ); - /// Returns this segment with all logical lengths scaled by [factor]. - BeamSegment scaledBy(double factor) => - BeamSegment(start: start, end: end, feather: feather * factor); + /// The perimeter coordinates of [start] and [end] on [outline], each in + /// `[0, 1)`. When `to` is smaller than `from` the segment wraps through + /// top-centre. + ({double from, double to}) resolve(BeamOutline outline) => + (from: start.resolve(outline), to: end.resolve(outline)); @override bool operator ==(Object other) => diff --git a/lib/src/models/beam_shape.dart b/lib/src/models/beam_shape.dart index feafa8c..ba31413 100644 --- a/lib/src/models/beam_shape.dart +++ b/lib/src/models/beam_shape.dart @@ -1,38 +1,39 @@ +/// @docImport 'package:flutter/widgets.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; -import 'beam_options.dart'; import 'beam_segment.dart'; -/// The geometry of a beam: its corner radii, ring thickness, corner family -/// (circular arcs or superellipse), how far the ring sits from the child, -/// and which edge the line variant rides. +/// The geometry of a beam's outline: its corner radii and corner family +/// (circular arcs or superellipse), the stroke thickness, how far the outline +/// sits from the child, and which part of it is lit. /// /// Every field is nullable and means *inherit*. A field is resolved in this /// order: the value set on the widget (the `borderRadius` shorthand wins over -/// [radius]), then the nearest `BorderBeamTheme`, then the variant's preset -/// (radius 16, or 32 for `BeamVariant.small`; border width 1). +/// [radius]), then the nearest `BorderBeamTheme`, then the default (radius +/// 16, border width 1, ring offset 0, circular corners, the whole border, +/// solid). /// /// ```dart -/// BorderBeam.rotate( +/// BorderBeam( /// shape: const BeamShape.all(24, superellipse: true), /// child: card, /// ) /// ``` @immutable class BeamShape { - /// Creates a shape with per-corner [radius]. Every omitted field is + /// Creates a shape with per-corner `radius`. Every omitted field is /// inherited. const BeamShape({ - BorderRadiusGeometry? radius, - this.borderWidth, + this._radius, this.superellipse, - this.edge, + this.borderWidth, this.ringOffset, - this.contour, this.segment, - this.wrapCorners, - }) : _radius = radius, + this.dashes, + }) : assert(dashes == null || dashes >= 0, 'dashes must not be negative'), _uniformRadius = null; /// A shape whose four corners share one radius — the const path. @@ -40,17 +41,16 @@ class BeamShape { /// The number is stored as given and grown into a [BorderRadius] where /// [radius] is read, which is what keeps the constructor const: building a /// [BorderRadius] from a parameter is a runtime construction. `all` and - /// [circular] compare equal for the same number. + /// [BeamShape.circular] compare equal for the same number. const BeamShape.all( double radius, { - this.borderWidth, this.superellipse, - this.edge, + this.borderWidth, this.ringOffset, - this.contour, this.segment, - this.wrapCorners, - }) : _uniformRadius = radius, + this.dashes, + }) : assert(dashes == null || dashes >= 0, 'dashes must not be negative'), + _uniformRadius = radius, _radius = null; /// A shape whose four corners share one [radius], built as a @@ -61,107 +61,98 @@ class BeamShape { /// [BorderRadius] terms. BeamShape.circular( double radius, { - this.borderWidth, this.superellipse, - this.edge, + this.borderWidth, this.ringOffset, - this.contour, this.segment, - this.wrapCorners, - }) : _radius = BorderRadius.circular(radius), + this.dashes, + }) : assert(dashes == null || dashes >= 0, 'dashes must not be negative'), + _radius = BorderRadius.circular(radius), _uniformRadius = null; /// A pill: each corner rounds to half the shortest side of the box, so a /// square box comes out a circle. /// - /// The radius is infinite and the ring geometry clamps it per corner, which - /// is what makes it track the box as it resizes. + /// The radius is infinite and the outline clamps it per corner, which is + /// what makes it track the box as it resizes. const BeamShape.stadium({ - this.borderWidth, this.superellipse, - this.edge, + this.borderWidth, this.ringOffset, - this.contour, this.segment, - this.wrapCorners, - }) : _radius = const BorderRadius.all(Radius.circular(double.infinity)), + this.dashes, + }) : assert(dashes == null || dashes >= 0, 'dashes must not be negative'), + _radius = const BorderRadius.all(Radius.circular(double.infinity)), _uniformRadius = null; + /// The corner radius used when no [radius] is set anywhere. + static const double defaultRadius = 16; + final BorderRadiusGeometry? _radius; final double? _uniformRadius; - /// Corner radii of the beam contour, direction-aware. + /// Corner radii of the outline, direction-aware. Default 16 on every + /// corner. /// /// Resolved against the ambient [Directionality] (or LTR when there is /// none), then clamped per corner the way [RRect.scaleRadii] does: when two /// radii on one side exceed that side's length, all four scale down by the /// smallest offending ratio. Match your child's decoration radius — the /// beam does not read it. - /// - /// Ignored when [contour] is set. BorderRadiusGeometry? get radius { final uniform = _uniformRadius; return uniform == null ? _radius : BorderRadius.circular(uniform); } - /// Stroke ring thickness in logical px. Default 1, as in the source. - final double? borderWidth; - - /// Whether the contour is a rounded superellipse (an Apple-style squircle) - /// instead of circular corner arcs. - /// - /// Defaults to false, matching the circular-arc corners of the source - /// library's CSS `border-radius`. Ignored when [contour] is set. + /// Whether the corners are superellipse curves (an Apple-style squircle, + /// matching `RoundedSuperellipseBorder`) instead of circular arcs. + /// Default false. final bool? superellipse; - /// Which edge the line variant's beam travels along. Default - /// [BeamEdge.bottom], as in the source. The other variants ignore it. - final BeamEdge? edge; + /// Stroke thickness in logical px. Default 1. + final double? borderWidth; - /// Logical px the ring is pushed outward (positive) or pulled inward + /// Logical px the outline is pushed outward (positive) or pulled inward /// (negative) from the child's bounds, so the beam can orbit at a distance - /// or tuck inside a padded surface. Default 0 — the ring sits on the + /// or tuck inside a padded surface. Default 0 — the outline sits on the /// bounds. final double? ringOffset; - /// An arbitrary contour for the beam to travel instead of the rounded - /// rectangle built from [radius]. + /// The clockwise portion of the border on which the beam is visible. /// - /// Default null. When set, [radius] and [superellipse] are ignored — the - /// path the contour builds is the whole geometry. - final BeamContour? contour; + /// Null inherits, resolving to the whole border. + final BeamSegment? segment; - /// The clockwise portion of the contour on which the beam is visible. + /// Breaks the border into this many evenly spaced dashes. /// - /// Null inherits, resolving to the full ring. - final BeamSegment? segment; + /// Null, 0, and 1 keep the border solid (the default); 2 or more paints + /// that many dashes. Must not be negative. + final int? dashes; - /// Whether line-variant blobs use border-path space and bend around - /// corners instead of continuing straight past an edge. + /// [radius] resolved against [textDirection], or [defaultRadius] on every + /// corner when it is unset. /// - /// Null inherits, resolving to false. - final bool? wrapCorners; + /// The result is not yet clamped to a box — the outline does that. + BorderRadius resolveRadius(TextDirection textDirection) => + radius?.resolve(textDirection) ?? + const BorderRadius.all(Radius.circular(defaultRadius)); /// Returns a copy with the given fields replaced. A null argument keeps the /// current value; build a new [BeamShape] to clear a field back to inherit. BeamShape copyWith({ BorderRadiusGeometry? radius, - double? borderWidth, bool? superellipse, - BeamEdge? edge, + double? borderWidth, double? ringOffset, - BeamContour? contour, BeamSegment? segment, - bool? wrapCorners, + int? dashes, }) => BeamShape( radius: radius ?? this.radius, - borderWidth: borderWidth ?? this.borderWidth, superellipse: superellipse ?? this.superellipse, - edge: edge ?? this.edge, + borderWidth: borderWidth ?? this.borderWidth, ringOffset: ringOffset ?? this.ringOffset, - contour: contour ?? this.contour, segment: segment ?? this.segment, - wrapCorners: wrapCorners ?? this.wrapCorners, + dashes: dashes ?? this.dashes, ); /// Layers [other] over this shape: every non-null field of [other] wins, @@ -170,13 +161,11 @@ class BeamShape { ? this : copyWith( radius: other.radius, - borderWidth: other.borderWidth, superellipse: other.superellipse, - edge: other.edge, + borderWidth: other.borderWidth, ringOffset: other.ringOffset, - contour: other.contour, segment: other.segment, - wrapCorners: other.wrapCorners, + dashes: other.dashes, ); @override @@ -184,37 +173,31 @@ class BeamShape { identical(this, other) || other is BeamShape && other.radius == radius && - other.borderWidth == borderWidth && other.superellipse == superellipse && - other.edge == edge && + other.borderWidth == borderWidth && other.ringOffset == ringOffset && - other.contour == contour && other.segment == segment && - other.wrapCorners == wrapCorners; + other.dashes == dashes; @override int get hashCode => Object.hash( radius, - borderWidth, superellipse, - edge, + borderWidth, ringOffset, - contour, segment, - wrapCorners, + dashes, ); @override String toString() { final fields = [ if (radius != null) 'radius: $radius', - if (borderWidth != null) 'borderWidth: $borderWidth', if (superellipse != null) 'superellipse: $superellipse', - if (edge != null) 'edge: $edge', + if (borderWidth != null) 'borderWidth: $borderWidth', if (ringOffset != null) 'ringOffset: $ringOffset', - if (contour != null) 'contour: $contour', if (segment != null) 'segment: $segment', - if (wrapCorners != null) 'wrapCorners: $wrapCorners', + if (dashes != null) 'dashes: $dashes', ]; return 'BeamShape(${fields.join(', ')})'; } diff --git a/lib/src/models/beam_style.dart b/lib/src/models/beam_style.dart index 68d68ba..038ff48 100644 --- a/lib/src/models/beam_style.dart +++ b/lib/src/models/beam_style.dart @@ -1,22 +1,19 @@ import 'package:flutter/foundation.dart'; -import '../constants/pulse_constants.dart'; import 'beam_colors.dart'; import 'beam_options.dart'; import 'beam_theme.dart'; -import 'beam_theme_config.dart'; -/// How a beam looks: its colors, how it adapts to the background, the shape -/// of its beam and glow, and every filter and layer-opacity hook ported from -/// the source's CSS custom properties. +/// How a beam looks: its colours, how it adapts to the background, how +/// strongly it glows, and how its colours drift. /// /// Every field is nullable and means *inherit*. A field is resolved in this /// order: the value set on the widget (a shorthand such as `colors:` wins /// over the same field of the widget's own style), then the nearest -/// `BorderBeamTheme`, then the variant's preset. +/// `BorderBeamTheme`, then the effect's default. /// /// ```dart -/// BorderBeam.rotate( +/// BorderBeam( /// style: const BeamStyle(colors: BeamColors.ocean, strength: 0.6), /// child: card, /// ) @@ -28,241 +25,63 @@ class BeamStyle { this.colors, this.theme, this.strength, - this.brightness, - this.saturation, - this.hueRange, + this.glow, + this.hueShift, this.hueMode, this.hueBase, - this.staticColors, - this.strokeOpacityFactor, - this.innerOpacityFactor, - this.bloomOpacityFactor, - this.glowBoost, - this.coreBlur, - this.bloomBlur, - this.glowBrightness, - this.glowSaturation, - this.tailLength, - this.glowSpread, - this.comet, - this.sparkle, - this.segments, - this.innerSizeScale, - this.renderScale, - this.pulseOutsideTuning, - this.themeConfig, - }); + }) : assert(glow == null || glow >= 0, 'glow must not be negative'); - /// The pulse-outside look as the React library ships it, before the demo - /// page's tuning. - /// - /// `BorderBeam.pulseOutside` paints the tuned demo recipe by default — the - /// look beam.jakubantalik.com is known for. This style rolls every part of - /// that tuning back: the prominence boost, insets, blurs, and size-derived - /// unit through [pulseOutsideTuning], and the glow multiplier through the - /// three opacity factors and [glowBrightness]/[glowSaturation]. - /// - /// The result is a tighter, dimmer halo that sits closer to the child. - /// - /// ```dart - /// BorderBeam.pulseOutside( - /// style: BeamStyle.pulseOutsideStock, - /// child: card, - /// ) - /// ``` - /// - /// Layer your own fields over it with [copyWith] or [merge]; anything you - /// set wins, so `BeamStyle.pulseOutsideStock.copyWith(glowBoost: 1.4)` - /// keeps the stock geometry and enlarges both its foreground and glow - /// blobs from the same neutral baseline. - static const BeamStyle pulseOutsideStock = BeamStyle( - strokeOpacityFactor: 1 / pulseOuterTunedGlowMultiplier, - innerOpacityFactor: 1 / pulseOuterTunedGlowMultiplier, - bloomOpacityFactor: 1 / pulseOuterTunedGlowMultiplier, - glowBoost: 1, - glowBrightness: pulseOuterGlowBrightness, - glowSaturation: pulseOuterGlowSaturation, - pulseOutsideTuning: BeamPulseOutsideTuning.stock, - ); - - /// Color scheme: a preset, [BeamColors.custom], or [BeamColors.spec]. - /// Defaults to [BeamColors.colorful]. + /// The palette painted around the border. Defaults to + /// [BeamColors.colorful]. final BeamColors? colors; /// Background adaptation: dark, light, or follow the ambient theme. /// Defaults to [BeamTheme.auto]. final BeamTheme? theme; - /// Effect opacity 0–1 (clamped). Scales only the beam layers. Default 1. + /// Overall opacity of the beam, 0–1 (clamped). Default 1. final double? strength; - /// Glow brightness multiplier; inherits the variant/theme preset. - final double? brightness; + /// Multiplies the size and intensity of every glow around the border; the + /// crisp stroke is unaffected. Must not be negative; 0 leaves only the + /// stroke. Default 1. + final double? glow; - /// Glow saturation multiplier; inherits the variant/theme preset. - final double? saturation; - - /// Hue animation amplitude in degrees (default 30; the line variant caps it - /// at 13). Not used by pulse variants, whose hue cycles continuously. - final double? hueRange; + /// How far, in degrees either side, the hue swings under + /// [BeamHueMode.pingPong]. Default 30. + /// + /// Ignored by [BeamHueMode.continuous] and [BeamHueMode.none]. + final double? hueShift; - /// Whether the hue swings back and forth across ±[hueRange] or advances - /// through one continuous 360° revolution. + /// How the colours drift over time. Defaults to the effect's own choice + /// (`BeamEffect.defaultHueMode`). /// - /// Defaults to [BeamHueMode.pingPong] for the traveling variants and - /// [BeamHueMode.continuous] for the pulse variants, matching the source. + /// Palettes with a fixed hue ([BeamColors.mono], [BeamColors.gold]) never + /// drift, whatever this says. final BeamHueMode? hueMode; - /// Static hue offset in degrees added to the whole palette. Default 0. + /// A static hue rotation, in degrees, applied to the whole palette on top + /// of any drift. Default 0. final double? hueBase; - /// Disables the hue animation. Default false; forced on by - /// [BeamColors.mono]. - final bool? staticColors; - - /// Stroke ring opacity multiplier (React `--beam-stroke-opacity`). - /// Default 1. - final double? strokeOpacityFactor; - - /// Inner glow opacity multiplier (React `--beam-inner-opacity`). Default 1. - final double? innerOpacityFactor; - - /// Bloom opacity multiplier (React `--beam-bloom-opacity`). Default 1. - final double? bloomOpacityFactor; - - /// Pulse glow prominence multiplier (React `--pulse-glow-boost`). - /// Default 1. - final double? glowBoost; - - /// pulse-outside core glow blur override in px (React `--beam-core-blur`). - final double? coreBlur; - - /// pulse-outside halo blur override in px (React `--beam-bloom-blur`). - final double? bloomBlur; - - /// pulse-outside glow brightness override - /// (React `--beam-glow-brightness`). - final double? glowBrightness; - - /// pulse-outside glow saturation override (React `--beam-glow-saturate`). - final double? glowSaturation; - - /// Multiplier on the angular width of the rotate/small traveling window: - /// above 1 the beam drags a longer tail behind its head, below 1 it - /// shortens to a point. Default 1. - final double? tailLength; - - /// Multiplier on how far the bloom and halo layers reach past the stroke - /// ring: above 1 the glow spreads wider and softer, below 1 it hugs the - /// border. Default 1. - final double? glowSpread; - - /// Whether a soft halo trails the traveling head outside the ring, giving - /// the rotate and small beams a comet tail. Default false. - final bool? comet; - - /// Density 0–1 (clamped) of the twinkles scattered at the traveling beam's - /// head. Default 0 — no sparkle. - final double? sparkle; - - /// Number of dashes the ring is broken into, spaced evenly around the - /// contour. Null (the default) keeps the ring solid. - final int? segments; - - /// Multiplier on the size of the pulse-inside inner wash — its blobs and - /// its corner accents. Default 1. - /// - /// Below 1 the wash pulls tighter to the border, leaving more of the child - /// clear; above 1 it floods further in. The perimeter ring and the bloom - /// keep their own geometry, so the border itself does not move. - /// - /// Only `BeamVariant.pulseInside` paints that layer; every other variant - /// ignores this. - final double? innerSizeScale; - - /// The fraction of the box the beam is *painted* at before being scaled - /// back up to fill it, 0.25–1 (clamped). Default 1 — no rescaling. - /// - /// The palettes are authored against a 350×140 card, so on a - /// screen-width box the blobs read as small and sparse. Painting at, say, - /// `0.5` and magnifying restores the proportions the palette was drawn - /// for: the glow, its blurs, and the corner radii all grow together, so - /// the beam reads the same at any size. - /// - /// It costs nothing — one canvas transform, no extra layer — but it is a - /// magnification, so the ring's own edge softens as the factor drops. - final double? renderScale; - - /// Which pulse-outside glow geometry to paint: the demo recipe (the - /// default) or the source's stock table. - /// - /// [BeamStyle.pulseOutsideStock] is the whole stock look; this field alone - /// changes only the insets and blurs. - final BeamPulseOutsideTuning? pulseOutsideTuning; - - /// Replaces the whole variant×brightness preset (layer opacities, inset - /// shadow, and the default brightness/saturation) with your own. - /// - /// [brightness] and [saturation] still override on top of it. Start from - /// [BeamThemeConfig.presetFor] to tweak a single field of a preset. - final BeamThemeConfig? themeConfig; - /// Returns a copy with the given fields replaced. A null argument keeps the /// current value; build a new [BeamStyle] to clear a field back to inherit. BeamStyle copyWith({ BeamColors? colors, BeamTheme? theme, double? strength, - double? brightness, - double? saturation, - double? hueRange, + double? glow, + double? hueShift, BeamHueMode? hueMode, double? hueBase, - bool? staticColors, - double? strokeOpacityFactor, - double? innerOpacityFactor, - double? bloomOpacityFactor, - double? glowBoost, - double? coreBlur, - double? bloomBlur, - double? glowBrightness, - double? glowSaturation, - double? tailLength, - double? glowSpread, - bool? comet, - double? sparkle, - int? segments, - double? innerSizeScale, - double? renderScale, - BeamPulseOutsideTuning? pulseOutsideTuning, - BeamThemeConfig? themeConfig, }) => BeamStyle( colors: colors ?? this.colors, theme: theme ?? this.theme, strength: strength ?? this.strength, - brightness: brightness ?? this.brightness, - saturation: saturation ?? this.saturation, - hueRange: hueRange ?? this.hueRange, + glow: glow ?? this.glow, + hueShift: hueShift ?? this.hueShift, hueMode: hueMode ?? this.hueMode, hueBase: hueBase ?? this.hueBase, - staticColors: staticColors ?? this.staticColors, - strokeOpacityFactor: strokeOpacityFactor ?? this.strokeOpacityFactor, - innerOpacityFactor: innerOpacityFactor ?? this.innerOpacityFactor, - bloomOpacityFactor: bloomOpacityFactor ?? this.bloomOpacityFactor, - glowBoost: glowBoost ?? this.glowBoost, - coreBlur: coreBlur ?? this.coreBlur, - bloomBlur: bloomBlur ?? this.bloomBlur, - glowBrightness: glowBrightness ?? this.glowBrightness, - glowSaturation: glowSaturation ?? this.glowSaturation, - tailLength: tailLength ?? this.tailLength, - glowSpread: glowSpread ?? this.glowSpread, - comet: comet ?? this.comet, - sparkle: sparkle ?? this.sparkle, - segments: segments ?? this.segments, - innerSizeScale: innerSizeScale ?? this.innerSizeScale, - renderScale: renderScale ?? this.renderScale, - pulseOutsideTuning: pulseOutsideTuning ?? this.pulseOutsideTuning, - themeConfig: themeConfig ?? this.themeConfig, ); /// Layers [other] over this style: every non-null field of [other] wins, @@ -273,29 +92,10 @@ class BeamStyle { colors: other.colors, theme: other.theme, strength: other.strength, - brightness: other.brightness, - saturation: other.saturation, - hueRange: other.hueRange, + glow: other.glow, + hueShift: other.hueShift, hueMode: other.hueMode, hueBase: other.hueBase, - staticColors: other.staticColors, - strokeOpacityFactor: other.strokeOpacityFactor, - innerOpacityFactor: other.innerOpacityFactor, - bloomOpacityFactor: other.bloomOpacityFactor, - glowBoost: other.glowBoost, - coreBlur: other.coreBlur, - bloomBlur: other.bloomBlur, - glowBrightness: other.glowBrightness, - glowSaturation: other.glowSaturation, - tailLength: other.tailLength, - glowSpread: other.glowSpread, - comet: other.comet, - sparkle: other.sparkle, - segments: other.segments, - innerSizeScale: other.innerSizeScale, - renderScale: other.renderScale, - pulseOutsideTuning: other.pulseOutsideTuning, - themeConfig: other.themeConfig, ); @override @@ -305,59 +105,14 @@ class BeamStyle { other.colors == colors && other.theme == theme && other.strength == strength && - other.brightness == brightness && - other.saturation == saturation && - other.hueRange == hueRange && + other.glow == glow && + other.hueShift == hueShift && other.hueMode == hueMode && - other.hueBase == hueBase && - other.staticColors == staticColors && - other.strokeOpacityFactor == strokeOpacityFactor && - other.innerOpacityFactor == innerOpacityFactor && - other.bloomOpacityFactor == bloomOpacityFactor && - other.glowBoost == glowBoost && - other.coreBlur == coreBlur && - other.bloomBlur == bloomBlur && - other.glowBrightness == glowBrightness && - other.glowSaturation == glowSaturation && - other.tailLength == tailLength && - other.glowSpread == glowSpread && - other.comet == comet && - other.sparkle == sparkle && - other.segments == segments && - other.innerSizeScale == innerSizeScale && - other.renderScale == renderScale && - other.pulseOutsideTuning == pulseOutsideTuning && - other.themeConfig == themeConfig; + other.hueBase == hueBase; @override - int get hashCode => Object.hashAll([ - colors, - theme, - strength, - brightness, - saturation, - hueRange, - hueMode, - hueBase, - staticColors, - strokeOpacityFactor, - innerOpacityFactor, - bloomOpacityFactor, - glowBoost, - coreBlur, - bloomBlur, - glowBrightness, - glowSaturation, - tailLength, - glowSpread, - comet, - sparkle, - segments, - innerSizeScale, - renderScale, - pulseOutsideTuning, - themeConfig, - ]); + int get hashCode => + Object.hash(colors, theme, strength, glow, hueShift, hueMode, hueBase); @override String toString() { @@ -365,30 +120,10 @@ class BeamStyle { if (colors != null) 'colors: $colors', if (theme != null) 'theme: $theme', if (strength != null) 'strength: $strength', - if (brightness != null) 'brightness: $brightness', - if (saturation != null) 'saturation: $saturation', - if (hueRange != null) 'hueRange: $hueRange', + if (glow != null) 'glow: $glow', + if (hueShift != null) 'hueShift: $hueShift', if (hueMode != null) 'hueMode: $hueMode', if (hueBase != null) 'hueBase: $hueBase', - if (staticColors != null) 'staticColors: $staticColors', - if (strokeOpacityFactor != null) - 'strokeOpacityFactor: $strokeOpacityFactor', - if (innerOpacityFactor != null) 'innerOpacityFactor: $innerOpacityFactor', - if (bloomOpacityFactor != null) 'bloomOpacityFactor: $bloomOpacityFactor', - if (glowBoost != null) 'glowBoost: $glowBoost', - if (coreBlur != null) 'coreBlur: $coreBlur', - if (bloomBlur != null) 'bloomBlur: $bloomBlur', - if (glowBrightness != null) 'glowBrightness: $glowBrightness', - if (glowSaturation != null) 'glowSaturation: $glowSaturation', - if (tailLength != null) 'tailLength: $tailLength', - if (glowSpread != null) 'glowSpread: $glowSpread', - if (comet != null) 'comet: $comet', - if (sparkle != null) 'sparkle: $sparkle', - if (segments != null) 'segments: $segments', - if (innerSizeScale != null) 'innerSizeScale: $innerSizeScale', - if (renderScale != null) 'renderScale: $renderScale', - if (pulseOutsideTuning != null) 'pulseOutsideTuning: $pulseOutsideTuning', - if (themeConfig != null) 'themeConfig: $themeConfig', ]; return 'BeamStyle(${fields.join(', ')})'; } diff --git a/lib/src/models/beam_theme.dart b/lib/src/models/beam_theme.dart index e35a2d5..f2dd118 100644 --- a/lib/src/models/beam_theme.dart +++ b/lib/src/models/beam_theme.dart @@ -2,7 +2,7 @@ import 'dart:ui'; /// How the beam adapts to the surrounding background. enum BeamTheme { - /// Tuned for dark backgrounds (the React default). + /// Tuned for dark backgrounds. dark, /// Tuned for light backgrounds. diff --git a/lib/src/models/beam_theme_config.dart b/lib/src/models/beam_theme_config.dart deleted file mode 100644 index 19833fa..0000000 --- a/lib/src/models/beam_theme_config.dart +++ /dev/null @@ -1,115 +0,0 @@ -import 'dart:ui'; - -import '../constants/theme_presets.dart'; -import 'beam_variant.dart'; - -/// Theme-and-variant-tuned layer opacities and filter multipliers. -/// -/// Direct port of the React library's `ThemeColors` entries in -/// `sizeThemePresets`: each beam variant has one config per brightness. Reach -/// for [presetFor] to start from a built-in preset, [copyWith] the one field -/// you want moved, and hand the result to `BeamStyle.themeConfig`. -/// -/// ```dart -/// BorderBeam.rotate( -/// style: BeamStyle( -/// themeConfig: BeamThemeConfig.presetFor( -/// BeamVariant.rotate, -/// Brightness.dark, -/// ).copyWith(bloomOpacity: 0.4), -/// ), -/// child: card, -/// ) -/// ``` -class BeamThemeConfig { - /// Creates a theme config. - const BeamThemeConfig({ - required this.strokeOpacity, - required this.innerOpacity, - required this.bloomOpacity, - required this.innerShadow, - required this.saturation, - this.brightness, - this.hairlineOpacity, - }); - - /// The built-in preset for [variant] at [brightness]. - static BeamThemeConfig presetFor( - BeamVariant variant, - Brightness brightness, - ) => themePresetFor(variant, brightness); - - /// Opacity of the stroke ring layer. May exceed 1 (intentional overdrive - /// in the source, e.g. line/dark = 1.14); the painted product is clamped. - final double strokeOpacity; - - /// Opacity of the inner glow layer. - final double innerOpacity; - - /// Opacity of the bloom layer. - final double bloomOpacity; - - /// Color of the inset shadow on the inner glow layer - /// ([Color(0x00000000)] i.e. transparent for pulse variants). - final Color innerShadow; - - /// Default saturation filter multiplier. - final double saturation; - - /// Default brightness filter multiplier; null falls back to 1.3. - final double? brightness; - - /// Opacity of the static 1px hairline (pulse-outside only; preset 0 so the - /// wrapped child's own border provides the idle edge). - final double? hairlineOpacity; - - /// Returns a copy with the given fields replaced. A null argument keeps the - /// current value. - BeamThemeConfig copyWith({ - double? strokeOpacity, - double? innerOpacity, - double? bloomOpacity, - Color? innerShadow, - double? saturation, - double? brightness, - double? hairlineOpacity, - }) => BeamThemeConfig( - strokeOpacity: strokeOpacity ?? this.strokeOpacity, - innerOpacity: innerOpacity ?? this.innerOpacity, - bloomOpacity: bloomOpacity ?? this.bloomOpacity, - innerShadow: innerShadow ?? this.innerShadow, - saturation: saturation ?? this.saturation, - brightness: brightness ?? this.brightness, - hairlineOpacity: hairlineOpacity ?? this.hairlineOpacity, - ); - - @override - bool operator ==(Object other) => - identical(this, other) || - other is BeamThemeConfig && - other.strokeOpacity == strokeOpacity && - other.innerOpacity == innerOpacity && - other.bloomOpacity == bloomOpacity && - other.innerShadow == innerShadow && - other.saturation == saturation && - other.brightness == brightness && - other.hairlineOpacity == hairlineOpacity; - - @override - int get hashCode => Object.hash( - strokeOpacity, - innerOpacity, - bloomOpacity, - innerShadow, - saturation, - brightness, - hairlineOpacity, - ); - - @override - String toString() => - 'BeamThemeConfig(strokeOpacity: $strokeOpacity, ' - 'innerOpacity: $innerOpacity, bloomOpacity: $bloomOpacity, ' - 'innerShadow: $innerShadow, saturation: $saturation, ' - 'brightness: $brightness, hairlineOpacity: $hairlineOpacity)'; -} diff --git a/lib/src/models/beam_timing.dart b/lib/src/models/beam_timing.dart index 75be6b5..9dac4da 100644 --- a/lib/src/models/beam_timing.dart +++ b/lib/src/models/beam_timing.dart @@ -3,15 +3,15 @@ import 'package:flutter/foundation.dart'; import 'beam_options.dart'; /// How fast a beam moves: cycle length, the rest between sweeps, playback -/// rate, travel direction, and the periods of the tracks that do not ride -/// the cycle. +/// rate, travel direction, starting phase, and the period of the colour +/// drift. /// /// Every field is nullable and means *inherit*. A field is resolved in this /// order: the value set on the widget, then the nearest `BorderBeamTheme`, -/// then the variant's preset. +/// then the effect's default. /// /// ```dart -/// BorderBeam.rotate( +/// BorderBeam( /// timing: const BeamTiming( /// cycle: Duration(seconds: 3), /// cycleGap: Duration(seconds: 1), @@ -28,12 +28,7 @@ class BeamTiming { this.speed, this.direction, this.phaseOffset, - this.beamCount, this.huePeriod, - this.bloomHuePeriod, - this.breatheFactor, - this.spikeFactor, - this.spike2Factor, }) : assert( speed == null || (speed > 0 && speed < double.infinity), 'speed must be finite and positive', @@ -41,57 +36,39 @@ class BeamTiming { assert( phaseOffset == null || (phaseOffset >= 0 && phaseOffset <= 1), 'phaseOffset must be between 0 and 1', - ), - assert( - beamCount == null || beamCount >= 1, - 'beamCount must be at least 1', - ), - assert( - breatheFactor == null || - (breatheFactor > 0 && breatheFactor < double.infinity), - 'breatheFactor must be finite and positive', - ), - assert( - spikeFactor == null || - (spikeFactor > 0 && spikeFactor < double.infinity), - 'spikeFactor must be finite and positive', - ), - assert( - spike2Factor == null || - (spike2Factor > 0 && spike2Factor < double.infinity), - 'spike2Factor must be finite and positive', ); - /// Length of one animation cycle. Defaults to the variant preset: 1.96s for - /// rotate and small, 3.1s for line, 2.3s for the pulse variants. + /// Length of one animation cycle: one sweep of a travelling effect, one + /// breath or revolution of an ambient one. The default depends on the + /// effect (`BeamEffect.defaultCycle`). /// - /// Changing it while the beam runs retimes the animation in place: every - /// track keeps the phase it was at, so the beam speeds up or slows down - /// without a jump. + /// Changing it while the beam runs retimes the animation in place: the + /// beam keeps the phase it was at and speeds up or slows down without a + /// jump. final Duration? cycle; - /// Rest between sweeps: after each cycle the beam parks at the end of its - /// travel and fades away for this long before the next sweep starts. - /// Default [Duration.zero] — one sweep runs straight into the next. + /// Rest between sweeps: after each cycle a travelling effect parks at the + /// end of its travel and fades away for this long before the next sweep + /// starts. Defaults to the effect's `BeamEffect.defaultCycleGap` — zero, + /// so one sweep runs straight into the next. /// - /// The fade at each end of the gap takes `min(0.25s, gap / 2)`. Hue, - /// breathe, and spike tracks are textures rather than the sweep, so they - /// keep running through the gap. - /// - /// The pulse variants ignore it: their breathing has no cycle boundary to - /// rest at. Changing it needs no retime — the sweep keeps its position and - /// the gap simply appears at the next cycle end. + /// The colour drift keeps running through the gap. Ambient effects ignore + /// it: their motion has no cycle boundary to rest at. Changing it while the + /// beam runs keeps the sweep where it is; the new rest takes effect at the + /// next cycle end. final Duration? cycleGap; - /// Playback rate multiplier; must be positive. Default 1. + /// Playback rate multiplier; must be finite and positive. Default 1. /// - /// Ignored while a `BorderBeamController` is attached — the controller's - /// own `speed` owns the rate then. + /// Scales the animation only: the fades in and out take the same time at + /// any rate. Ignored while a `BorderBeamController` is attached — the + /// controller's own `speed` owns the rate then — and a + /// `BorderBeam.speedListenable` wins over both. final double? speed; - /// Which way the beam travels: clockwise (or left-to-right for the line - /// variant), mirrored, or alternating each cycle. Default - /// [BeamDirection.forward]. The pulse variants have no travel to direct. + /// Which way a travelling effect moves: clockwise (left-to-right for the + /// line effect), mirrored, or alternating each cycle. Default + /// [BeamDirection.forward]. Ambient effects have no travel to direct. final BeamDirection? direction; /// Fraction of a cycle, 0–1, the timeline starts at, so two beams on the @@ -99,52 +76,16 @@ class BeamTiming { /// beginning. final double? phaseOffset; - /// How many beams travel the contour at once, spaced equally along the - /// cycle. Must be at least 1; default 1. - final int? beamCount; - - /// One full period of the hue track. + /// One full period of the colour drift: a swing across ±`hueShift` under + /// `BeamHueMode.pingPong`, or a 360° revolution under + /// `BeamHueMode.continuous`. The default depends on the effect + /// (`BeamEffect.defaultHuePeriod`). /// - /// Defaults to 12s for rotate, small, and line (a ping-pong across - /// ±`hueRange`), and to the pulse presets' own periods — 16s for - /// pulse-inside, 14s for pulse-outside (a continuous revolution). Setting - /// it overrides the period for every variant. - /// - /// Changing it mid-run re-phases the hue track — see [breatheFactor]. + /// Changing it mid-run **re-phases the drift**: it resumes at + /// `elapsed / newPeriod` rather than holding the fraction it had, so the + /// colours jump once and then continue smoothly. final Duration? huePeriod; - /// Period of the line variant's separate bloom hue track, a ping-pong - /// across ±(`hueRange` + 10)°. Default 8s. - /// - /// Changing it mid-run re-phases the bloom hue track — see [breatheFactor]. - final Duration? bloomHuePeriod; - - /// The line beam's height-breathe period, as a multiple of [cycle]. - /// Default 1.3. - /// - /// Changing a track's own period mid-run **re-phases that track**: it - /// resumes at `elapsed / newPeriod` rather than holding the fraction it - /// had, so the line's height jumps once and then continues smoothly. The - /// in-place retiming [cycle] documents is a different thing — it rescales - /// elapsed time, which every cycle-derived track (this one included) rides - /// through without a jump. There is no way to change a period *and* keep - /// its phase, because the two describe different animations; the same - /// applies to [spikeFactor], [spike2Factor], [huePeriod], and - /// [bloomHuePeriod]. Set these once, or accept the single step. - final double? breatheFactor; - - /// The line beam's first spike-scale period, as a multiple of [cycle]. - /// Default 1.33. - /// - /// Changing it mid-run re-phases the spike track — see [breatheFactor]. - final double? spikeFactor; - - /// The line beam's second spike-scale period, as a multiple of [cycle]. - /// Default 1.7. - /// - /// Changing it mid-run re-phases the spike track — see [breatheFactor]. - final double? spike2Factor; - /// Returns a copy with the given fields replaced. A null argument keeps the /// current value; build a new [BeamTiming] to clear a field back to /// inherit. @@ -154,24 +95,14 @@ class BeamTiming { double? speed, BeamDirection? direction, double? phaseOffset, - int? beamCount, Duration? huePeriod, - Duration? bloomHuePeriod, - double? breatheFactor, - double? spikeFactor, - double? spike2Factor, }) => BeamTiming( cycle: cycle ?? this.cycle, cycleGap: cycleGap ?? this.cycleGap, speed: speed ?? this.speed, direction: direction ?? this.direction, phaseOffset: phaseOffset ?? this.phaseOffset, - beamCount: beamCount ?? this.beamCount, huePeriod: huePeriod ?? this.huePeriod, - bloomHuePeriod: bloomHuePeriod ?? this.bloomHuePeriod, - breatheFactor: breatheFactor ?? this.breatheFactor, - spikeFactor: spikeFactor ?? this.spikeFactor, - spike2Factor: spike2Factor ?? this.spike2Factor, ); /// Layers [other] over this timing: every non-null field of [other] wins, @@ -184,12 +115,7 @@ class BeamTiming { speed: other.speed, direction: other.direction, phaseOffset: other.phaseOffset, - beamCount: other.beamCount, huePeriod: other.huePeriod, - bloomHuePeriod: other.bloomHuePeriod, - breatheFactor: other.breatheFactor, - spikeFactor: other.spikeFactor, - spike2Factor: other.spike2Factor, ); @override @@ -201,27 +127,11 @@ class BeamTiming { other.speed == speed && other.direction == direction && other.phaseOffset == phaseOffset && - other.beamCount == beamCount && - other.huePeriod == huePeriod && - other.bloomHuePeriod == bloomHuePeriod && - other.breatheFactor == breatheFactor && - other.spikeFactor == spikeFactor && - other.spike2Factor == spike2Factor; + other.huePeriod == huePeriod; @override - int get hashCode => Object.hashAll([ - cycle, - cycleGap, - speed, - direction, - phaseOffset, - beamCount, - huePeriod, - bloomHuePeriod, - breatheFactor, - spikeFactor, - spike2Factor, - ]); + int get hashCode => + Object.hash(cycle, cycleGap, speed, direction, phaseOffset, huePeriod); @override String toString() { @@ -231,12 +141,7 @@ class BeamTiming { if (speed != null) 'speed: $speed', if (direction != null) 'direction: $direction', if (phaseOffset != null) 'phaseOffset: $phaseOffset', - if (beamCount != null) 'beamCount: $beamCount', if (huePeriod != null) 'huePeriod: $huePeriod', - if (bloomHuePeriod != null) 'bloomHuePeriod: $bloomHuePeriod', - if (breatheFactor != null) 'breatheFactor: $breatheFactor', - if (spikeFactor != null) 'spikeFactor: $spikeFactor', - if (spike2Factor != null) 'spike2Factor: $spike2Factor', ]; return 'BeamTiming(${fields.join(', ')})'; } diff --git a/lib/src/models/beam_variant.dart b/lib/src/models/beam_variant.dart deleted file mode 100644 index bab3ef8..0000000 --- a/lib/src/models/beam_variant.dart +++ /dev/null @@ -1,66 +0,0 @@ -import 'dart:ui'; - -import '../constants/pulse_params.dart'; - -/// The five beam effect variants, matching the React library's `size` prop. -/// -/// Rotate family (a traveling beam sweeps around the border): -/// - [rotate] — full border glow for cards and large surfaces (React `md`). -/// - [small] — compact glow tuned for buttons and icons (React `sm`). -/// - [line] — a beam that travels along the bottom edge (React `line`). -/// -/// Pulse family (a breathing glow, no rotation): -/// - [pulseInside] — contained breathing border glow (React `pulse-inner`). -/// - [pulseOutside] — outward-blooming halo behind the child -/// (React `pulse-outside`). -enum BeamVariant { - /// Full border traveling beam (React `md`). The default look. - rotate, - - /// Compact traveling beam for small elements (React `sm`). - small, - - /// Bottom-edge traveling beam (React `line`). - line, - - /// Contained breathing glow (React `pulse-inner`). - pulseInside, - - /// Outward-blooming breathing halo (React `pulse-outside`). - pulseOutside; - - /// Whether this variant uses the breathing (oscillator-driven) engine - /// instead of the traveling-beam engine. - bool get isPulse => this == pulseInside || this == pulseOutside; - - /// Default duration of one animation cycle, matching the React defaults - /// (1.96s for rotate/small, 3.1s for line, 2.3s for pulse). - Duration get defaultCycleDuration => switch (this) { - rotate || small => const Duration(milliseconds: 1960), - line => const Duration(milliseconds: 3100), - pulseInside || pulseOutside => const Duration(milliseconds: 2300), - }; - - /// Default border radius preset (React `sizePresets`). - double get defaultBorderRadius => this == small ? 32 : 16; - - /// Default border (stroke ring) width preset. All variants use 1px. - double get defaultBorderWidth => 1; - - /// Default period of one full hue track pass: 12s for the traveling - /// variants, 16s for [pulseInside], 14s for [pulseOutside]. - /// - /// The pulse periods come from [PulseParams], which tunes them by neither - /// brightness nor cycle length — the arguments below only satisfy that - /// signature. - Duration get defaultHuePeriod => isPulse - ? _seconds(PulseParams.resolve(this, Brightness.dark, 2.3).huePeriod) - : const Duration(seconds: 12); - - /// Default period of the [line] variant's separate bloom hue track: 8s. - /// No other variant paints a bloom hue track of its own. - Duration get defaultBloomHuePeriod => const Duration(seconds: 8); -} - -Duration _seconds(double value) => - Duration(microseconds: (value * Duration.microsecondsPerSecond).round()); diff --git a/lib/src/models/model_validation.dart b/lib/src/models/model_validation.dart index 99d850e..40c5876 100644 --- a/lib/src/models/model_validation.dart +++ b/lib/src/models/model_validation.dart @@ -1,4 +1,7 @@ +import 'dart:ui'; + import 'beam_options.dart'; +import 'beam_palette.dart'; import 'beam_timing.dart'; /// Runtime counterpart to [BeamTiming]'s constructor assertions. @@ -37,36 +40,24 @@ void validateBeamTiming(BeamTiming timing) { timing.phaseOffset, 'must be finite and between 0 and 1', ); - require( - timing.beamCount == null || timing.beamCount! >= 1, - 'beamCount', - timing.beamCount, - 'must be at least 1', - ); require( timing.huePeriod == null || timing.huePeriod! > Duration.zero, 'huePeriod', timing.huePeriod, 'must be positive', ); - require( - timing.bloomHuePeriod == null || timing.bloomHuePeriod! > Duration.zero, - 'bloomHuePeriod', - timing.bloomHuePeriod, - 'must be positive', - ); - for (final (name, value) in [ - ('breatheFactor', timing.breatheFactor), - ('spikeFactor', timing.spikeFactor), - ('spike2Factor', timing.spike2Factor), - ]) { - require( - value == null || (value.isFinite && value > 0), - name, - value, - 'must be finite and positive', - ); +} + +/// Returns [speed] when it is finite and positive, and throws otherwise, +/// including in release builds. [name] labels the argument in the error. +/// +/// A playback rate multiplies the timeline every frame, so a NaN, an +/// infinity, or a non-positive rate would poison every phase it feeds. +double validateSpeed(double speed, String name) { + if (!speed.isFinite || speed <= 0) { + throw ArgumentError.value(speed, name, 'must be finite and positive'); } + return speed; } /// Returns a valid repeat budget, including in release builds. @@ -82,14 +73,34 @@ int? validateRepeat(BeamRepeat? repeat) { return cycles; } -/// Rejects an empty color table, including in release builds. +/// Rejects a malformed palette, including in release builds. /// /// `BeamColors` is a const hierarchy, so its constructors cannot assert on a -/// list's length; resolution checks it instead. Every pulse layer reads its -/// color through `index % table.length`, which would otherwise fail as an -/// `IntegerDivisionByZeroException` deep inside a paint strategy. -void validateColorTable(int length, String name) { - if (length < 1) { - throw ArgumentError.value(length, name, 'must contain at least one entry'); +/// list's length; resolution checks it instead. A palette needs 1 to +/// [maxPaletteStops] colors and one stop per color, each finite, in +/// `[0, 1)`, and ascending (equal neighbours make a hard edge). +void validatePalette(List colors, List stops, String name) { + if (colors.isEmpty || colors.length > maxPaletteStops) { + throw ArgumentError.value( + colors.length, + '$name colors', + 'must contain 1 to $maxPaletteStops entries', + ); + } + if (stops.length != colors.length) { + throw ArgumentError.value( + stops.length, + '$name stops', + 'must contain one stop per color (${colors.length})', + ); + } + for (var i = 0; i < stops.length; i++) { + final s = stops[i]; + if (!s.isFinite || s < 0 || s >= 1) { + throw ArgumentError.value(s, '$name stops[$i]', 'must be in [0, 1)'); + } + if (i > 0 && s < stops[i - 1]) { + throw ArgumentError.value(s, '$name stops[$i]', 'must not descend'); + } } } diff --git a/lib/src/painting/beam_painter.dart b/lib/src/painting/beam_painter.dart deleted file mode 100644 index 97a557a..0000000 --- a/lib/src/painting/beam_painter.dart +++ /dev/null @@ -1,179 +0,0 @@ -import 'package:flutter/foundation.dart'; -import 'package:flutter/rendering.dart'; - -import '../animation/beam_clock.dart'; -import '../animation/beam_phases.dart'; -import '../models/beam_config.dart'; -import '../models/beam_variant.dart'; -import 'strategies/line_strategy.dart'; -import 'strategies/pulse_inner_strategy.dart'; -import 'strategies/pulse_outer_strategy.dart'; -import 'strategies/rotate_strategy.dart'; -import 'variant_strategy.dart'; - -/// Resolves the strategy singleton for a variant. -BeamVariantStrategy strategyFor(BeamVariant variant) => switch (variant) { - BeamVariant.rotate => const RotateStrategy(compact: false), - BeamVariant.small => const RotateStrategy(compact: true), - BeamVariant.line => const LineStrategy(), - BeamVariant.pulseInside => const PulseInnerStrategy(), - BeamVariant.pulseOutside => const PulseOuterStrategy(), -}; - -/// The beam's [CustomPainter]. One instance paints either the behind-child -/// pass or the above-child pass of its strategy; repaints are driven -/// directly by the [BeamClock] (no widget rebuilds per frame). -class BeamPainter extends CustomPainter with Diagnosticable { - /// Creates a painter bound to [clock]. - BeamPainter({ - required this.clock, - required this.config, - required this.resolver, - required this.strategy, - required this.behind, - required this.staticMode, - this.progress, - this.strength, - this.frozenAt, - }) : super(repaint: Listenable.merge([clock, ?progress, ?strength])); - - /// The time source; also the repaint trigger. - final BeamClock clock; - - /// Resolved beam configuration. - final BeamConfig config; - - /// Phase computer (owns the oscillator bank). - final BeamPhaseResolver resolver; - - /// The variant strategy. - final BeamVariantStrategy strategy; - - /// Whether this instance paints the behind-child pass. - final bool behind; - - /// Reduced-motion mode: paint one static frame, ignore the clock. - final bool staticMode; - - /// The externally driven sweep position (0–1), or null when nothing - /// drives it. - /// - /// Held as a listenable rather than a value so `BorderBeam.progress` and - /// `BorderBeam.follow` can move the beam without rebuilding the config. - final ValueListenable? progress; - - /// A per-frame multiplier on every layer's opacity, or null for none. - /// - /// `BorderBeam.strengthListenable`, the live twin of `BeamStyle.strength`: - /// it repaints without rebuilding, and the reduced-motion static frame - /// ignores it along with the rest of the clock. - final ValueListenable? strength; - - /// The timeline position every frame is sampled at, or null to follow the - /// clock. - /// - /// `BeamPlayback.debugFrozenAt`: the beam paints that one instant of the - /// timeline forever, which is what makes a screenshot of it reproducible. - /// The instant carries its own point on the fade envelope and is still - /// scaled by the live [strength], so a strength below 1 dims the frozen - /// frame the way it dims a running one. It lives on the painter rather - /// than on the config because it changes no painted value — only which - /// moment of the timeline is read — so a config cached across a freeze is - /// still the right config. - final Duration? frozenAt; - - // The config the strategies actually paint with: at renderScale 1 it is - // the config itself, and below that the same beam re-authored for the - // smaller box the canvas transform magnifies back up. - late final BeamConfig _paintConfig = config.renderScale >= 1 - ? config - : config.scaledBy(config.renderScale); - - @override - void paint(Canvas canvas, Size size) { - final driven = progress?.value; - final BeamFramePhases phases; - final frozen = frozenAt; - if (frozen != null) { - phases = resolver.sample( - frozen.inMicroseconds / Duration.microsecondsPerSecond, - strength?.value ?? 1, - progress: driven, - ); - } else if (staticMode) { - phases = resolver.staticFrame(progress: driven); - } else { - if (!clock.isVisible) return; - // The boost and the live strength both scale every layer, and layer - // opacity is clamped at paint time — so they ride in on the fade - // rather than needing a channel of their own. - final amplitude = clock.boost * (strength?.value ?? 1); - phases = resolver.sample( - clock.elapsedSeconds, - clock.fadeOpacity * amplitude, - progress: driven, - ); - } - final scale = config.renderScale; - if (scale >= 1) { - _paintPass(canvas, size, config, phases); - return; - } - // One transform, no layer: the beam is drawn into a box `scale` the size - // of the real one and magnified back about the origin, so it lands - // exactly on the box's bounds. Blur sigmas ride the canvas, so they grow - // with everything else. - canvas.save(); - canvas.scale(1 / scale); - _paintPass( - canvas, - Size(size.width * scale, size.height * scale), - _paintConfig, - phases, - ); - canvas.restore(); - } - - void _paintPass( - Canvas canvas, - Size size, - BeamConfig painted, - BeamFramePhases phases, - ) { - if (behind) { - strategy.paintBehind(canvas, size, painted, phases); - } else { - strategy.paintAbove(canvas, size, painted, phases); - } - } - - @override - bool shouldRepaint(BeamPainter oldDelegate) => - oldDelegate.config != config || - oldDelegate.strategy != strategy || - oldDelegate.behind != behind || - oldDelegate.staticMode != staticMode || - oldDelegate.clock != clock || - oldDelegate.progress != progress || - oldDelegate.strength != strength || - oldDelegate.frozenAt != frozenAt; - - @override - void debugFillProperties(DiagnosticPropertiesBuilder properties) { - super.debugFillProperties(properties); - properties - ..add(DiagnosticsProperty('config', config)) - ..add(FlagProperty('behind', value: behind, ifTrue: 'behind child')) - ..add( - FlagProperty('staticMode', value: staticMode, ifTrue: 'static frame'), - ) - ..add(DoubleProperty('elapsedSeconds', clock.elapsedSeconds)) - ..add(DoubleProperty('fadeOpacity', clock.fadeOpacity)) - ..add(DoubleProperty('boost', clock.boost, defaultValue: 1.0)) - ..add(DoubleProperty('progress', progress?.value, defaultValue: null)) - ..add(DoubleProperty('strength', strength?.value, defaultValue: null)) - ..add( - DiagnosticsProperty('frozenAt', frozenAt, defaultValue: null), - ); - } -} diff --git a/lib/src/painting/color_matrix.dart b/lib/src/painting/color_matrix.dart deleted file mode 100644 index 9c414c6..0000000 --- a/lib/src/painting/color_matrix.dart +++ /dev/null @@ -1,135 +0,0 @@ -import 'dart:math' as math; -import 'dart:ui'; - -/// Color-matrix math for the CSS `hue-rotate() brightness() saturate()` -/// filter chain. -/// -/// Two consumption modes: -/// - [BeamColorMatrix.toColorFilter] for layers that must be filtered after -/// compositing (the blurred blooms), and -/// - [BeamColorMatrix.transform] to fold the filter into gradient colors on -/// the CPU (9–14 colors per layer per frame), which lets the traveling -/// variants skip a per-layer `saveLayer` entirely. -/// -/// Matrices are 4×5 row-major lists as accepted by [ColorFilter.matrix] -/// (RGBA in 0–255 space; the offset column is unused here). -class BeamColorMatrix { - BeamColorMatrix._(this._m); - - /// Identity filter. - factory BeamColorMatrix.identity() => BeamColorMatrix._(_identity()); - - /// The CSS chain `hue-rotate(degrees) brightness(b) saturate(s)`, applied - /// in that order (matching the source library's filter strings). - factory BeamColorMatrix.beamFilter({ - required double hueDegrees, - required double brightness, - required double saturation, - }) { - var m = _hueRotate(hueDegrees); - if (brightness != 1) m = _multiply(_brightness(brightness), m); - if (saturation != 1) m = _multiply(_saturate(saturation), m); - return BeamColorMatrix._(m); - } - - final List _m; - - /// Whether this matrix is a no-op. - bool get isIdentity { - const id = [ - 1.0, 0.0, 0.0, 0.0, 0.0, // - 0.0, 1.0, 0.0, 0.0, 0.0, // - 0.0, 0.0, 1.0, 0.0, 0.0, // - 0.0, 0.0, 0.0, 1.0, 0.0, - ]; - for (var i = 0; i < 20; i++) { - if ((_m[i] - id[i]).abs() > 1e-9) return false; - } - return true; - } - - /// This matrix as a [ColorFilter]. - ColorFilter toColorFilter() => ColorFilter.matrix(_m); - - /// Applies the matrix to a single color on the CPU. Alpha is preserved - /// (the matrix has an identity alpha row). Channels are clamped to 0–1, - /// matching how the GPU filter saturates. - Color transform(Color c) { - final r = _m[0] * c.r + _m[1] * c.g + _m[2] * c.b; - final g = _m[5] * c.r + _m[6] * c.g + _m[7] * c.b; - final b = _m[10] * c.r + _m[11] * c.g + _m[12] * c.b; - return Color.from( - alpha: c.a, - red: r.clamp(0.0, 1.0), - green: g.clamp(0.0, 1.0), - blue: b.clamp(0.0, 1.0), - ); - } - - static List _identity() => [ - 1, 0, 0, 0, 0, // - 0, 1, 0, 0, 0, // - 0, 0, 1, 0, 0, // - 0, 0, 0, 1, 0, - ]; - - // SVG feColorMatrix hueRotate (the same matrix CSS hue-rotate() is - // specified against), luminance coefficients 0.213/0.715/0.072. - static List _hueRotate(double degrees) { - final rad = degrees * math.pi / 180; - final c = math.cos(rad); - final s = math.sin(rad); - return [ - 0.213 + c * 0.787 - s * 0.213, - 0.715 - c * 0.715 - s * 0.715, - 0.072 - c * 0.072 + s * 0.928, - 0, - 0, - 0.213 - c * 0.213 + s * 0.143, - 0.715 + c * 0.285 + s * 0.140, - 0.072 - c * 0.072 - s * 0.283, - 0, - 0, - 0.213 - c * 0.213 - s * 0.787, - 0.715 - c * 0.715 + s * 0.715, - 0.072 + c * 0.928 + s * 0.072, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - ]; - } - - static List _saturate(double s) => [ - 0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0, 0, // - 0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0, 0, // - 0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0, 0, // - 0, 0, 0, 1, 0, - ]; - - static List _brightness(double b) => [ - b, 0, 0, 0, 0, // - 0, b, 0, 0, 0, // - 0, 0, b, 0, 0, // - 0, 0, 0, 1, 0, - ]; - - // 4×5 row-major multiply: result = a ∘ b (b applied first). - static List _multiply(List a, List b) { - final out = List.filled(20, 0); - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 5; col++) { - var v = 0.0; - for (var k = 0; k < 4; k++) { - v += a[row * 5 + k] * b[k * 5 + col]; - } - if (col == 4) v += a[row * 5 + 4]; - out[row * 5 + col] = v; - } - } - return out; - } -} diff --git a/lib/src/painting/gradient_builders.dart b/lib/src/painting/gradient_builders.dart deleted file mode 100644 index 029c4e0..0000000 --- a/lib/src/painting/gradient_builders.dart +++ /dev/null @@ -1,336 +0,0 @@ -import 'dart:math' as math; -import 'dart:typed_data'; -import 'dart:ui' as ui; -import 'dart:ui'; - -/// Shader/paint helpers translating the CSS gradient vocabulary of the source -/// library to Flutter canvas primitives. -abstract final class BeamGradients { - /// A CSS `conic-gradient(from ...)` equivalent. - /// - /// CSS conic gradients start at 12 o'clock and run clockwise; - /// [ui.Gradient.sweep] starts at 3 o'clock — a constant −90° rotation - /// aligns them. [cssFromRadians] is the CSS `from` angle (the rotating - /// beam angle). - static Shader conic({ - required Rect rect, - required double cssFromRadians, - required List colors, - required List stops, - }) { - final center = rect.center; - final rotation = cssFromRadians - math.pi / 2; - final matrix = Matrix4Rotation.aboutPoint(rotation, center); - return ui.Gradient.sweep( - center, - colors, - stops, - TileMode.clamp, - 0, - 2 * math.pi, - matrix, - ); - } - - /// Paints one radial ellipse blob: fades from [color] at the center to - /// fully transparent at the ellipse edge (CSS - /// `radial-gradient(ellipse Wpx Hpx at x y, color, transparent)` — W/H are - /// the ellipse radii). - /// - /// [center] is in canvas coordinates; [radiusX]/[radiusY] in logical px. - /// [alpha] scales the blob color's opacity (pulse quadrant breathing). - static void paintBlob( - Canvas canvas, { - required Offset center, - required double radiusX, - required double radiusY, - required Color color, - double alpha = 1, - double rotation = 0, - }) { - final rx = math.max(radiusX, 0.01); - final ry = math.max(radiusY, 0.01); - final c = alpha >= 1 ? color : color.withValues(alpha: color.a * alpha); - if (c.a <= 0) return; - // Circular gradient of radius rx, scaled vertically to ry about center. - final matrix = ellipseTransform(center, ry / rx, rotation); - final shader = ui.Gradient.radial( - center, - rx, - [c, c.withValues(alpha: 0)], - const [0, 1], - TileMode.clamp, - matrix, - ); - final extent = rotation == 0 ? null : math.max(rx, ry); - canvas.drawRect( - Rect.fromCenter( - center: center, - width: (extent ?? rx) * 2, - height: (extent ?? ry) * 2, - ), - Paint()..shader = shader, - ); - } - - /// The vertical edge-feather mask of the source's inner glow layers: - /// opaque at the top/bottom edges, transparent [feather] px inward - /// (CSS `linear-gradient(white, transparent 28px, transparent - /// calc(100% - 28px), white)`). - static Shader verticalEdgeFeather(Rect rect, {double feather = 28}) { - final f = (feather / rect.height).clamp(0.0, 0.5); - return ui.Gradient.linear( - rect.topCenter, - rect.bottomCenter, - [ - _white, - _white.withValues(alpha: 0), - _white.withValues(alpha: 0), - _white, - ], - [0, f, 1 - f, 1], - ); - } - - /// The horizontal edge-feather mask (left/right edges). - static Shader horizontalEdgeFeather(Rect rect, {double feather = 28}) { - final f = (feather / rect.width).clamp(0.0, 0.5); - return ui.Gradient.linear( - rect.centerLeft, - rect.centerRight, - [ - _white, - _white.withValues(alpha: 0), - _white.withValues(alpha: 0), - _white, - ], - [0, f, 1 - f, 1], - ); - } - - /// A radial window mask (line variant): white at [center], fading through - /// [midAlpha] at [midStop] to transparent at the ellipse edge. - static Shader radialWindow({ - required Offset center, - required double radiusX, - required double radiusY, - required double midStop, - required double midAlpha, - double rotation = 0, - }) { - final rx = math.max(radiusX, 0.01); - final ry = math.max(radiusY, 0.01); - final matrix = ellipseTransform(center, ry / rx, rotation); - return ui.Gradient.radial( - center, - rx, - [_white, _white.withValues(alpha: midAlpha), _white.withValues(alpha: 0)], - [0, midStop, 1], - TileMode.clamp, - matrix, - ); - } - - /// A conic dash mask: [segments] evenly spaced dashes around the ring, - /// drawn with [BlendMode.dstIn] to cut the gaps out of a layer. - /// - /// [duty] is the fraction of each dash period the dash occupies and - /// [feather] the fraction faded at each of its two edges, so the dashes end - /// in a soft taper rather than a hard chop. The mask is anchored at 12 - /// o'clock rather than at the beam angle: the dashes are a property of the - /// ring, and the beam travels over them. - static Shader segmentMask( - Rect rect, - int segments, { - double duty = 0.6, - double feather = 0.05, - }) { - final n = math.max(1, segments); - final p = 1 / n; - final stops = []; - final colors = []; - void stop(double s, double alpha) { - stops.add(s.clamp(0.0, 1.0)); - colors.add(_white.withValues(alpha: alpha)); - } - - for (var k = 0; k < n; k++) { - final base = k * p; - stop(base, 1); - stop(base + (duty - feather) * p, 1); - stop(base + (duty + feather) * p, 0); - stop(base + (1 - feather) * p, 0); - } - stop(1, 1); - return conic(rect: rect, cssFromRadians: 0, colors: colors, stops: stops); - } - - static const Color _white = Color(0xFFFFFFFF); - - /// Scales a circular radial shader into an ellipse and rotates its width - /// axis by [rotation] around [center]. - /// - /// The zero-rotation matrix is intentionally the historical matrix byte - /// for byte, so callers that do not opt into path-space painting retain - /// their existing raster output. - static Float64List ellipseTransform( - Offset center, - double yScale, - double rotation, - ) { - if (rotation == 0) { - return Float64List.fromList([ - 1, 0, 0, 0, // - 0, yScale, 0, 0, // - 0, 0, 1, 0, // - 0, center.dy - center.dy * yScale, 0, 1, - ]); - } - final c = math.cos(rotation); - final s = math.sin(rotation); - final m0 = c; - final m1 = s; - final m4 = -s * yScale; - final m5 = c * yScale; - return Float64List.fromList([ - m0, m1, 0, 0, // - m4, m5, 0, 0, // - 0, 0, 1, 0, // - center.dx - m0 * center.dx - m4 * center.dy, - center.dy - m1 * center.dx - m5 * center.dy, - 0, - 1, - ]); - } -} - -/// A conic gradient's stop table: parallel stop and alpha lists, as the -/// rotate/small variants transcribe them from the source's CSS. -typedef BeamConicTable = ({List stops, List alphas}); - -/// Runtime transforms of the transcribed conic window tables. -/// -/// The tables themselves are constants and never change; travel direction, -/// tail length, and beam count reshape them per frame instead. -abstract final class BeamConicWindow { - /// Applies [tailLength], [reversed], and [beamCount] to a base table, in - /// that order. - /// - /// Returns the base lists untouched at the defaults (tail 1, forward, one - /// beam), so the common path allocates nothing. - static BeamConicTable resolve( - List stops, - List alphas, { - required bool reversed, - required double tailLength, - required int beamCount, - }) { - var table = scaleTail((stops: stops, alphas: alphas), tailLength); - if (reversed) table = mirror(table); - return repeat(table, beamCount); - } - - /// Mirrors a table for a beam traveling the other way: every stop becomes - /// `1 − stop` (which reverses their order, so the list is reversed to stay - /// ascending) and the alphas reverse with them. - /// - /// The transcribed tables are asymmetric — a short falloff on the leading - /// side, a long soft foot trailing — so a reversed beam that reused them - /// verbatim would drag its tail in front of its head. - static BeamConicTable mirror(BeamConicTable table) => ( - stops: [for (final s in table.stops.reversed) 1 - s], - alphas: table.alphas.reversed.toList(growable: false), - ); - - /// Scales the angular width of the window about its head by [factor]. - /// - /// The head is the leading edge of the bright core — the last stop holding - /// the table's maximum alpha — so scaling about it stretches the trailing - /// tail and the short leading falloff together while the beam's position - /// stays put. - /// - /// [factor] is clamped to what the table can hold: a window may not grow - /// past the full turn, or its two ends would collide at the seam and cut - /// the beam in half. The rotate window saturates at ≈1.33×, its highlight - /// and bloom bands (which start narrower) well past 2×. - static BeamConicTable scaleTail(BeamConicTable table, double factor) { - if (factor == 1 || table.stops.length < 3) return table; - final head = _head(table); - final (lo, hi) = _support(table); - final backSpan = head - lo; - final frontSpan = hi - head; - var maxFactor = double.infinity; - if (backSpan > 0) maxFactor = math.min(maxFactor, head / backSpan); - if (frontSpan > 0) maxFactor = math.min(maxFactor, (1 - head) / frontSpan); - final f = factor.clamp(0.05, math.max(0.05, maxFactor)); - return ( - stops: [ - for (final s in table.stops) - (head + (s - head) * f).clamp(0.0, 1.0).toDouble(), - ], - alphas: table.alphas, - ); - } - - /// Tiles a table [count] times around the circle, so one sweep shader - /// carries every beam: each copy's stops are scaled by `1 / count` and - /// offset into its own slot. - static BeamConicTable repeat(BeamConicTable table, int count) { - if (count <= 1) return table; - final stops = []; - final alphas = []; - for (var k = 0; k < count; k++) { - for (var i = 0; i < table.stops.length; i++) { - stops.add((table.stops[i] + k) / count); - alphas.add(table.alphas[i]); - } - } - return (stops: stops, alphas: alphas); - } - - // The last stop carrying the table's peak alpha: the leading edge of the - // bright core. - static double _head(BeamConicTable table) { - var peak = table.alphas.first; - for (final a in table.alphas) { - if (a > peak) peak = a; - } - var head = table.stops.first; - for (var i = 0; i < table.alphas.length; i++) { - if (table.alphas[i] >= peak) head = table.stops[i]; - } - return head; - } - - // The zero-alpha stops flanking the lit band — the width the window - // actually occupies, ignoring the table's 0 and 1 anchors. - static (double lo, double hi) _support(BeamConicTable table) { - var first = 0; - while (first < table.alphas.length - 1 && table.alphas[first + 1] <= 0) { - first++; - } - var last = table.alphas.length - 1; - while (last > 0 && table.alphas[last - 1] <= 0) { - last--; - } - return (table.stops[first], table.stops[last]); - } -} - -/// Small helper building a rotation matrix (as the `Float64List` gradient -/// transform) about an arbitrary point. -abstract final class Matrix4Rotation { - /// Rotation by [radians] about [point]. - static Float64List aboutPoint(double radians, Offset point) { - final c = math.cos(radians); - final s = math.sin(radians); - final dx = point.dx - point.dx * c + point.dy * s; - final dy = point.dy - point.dx * s - point.dy * c; - return Float64List.fromList([ - c, s, 0, 0, // - -s, c, 0, 0, // - 0, 0, 1, 0, // - dx, dy, 0, 1, - ]); - } -} diff --git a/lib/src/painting/layer_utils.dart b/lib/src/painting/layer_utils.dart deleted file mode 100644 index fce77d8..0000000 --- a/lib/src/painting/layer_utils.dart +++ /dev/null @@ -1,302 +0,0 @@ -import 'dart:math' as math; -import 'dart:ui' as ui; -import 'dart:ui'; - -import '../models/beam_config.dart'; -import 'gradient_builders.dart'; -import 'ring_geometry.dart'; - -/// Shared painting helpers used by every variant strategy. -abstract final class BeamLayerUtils { - /// The final opacity of one decorative layer: the product of the fade - /// envelope, the theme preset value, the mono multiplier, the consumer - /// hook factor, and strength — clamped like CSS clamps effective opacity - /// (the line/dark preset intentionally exceeds 1). - static double layerOpacity( - BeamConfig config, { - required double fade, - required double preset, - required double hookFactor, - double extra = 1, - }) { - final v = - fade * - preset * - config.palette.opacityMultiplier * - hookFactor * - config.strength * - extra; - return v.clamp(0.0, 1.0); - } - - /// The source's `attenuateSpike`: multiplies an existing alpha by - /// [factor], or assigns [factor] as the alpha of an opaque color. - static Color attenuateSpike(Color c, double factor) => - c.a < 1 ? c.withValues(alpha: c.a * factor) : c.withValues(alpha: factor); - - /// Sets [alpha] as the color's alpha (the source's `withAlpha`). - static Color withAlpha(Color c, double alpha) => c.withValues(alpha: alpha); - - /// Paints a multi-stop radial ellipse (CSS - /// `radial-gradient(ellipse RXpx RYpx at cx cy, ...stops)`). - static void paintRadial( - Canvas canvas, { - required Offset center, - required double radiusX, - required double radiusY, - required List colors, - required List stops, - double rotation = 0, - }) { - final rx = math.max(radiusX, 0.01); - final ry = math.max(radiusY, 0.01); - final matrix = BeamGradients.ellipseTransform(center, ry / rx, rotation); - final shader = ui.Gradient.radial( - center, - rx, - colors, - stops, - TileMode.clamp, - matrix, - ); - final extent = rotation == 0 ? null : math.max(rx, ry); - canvas.drawRect( - Rect.fromCenter( - center: center, - width: (extent ?? rx) * 2, - height: (extent ?? ry) * 2, - ), - Paint()..shader = shader, - ); - } - - /// Clips an existing layer scope to the configured perimeter segment. - /// - /// Call this after `canvas.save()` and before `saveLayer`. A null segment - /// deliberately performs no canvas operation, preserving the legacy paint - /// path exactly. - static void clipSegment( - Canvas canvas, - BeamRingGeometry geometry, { - required double inward, - required double outward, - }) { - if (geometry.segment == null) return; - canvas.clipPath( - segmentBandPath(geometry, inward: inward, outward: outward), - ); - } - - /// The band covering [geometry]'s segment, reaching [inward] px toward the - /// interior and [outward] px away from it. - /// - /// A contour offset inward by more than its local radius of curvature folds - /// back through the centre of that curvature: at a rounded corner the - /// offset arc reverses, sweeps across the far side of the segment, and — as - /// one polygon under the non-zero fill rule — both loses the interior it - /// was meant to cover and punches a spurious wedge where the two reversed - /// arcs cross. Each sample's inward depth is therefore capped at that - /// radius, which collapses a corner's inner boundary onto its own centre - /// instead of past it, leaving a simple polygon. - /// - /// Only the inward direction can fold — growing a convex contour outward - /// never does — so an [inward] of zero or less takes the perimeter's own - /// sampler unchanged. - static Path segmentBandPath( - BeamRingGeometry geometry, { - required double inward, - required double outward, - }) { - final range = geometry.segmentRange; - if (range == null || inward <= 0) { - return geometry.segmentBand(inward: inward, outward: outward); - } - final perimeter = geometry.perimeter; - final length = perimeter.length; - if (length <= 0) return Path(); - - final start = _fraction(range.from); - var span = _fraction(range.to - start); - if (span == 0) span = 1; - // Matches BeamPerimeter.band's sampling: ~2 logical px between samples. - final steps = math.max(8, (span * length / 2).ceil()); - final step = span * length / steps; - - final points = []; - final normals = []; - for (var i = 0; i <= steps; i++) { - final fraction = start + span * i / steps; - points.add(perimeter.pointAt(fraction)); - normals.add(perimeter.normalAt(fraction)); - } - - final result = Path() - ..moveTo( - points.first.dx + normals.first.dx * outward, - points.first.dy + normals.first.dy * outward, - ); - for (var i = 1; i < points.length; i++) { - result.lineTo( - points[i].dx + normals[i].dx * outward, - points[i].dy + normals[i].dy * outward, - ); - } - for (var i = points.length - 1; i >= 0; i--) { - final depth = math.min(inward, _curvatureRadius(normals, step, i)); - result.lineTo( - points[i].dx - normals[i].dx * depth, - points[i].dy - normals[i].dy * depth, - ); - } - return result..close(); - } - - // How far sample [i] may be offset inward before the offset curve reverses: - // an outward normal turning by phi over an arc length [step] puts the centre - // of curvature step/phi inward. A normal that turns the other way (a concave - // stretch) curves away from the interior and never folds, so it is - // unbounded. - static double _curvatureRadius(List normals, double step, int i) { - var radius = double.infinity; - for (final j in [i - 1, i + 1]) { - if (j < 0 || j >= normals.length) continue; - final (a, b) = i < j - ? (normals[i], normals[j]) - : (normals[j], normals[i]); - final turn = math.atan2( - a.dx * b.dy - a.dy * b.dx, - a.dx * b.dx + a.dy * b.dy, - ); - if (turn > 1e-9) radius = math.min(radius, step / turn); - } - return radius; - } - - static double _fraction(double value) { - final result = value % 1; - return result < 0 ? result + 1 : result; - } - - /// Multiplies the current layer by the two configured endpoint feathers. - /// - /// Both masks are radial gradients from transparent at the endpoint to - /// opaque at [BeamSegment.feather]. They are drawn into the layer that - /// already composites the variant, so segment painting adds no layer. - static void applySegmentFeather( - Canvas canvas, - Rect bounds, - BeamRingGeometry geometry, - ) { - final segment = geometry.segment; - final range = geometry.segmentRange; - if (segment == null || range == null || segment.feather <= 0) return; - final radius = math.max(segment.feather, 0.01); - for (final fraction in [range.from, range.to]) { - final center = geometry.perimeter.pointAt(fraction); - canvas.drawRect( - bounds, - Paint() - ..blendMode = BlendMode.dstIn - ..shader = ui.Gradient.radial( - center, - radius, - const [Color(0x00FFFFFF), Color(0xFFFFFFFF)], - const [0, 1], - TileMode.clamp, - ), - ); - } - } - - /// The point where a ray leaving the centre of [rect] at [angle] crosses - /// the rect's edge, in the CSS conic convention the beam angle uses: 0 is - /// 12 o'clock and the angle grows clockwise. - /// - /// An approximation of the rounded contour — a corner radius pulls the true - /// border in by a few px — which is all the sparkle scatter needs. - static Offset edgePointAt(Rect rect, double angle) { - if (rect.isEmpty) return rect.center; - final dx = math.sin(angle); - final dy = -math.cos(angle); - final tx = dx.abs() < 1e-6 ? double.infinity : (rect.width / 2) / dx.abs(); - final ty = dy.abs() < 1e-6 ? double.infinity : (rect.height / 2) / dy.abs(); - final t = math.min(tx, ty); - if (!t.isFinite) return rect.center; - return rect.center + Offset(dx * t, dy * t); - } - - /// Paints the twinkles of `BeamStyle.sparkle`: tiny radial blobs scattered - /// in a disc of radius [spread] around [center], the beam's head. - /// - /// Every position, size, and brightness comes from a hash of the sparkle's - /// index and [seed], so a frame is reproducible from its phases alone — - /// there is no particle state to carry between frames. [seed] is quantised - /// travel progress: it holds a scatter still for a fraction of a cycle and - /// then re-rolls it, which is what makes the field twinkle instead of - /// crawling along with the beam. - /// - /// The blobs are drawn straight onto the canvas with their opacity baked - /// into each colour rather than into a group layer — they need no group - /// mask, and the stroke layer they belong to is clipped to the ring, which - /// would flatten them to hairlines. Either way they cost no `saveLayer`. - static void paintSparkles( - Canvas canvas, { - required Offset center, - required double density, - required Color color, - required double opacity, - required double spread, - required int seed, - }) { - if (density <= 0 || opacity <= 0 || spread <= 0) return; - final count = (2 + 10 * density).round(); - for (var i = 0; i < count; i++) { - final angle = _hash(i, seed) * 2 * math.pi; - final distance = spread * math.sqrt(_hash(i + 91, seed)); - final radius = 0.8 + 2.4 * _hash(i + 173, seed) * (0.5 + density / 2); - final twinkle = _hash(i + 379, seed * 31 + 7); - final alpha = (opacity * density * (0.25 + 0.75 * twinkle)).clamp( - 0.0, - 1.0, - ); - if (alpha <= 0) continue; - BeamGradients.paintBlob( - canvas, - center: center + Offset(math.cos(angle), math.sin(angle)) * distance, - radiusX: radius, - radiusY: radius, - color: color.withValues(alpha: alpha), - ); - } - } - - // A cheap integer hash in 0–1: deterministic across runs and platforms, - // unlike Random(), whose stream the golden tests could not pin. - static double _hash(int a, int b) { - var h = a * 374761393 + b * 668265263; - h = (h ^ (h >> 13)) * 1274126177; - return ((h ^ (h >> 16)) & 0xFFFFFF) / 0xFFFFFF; - } - - /// Approximates the CSS `box-shadow: inset 0 0 px 1px ` of - /// the inner glow layers: the shape's contour stroked and blurred, clipped - /// to the inside. - static void paintInnerShadow( - Canvas canvas, { - required Path contour, - required Color color, - required double blur, - }) { - if (color.a <= 0) return; - canvas.save(); - canvas.clipPath(contour); - final paint = Paint() - ..color = color - ..style = PaintingStyle.stroke - // Blur + 1px spread: half the stroke falls inside the clip. - ..strokeWidth = (blur + 1) * 2 - ..maskFilter = MaskFilter.blur(BlurStyle.normal, blur * 0.5); - canvas.drawPath(contour, paint); - canvas.restore(); - } -} diff --git a/lib/src/painting/ring_geometry.dart b/lib/src/painting/ring_geometry.dart deleted file mode 100644 index 24136c1..0000000 --- a/lib/src/painting/ring_geometry.dart +++ /dev/null @@ -1,582 +0,0 @@ -import 'dart:math' as math; -import 'dart:ui' show PathMetric, Tangent; - -import 'package:flutter/painting.dart'; - -import '../models/beam_options.dart'; -import '../models/beam_segment.dart'; - -/// Arc-length geometry for a closed beam contour. -/// -/// Public fractions increase clockwise from the point nearest [Rect.topCenter] -/// regardless of the source path's winding direction. -class BeamPerimeter { - /// Measures [outer] and aligns its coordinates to [rect]. - BeamPerimeter(Path outer, this.rect, {this.radii}) { - final metrics = outer.computeMetrics().toList(growable: false); - _metric = metrics.isEmpty ? null : metrics.first; - length = _metric?.length ?? 0; - if (length <= 0) { - _s0 = 0; - _clockwiseSource = true; - return; - } - - const samples = 128; - var best = 0.0; - var bestDistance = double.infinity; - for (var i = 0; i < samples; i++) { - final offset = length * i / samples; - final distance = - (_rawTangent(offset)!.position - rect.topCenter).distanceSquared; - if (distance < bestDistance) { - bestDistance = distance; - best = offset; - } - } - var low = best - length / samples; - var high = best + length / samples; - for (var i = 0; i < 8; i++) { - final left = (2 * low + high) / 3; - final right = (low + 2 * high) / 3; - final leftDistance = - (_rawTangent(left)!.position - rect.topCenter).distanceSquared; - final rightDistance = - (_rawTangent(right)!.position - rect.topCenter).distanceSquared; - if (leftDistance <= rightDistance) { - high = right; - } else { - low = left; - } - } - _s0 = _wrapOffset((low + high) / 2); - _clockwiseSource = _rawTangent(_s0)!.vector.dx >= 0; - } - - /// The bounds used to identify top-center and rectangular edge anchors. - final Rect rect; - - /// Resolved corner radii, or null for an arbitrary contour. - final BorderRadius? radii; - - late final PathMetric? _metric; - - /// Total length of the first contour in logical pixels. - late final double length; - - late final double _s0; - late final bool _clockwiseSource; - - static double _fraction(double value) { - final result = value % 1; - return result < 0 ? result + 1 : result; - } - - double _wrapOffset(double value) { - if (length <= 0) return 0; - final result = value % length; - return result < 0 ? result + length : result; - } - - Tangent? _rawTangent(double offset) => - _metric?.getTangentForOffset(_wrapOffset(offset)); - - Tangent? _tangent(double fraction) { - if (length <= 0) return null; - final distance = _fraction(fraction) * length; - return _rawTangent(_s0 + (_clockwiseSource ? distance : -distance)); - } - - /// The point at clockwise arc-length fraction [f]. - Offset pointAt(double f) => _tangent(f)?.position ?? rect.topCenter; - - /// The clockwise unit tangent at fraction [f]. - Offset tangentAt(double f) { - final vector = _tangent(f)?.vector ?? Offset.zero; - return _clockwiseSource ? vector : -vector; - } - - /// The outward unit normal at fraction [f]. - Offset normalAt(double f) { - final tangent = tangentAt(f); - return Offset(tangent.dy, -tangent.dx); - } - - /// The perimeter point moved [inward] logical pixels toward the interior. - Offset offsetPointAt(double f, double inward) => - pointAt(f) - normalAt(f) * inward; - - /// Finds the clockwise fraction whose perimeter point is nearest [point]. - double nearestFraction(Offset point) { - if (length <= 0) return 0; - const samples = 64; - var best = 0.0; - var bestDistance = double.infinity; - for (var i = 0; i < samples; i++) { - final fraction = i / samples; - final distance = (pointAt(fraction) - point).distanceSquared; - if (distance < bestDistance) { - bestDistance = distance; - best = fraction; - } - } - var low = best - 1 / samples; - var high = best + 1 / samples; - for (var i = 0; i < 12; i++) { - final left = (2 * low + high) / 3; - final right = (low + 2 * high) / 3; - if ((pointAt(left) - point).distanceSquared <= - (pointAt(right) - point).distanceSquared) { - high = right; - } else { - low = left; - } - } - return _fraction((low + high) / 2); - } - - BorderRadius get _scaledRadii { - final source = radii; - if (source == null) return BorderRadius.zero; - final half = rect.shortestSide / 2; - Radius normalized(Radius radius) => Radius.elliptical( - radius.x.isFinite ? math.max(0, radius.x) : half, - radius.y.isFinite ? math.max(0, radius.y) : half, - ); - final topLeft = normalized(source.topLeft); - final topRight = normalized(source.topRight); - final bottomRight = normalized(source.bottomRight); - final bottomLeft = normalized(source.bottomLeft); - var scale = 1.0; - double limit(double side, double sum) => - sum <= 0 ? scale : math.min(scale, side / sum); - scale = limit(rect.width, topLeft.x + topRight.x); - scale = limit(rect.height, topRight.y + bottomRight.y); - scale = limit(rect.width, bottomLeft.x + bottomRight.x); - scale = limit(rect.height, topLeft.y + bottomLeft.y); - Radius scaled(Radius radius) => radius * scale; - return BorderRadius.only( - topLeft: scaled(topLeft), - topRight: scaled(topRight), - bottomRight: scaled(bottomRight), - bottomLeft: scaled(bottomLeft), - ); - } - - (Offset, Offset) _cornerPoints(BeamCorner corner) { - final r = _scaledRadii; - return switch (corner) { - BeamCorner.topLeft => ( - Offset(rect.left, rect.top + r.topLeft.y), - Offset(rect.left + r.topLeft.x, rect.top), - ), - BeamCorner.topRight => ( - Offset(rect.right - r.topRight.x, rect.top), - Offset(rect.right, rect.top + r.topRight.y), - ), - BeamCorner.bottomRight => ( - Offset(rect.right, rect.bottom - r.bottomRight.y), - Offset(rect.right - r.bottomRight.x, rect.bottom), - ), - BeamCorner.bottomLeft => ( - Offset(rect.left + r.bottomLeft.x, rect.bottom), - Offset(rect.left, rect.bottom - r.bottomLeft.y), - ), - }; - } - - (double, double) _cornerRange(BeamCorner corner) { - final (start, end) = _cornerPoints(corner); - return (nearestFraction(start), nearestFraction(end)); - } - - static double _clockwiseSpan(double from, double to) => _fraction(to - from); - - /// Resolves [t] along the straight part of [edge] in clockwise direction. - double fractionOfEdge(BeamEdge edge, double t) { - final (from, to) = switch (edge) { - BeamEdge.top => ( - _cornerRange(BeamCorner.topLeft).$2, - _cornerRange(BeamCorner.topRight).$1, - ), - BeamEdge.right => ( - _cornerRange(BeamCorner.topRight).$2, - _cornerRange(BeamCorner.bottomRight).$1, - ), - BeamEdge.bottom => ( - _cornerRange(BeamCorner.bottomRight).$2, - _cornerRange(BeamCorner.bottomLeft).$1, - ), - BeamEdge.left => ( - _cornerRange(BeamCorner.bottomLeft).$2, - _cornerRange(BeamCorner.topLeft).$1, - ), - }; - return _fraction(from + _clockwiseSpan(from, to) * t.clamp(0.0, 1.0)); - } - - /// Resolves [t] through [corner]'s arc in clockwise direction. - double fractionOfCorner(BeamCorner corner, double t) { - final (from, to) = _cornerRange(corner); - return _fraction(from + _clockwiseSpan(from, to) * t.clamp(0.0, 1.0)); - } - - /// Builds a closed sampled band from [from] clockwise to [to]. - /// - /// Equal endpoints cover the full perimeter. [samplesPerUnit] is the - /// approximate number of logical pixels between adjacent samples. - Path band({ - required double from, - required double to, - required double inward, - required double outward, - int samplesPerUnit = 2, - }) { - final result = Path(); - if (length <= 0) return result; - final start = _fraction(from); - var span = _clockwiseSpan(start, _fraction(to)); - if (span == 0) span = 1; - final spacing = math.max(1, samplesPerUnit); - final steps = math.max(8, (span * length / spacing).ceil()); - final outside = []; - final inside = []; - for (var i = 0; i <= steps; i++) { - final fraction = start + span * i / steps; - final point = pointAt(fraction); - final normal = normalAt(fraction); - outside.add(point + normal * outward); - inside.add(point - normal * inward); - } - result.moveTo(outside.first.dx, outside.first.dy); - for (final point in outside.skip(1)) { - result.lineTo(point.dx, point.dy); - } - for (final point in inside.reversed) { - result.lineTo(point.dx, point.dy); - } - return result..close(); - } - - /// Returns the segment mask weight at [f]. - double weightAt( - double f, { - required double from, - required double to, - required double featherFraction, - }) { - final start = _fraction(from); - var span = _clockwiseSpan(start, _fraction(to)); - if (span == 0) return 1; - final position = _clockwiseSpan(start, _fraction(f)); - if (position > span) return 0; - final feather = featherFraction.clamp(0.0, span / 2); - if (feather == 0) return 1; - double smoothstep(double value) => value * value * (3 - 2 * value); - if (position < feather) return smoothstep(position / feather); - final remaining = span - position; - if (remaining < feather) return smoothstep(remaining / feather); - return 1; - } - - /// Converts a logical-pixel feather length into a perimeter fraction. - double featherFractionFor(double featherPx) => - length <= 0 ? 0 : featherPx / length; - - /// Resolves [segment]'s anchors against this perimeter. - ({double from, double to}) resolveSegment(BeamSegment segment) => - (from: segment.start.resolve(this), to: segment.end.resolve(this)); -} - -/// Path builders for the beam's shape: rounded rect, rounded superellipse, or -/// an arbitrary [BeamContour], plus the "ring" region every stroke layer is -/// clipped to. -/// -/// The React library paints stroke layers into a CSS mask ring — -/// padding-box minus content-box. Here that is the [ring] path: the outer -/// contour (the shape's corner radii over the full rect) minus the inner -/// contour (each radius shrunk by `borderWidth`, over the rect deflated by -/// `borderWidth`). -class BeamRingGeometry { - /// Creates geometry for [rect] with the given corner [radius], - /// [borderWidth], and shape family. - /// - /// A non-null [contour] replaces the rounded-rect family entirely: it - /// builds [outer], and [radius]/[useSuperellipse] go unread. - BeamRingGeometry({ - required this.rect, - required this.radius, - required this.borderWidth, - required this.useSuperellipse, - this.contour, - this.segment, - }); - - /// The layer bounds. - final Rect rect; - - /// Outer corner radii in logical px, per corner. - final BorderRadius radius; - - /// Ring thickness in logical px. - final double borderWidth; - - /// Whether contours are rounded superellipses (squircles) instead of - /// circular-arc rounded rects. - final bool useSuperellipse; - - /// An arbitrary outer contour replacing the rounded-rect family, or null. - final BeamContour? contour; - - /// The visible clockwise portion of the contour, or null for the full ring. - final BeamSegment? segment; - - /// Outer contour of the shape. - late final Path outer = rect.isEmpty - ? Path() - : (contour?.build(rect) ?? _shapePath(rect, radius)); - - /// Arc-length coordinates for [outer]. - late final BeamPerimeter perimeter = BeamPerimeter( - outer, - rect, - radii: contour == null ? radius : null, - ); - - /// Resolved segment endpoints, or null when the complete ring is visible. - late final ({double from, double to})? segmentRange = segment == null - ? null - : perimeter.resolveSegment(segment!); - - /// A sampled band covering the configured segment at the given offsets. - /// - /// With no segment, a bounds-covering path keeps masking neutral. - Path segmentBand({required double inward, required double outward}) { - final range = segmentRange; - return range == null - ? (Path()..addRect(outer.getBounds())) - : perimeter.band( - from: range.from, - to: range.to, - inward: inward, - outward: outward, - ); - } - - /// The configured segment's feathered visibility at perimeter fraction [f]. - double segmentWeightAt(double f) { - final range = segmentRange; - final configured = segment; - if (range == null || configured == null) return 1; - return perimeter.weightAt( - f, - from: range.from, - to: range.to, - featherFraction: perimeter.featherFractionFor(configured.feather), - ); - } - - /// Inner contour (the content box: deflated by [borderWidth], every corner - /// radius reduced by the same amount). - /// - /// A box thinner than twice the border width has no content box left, and - /// the contour is empty — the ring is then the whole shape. Under a custom - /// [contour] the inner path is [outer] offset inward along its own normals - /// by [borderWidth] (see [insetPath]), since an arbitrary path has no - /// corner radii to shrink. - late final Path inner = rect.isEmpty - ? Path() - : contour != null - ? insetPath(outer, borderWidth) - : _shapePath( - rect.deflate(borderWidth), - _deflateRadius(radius, borderWidth), - ); - - /// The border ring: [outer] minus [inner]. - late final Path ring = rect.isEmpty ? Path() : _subtract(outer, inner); - - // Subtracts the nested [hole] from [shell]. - // - // `Path.combine(PathOperation.difference, ...)` is unreliable on Flutter web - // (CanvasKit): it silently returns the first operand, so the ring collapses - // back into the filled shape and every ring-confined layer washes across the - // whole child. For the built-in shapes both contours are simple and nested, - // so the even-odd fill of the two in one path describes the same region - // without a path-ops pass, and renders identically on every backend. - // - // A custom [contour] can be self-intersecting (a star is), where even-odd - // and non-zero disagree and the shortcut would punch a hole of its own — so - // those keep the path-ops route. - Path _subtract(Path shell, Path hole) { - if (contour != null) { - return Path.combine(PathOperation.difference, shell, hole); - } - return Path() - ..fillType = PathFillType.evenOdd - ..addPath(shell, Offset.zero) - ..addPath(hole, Offset.zero); - } - - Path _shapePath(Rect r, BorderRadius cornerRadii) { - // A rect with no area (or an inverted one, from deflating past the - // center) has no contour to describe. - if (r.isEmpty) return Path(); - final c = _scaleRadii(r, cornerRadii); - if (useSuperellipse) { - return Path()..addRSuperellipse( - RSuperellipse.fromRectAndCorners( - r, - topLeft: c.topLeft, - topRight: c.topRight, - bottomLeft: c.bottomLeft, - bottomRight: c.bottomRight, - ), - ); - } - return Path()..addRRect( - RRect.fromRectAndCorners( - r, - topLeft: c.topLeft, - topRight: c.topRight, - bottomLeft: c.bottomLeft, - bottomRight: c.bottomRight, - ), - ); - } - - /// A standalone contour for an arbitrary rect/radius in the same shape - /// family (used by pulse-outside's outward layers). - Path shapeContour(Rect r, BorderRadius cornerRadii) => - _shapePath(r, cornerRadii); - - /// The halo a comet bloom fills: the shape grown by [reach], minus the - /// content box, so the glow hugs the border and spills outward instead of - /// washing across the child. - Path halo(double reach) => - rect.isEmpty ? Path() : _subtract(grown(reach), inner); - - /// [outer] grown outward by [reach], in the shape's own family. - Path grown(double reach) => contour != null - ? insetPath(outer, -reach) - : _shapePath(rect.inflate(reach), _inflateRadius(radius, reach)); - - /// [source] offset inward by [inset] along its own normals — a true - /// polygonal offset, not a scale about the centre, so a lobed contour keeps - /// an even border width all the way round. - /// - /// Each closed subpath is resampled at ~1px, its orientation read from the - /// signed area (so a path drawn either way offsets inward), and every - /// sample moved along the inward normal. A concave notch tighter than - /// [inset] folds the offset over itself; the fold is a hairline at the - /// border widths this is used at, and the non-zero fill rule swallows it. - /// - /// A negative [inset] offsets outward instead, which is how the comet halo - /// grows an arbitrary contour. - static Path insetPath(Path source, double inset) { - final result = Path(); - if (inset == 0) return result..addPath(source, Offset.zero); - for (final metric in source.computeMetrics()) { - final length = metric.length; - if (length <= 0) continue; - final steps = math.max(8, length.round()); - final points = []; - final normals = []; - for (var i = 0; i < steps; i++) { - final tangent = metric.getTangentForOffset(length * i / steps); - if (tangent == null) continue; - points.add(tangent.position); - normals.add(Offset(tangent.vector.dx, tangent.vector.dy)); - } - if (points.length < 3) continue; - // Shoelace sign: positive for a path wound so that rotating the tangent - // a quarter turn one way points inward, negative for the other. - var area = 0.0; - for (var i = 0; i < points.length; i++) { - final a = points[i]; - final b = points[(i + 1) % points.length]; - area += a.dx * b.dy - b.dx * a.dy; - } - final sign = area >= 0 ? 1.0 : -1.0; - for (var i = 0; i < points.length; i++) { - final t = normals[i]; - final inward = Offset(-t.dy, t.dx) * sign; - final p = points[i] + inward * inset; - if (i == 0) { - result.moveTo(p.dx, p.dy); - } else { - result.lineTo(p.dx, p.dy); - } - } - result.close(); - } - return result; - } - - // Shrinks every corner by [amount], flooring each axis at zero — the - // content box's corners are the padding box's minus the border width. - static BorderRadius _deflateRadius(BorderRadius radii, double amount) => - BorderRadius.only( - topLeft: _shrink(radii.topLeft, amount), - topRight: _shrink(radii.topRight, amount), - bottomLeft: _shrink(radii.bottomLeft, amount), - bottomRight: _shrink(radii.bottomRight, amount), - ); - - // Grows every corner by [amount] — the mirror of [_deflateRadius], used by - // the comet halo. - static BorderRadius _inflateRadius(BorderRadius radii, double amount) => - BorderRadius.only( - topLeft: _shrink(radii.topLeft, -amount), - topRight: _shrink(radii.topRight, -amount), - bottomLeft: _shrink(radii.bottomLeft, -amount), - bottomRight: _shrink(radii.bottomRight, -amount), - ); - - static Radius _shrink(Radius r, double amount) => - Radius.elliptical(math.max(0, r.x - amount), math.max(0, r.y - amount)); - - // The clamp `RRect.scaleRadii` applies: if the two radii on any side add up - // to more than that side, all four shrink by the smallest offending ratio — - // so the corners keep their relative proportions instead of being clipped - // one at a time. - static BorderRadius _scaleRadii(Rect r, BorderRadius radii) { - final half = r.shortestSide / 2; - var tl = _normalize(radii.topLeft, half); - var tr = _normalize(radii.topRight, half); - var bl = _normalize(radii.bottomLeft, half); - var br = _normalize(radii.bottomRight, half); - - var scale = 1.0; - scale = _limit(scale, r.width, tl.x + tr.x); - scale = _limit(scale, r.height, tr.y + br.y); - scale = _limit(scale, r.width, bl.x + br.x); - scale = _limit(scale, r.height, tl.y + bl.y); - if (scale < 1) { - tl = tl * scale; - tr = tr * scale; - bl = bl * scale; - br = br * scale; - } - return BorderRadius.only( - topLeft: tl, - topRight: tr, - bottomLeft: bl, - bottomRight: br, - ); - } - - // Radii are floored at zero; an infinite one (BeamShape.stadium) becomes - // half the shortest side, the largest a corner can hold, which is what - // makes a pill track the box as it resizes. - static Radius _normalize(Radius r, double half) => - Radius.elliptical(_finite(r.x, half), _finite(r.y, half)); - - static double _finite(double value, double fallback) { - final floored = math.max(0.0, value); - return floored.isFinite ? floored : fallback; - } - - static double _limit(double scale, double side, double sum) => - sum <= 0 ? scale : math.min(scale, side / sum); -} diff --git a/lib/src/painting/strategies/line_strategy.dart b/lib/src/painting/strategies/line_strategy.dart deleted file mode 100644 index bf9191b..0000000 --- a/lib/src/painting/strategies/line_strategy.dart +++ /dev/null @@ -1,1012 +0,0 @@ -import 'dart:math' as math; -import 'dart:ui'; - -import 'package:flutter/painting.dart' show BorderRadius; - -import '../../animation/beam_phases.dart'; -import '../../constants/line_geometry.dart'; -import '../../constants/line_keyframes.dart'; -import '../../models/beam_blob.dart'; -import '../../models/beam_config.dart'; -import '../../models/beam_options.dart'; -import '../../models/beam_segment.dart'; -import '../color_matrix.dart'; -import '../gradient_builders.dart'; -import '../layer_utils.dart'; -import '../ring_geometry.dart'; -import '../variant_strategy.dart'; - -const Color _white = Color(0xFFFFFFFF); -const Color _black = Color(0xFF000000); - -// How far a traveller's band runs past the box, before and after the edge it -// rides: far enough that nothing a blob or a blur reaches is ever cut, while -// the bands still partition the edge between the travellers. -const double _bandOverhang = 10000; - -// The sparkle scatter's radius around a traveller, and how finely its -// position is quantised into the twinkle seed. -const double _sparkleSpread = 16; -const int _sparkleSeedSteps = 24; - -/// One traveller's frame: where it sits along the edge, its width factor, the -/// edge fade it carries, and the slice of the edge it owns. -/// -/// [band] is null for a lone beam — the ordinary case paints exactly as it -/// always has, with no clip and no radius clamp. -typedef _Traveller = ({ - double x, - double w, - double fade, - Rect? band, - double? fraction, - Path? pathBand, -}); - -/// The perimeter slice a path-mode frame is painted over: the geometry, the -/// clockwise range, and whether travel runs against that range. -/// -/// [mirrored] is set for the edge-derived range `wrapCorners` builds, where -/// the beam must keep the planar variant's direction (see [_paintPathAbove]). -typedef _PathContext = ({ - BeamRingGeometry geometry, - double from, - double span, - bool mirrored, -}); - -/// The edge-riding traveling beam (React `line`): all masks are radial -/// windows anchored at the traveling position on the edge, plus a bloom of -/// fixed spikes that shimmer via two counter-phased scale tracks. -/// -/// The geometry is authored for the bottom edge; every other edge is that -/// painting turned about the box's centre, so the transcribed numbers are -/// never touched. -class LineStrategy extends BeamVariantStrategy { - /// Const constructor. - const LineStrategy(); - - @override - void paintAbove( - Canvas canvas, - Size size, - BeamConfig config, - BeamFramePhases phases, - ) { - if (phases.fadeOpacity <= 0) return; - - final pathMode = config.segment != null || config.wrapCorners; - if (pathMode) { - _paintPathAbove(canvas, size, config, phases); - return; - } - - // The rotations run counter-clockwise around the box, so a beam that - // rides the bottom edge left-to-right rides the right edge - // bottom-to-top. - canvas.save(); - final authored = _applyEdgeTransform(canvas, size, config.edge); - final rect = beamRect(authored, config); - final geometry = BeamRingGeometry( - rect: rect, - radius: _rotateRadii(config.borderRadius, config.edge), - borderWidth: config.borderWidth, - useSuperellipse: config.useSuperellipse, - contour: config.contour, - ); - final isDark = config.brightness == Brightness.dark; - final beams = _travellers(rect, phases); - // A group's opacity carries the brightest traveller's edge fade; each - // traveller then scales its own colours by the rest of it. The bands are - // disjoint, so scaling per band is exact rather than an approximation. - var fadeMax = 0.0; - for (final beam in beams) { - fadeMax = math.max(fadeMax, beam.fade); - } - if (fadeMax <= 0) { - canvas.restore(); - return; - } - - final layerMatrix = config.staticColors - ? null - : BeamColorMatrix.beamFilter( - hueDegrees: phases.hueDegrees + config.hueBase, - brightness: config.brightnessFactor, - saturation: config.saturation, - ); - Color fold(Color c) => layerMatrix?.transform(c) ?? c; - - _paintInner(canvas, rect, geometry, config, phases, fold, beams, fadeMax); - _paintStroke( - canvas, - rect, - geometry, - config, - phases, - fold, - isDark, - beams, - fadeMax, - ); - _paintBloom(canvas, rect, geometry, config, phases, isDark, beams, fadeMax); - canvas.restore(); - } - - // A configured segment owns line travel, so [BeamConfig.edge] is ignored: - // the beam runs the segment's own clockwise start → end. - // - // With wrapCorners alone the selected edge resolves to its straight run plus - // both adjacent corner arcs, and feeds the same path-space code with one - // rule attached: wrapCorners is a modifier on the ordinary line variant, so - // turning it on must not reverse the animation. The planar painting is - // authored on the bottom edge running left to right, and every other edge is - // that painting turned rigidly about the box's centre — which leaves travel - // running counter-clockwise around the box on all four edges (bottom left to - // right, top right to left, left top to bottom, right bottom to top), the - // opposite of the perimeter's clockwise parameterisation. An edge-derived - // range therefore carries `mirrored`, and every progress, spike fraction and - // blob offset goes through [_pathFraction] to flip. `BeamDirection` is - // already folded into `phases.travellers` and composes on top of this. - void _paintPathAbove( - Canvas canvas, - Size size, - BeamConfig config, - BeamFramePhases phases, - ) { - final rect = beamRect(size, config); - final segment = config.segment ?? _edgeSegment(config.edge); - final geometry = config.segment != null - ? beamGeometry(rect, config) - : BeamRingGeometry( - rect: rect, - radius: config.borderRadius, - borderWidth: config.borderWidth, - useSuperellipse: config.useSuperellipse, - contour: config.contour, - segment: segment, - ); - final range = geometry.segmentRange!; - final span = _clockwiseSpan(range.from, range.to); - final path = ( - geometry: geometry, - from: range.from, - span: span, - mirrored: config.segment == null, - ); - final isDark = config.brightness == Brightness.dark; - final beams = _pathTravellers(path, phases); - var fadeMax = 0.0; - for (final beam in beams) { - fadeMax = math.max(fadeMax, beam.fade); - } - if (fadeMax <= 0) return; - - final layerMatrix = config.staticColors - ? null - : BeamColorMatrix.beamFilter( - hueDegrees: phases.hueDegrees + config.hueBase, - brightness: config.brightnessFactor, - saturation: config.saturation, - ); - Color fold(Color c) => layerMatrix?.transform(c) ?? c; - - _paintInner( - canvas, - rect, - geometry, - config, - phases, - fold, - beams, - fadeMax, - path: path, - ); - _paintStroke( - canvas, - rect, - geometry, - config, - phases, - fold, - isDark, - beams, - fadeMax, - path: path, - ); - _paintBloom( - canvas, - rect, - geometry, - config, - phases, - isDark, - beams, - fadeMax, - path: path, - ); - } - - // ─── Travel ───────────────────────────────────────────────────────────── - - // Resolves every beam travelling the edge this frame. With one beam the - // keyframe values already on the phases are used as they are; with several, - // each traveller samples the same tracks at its own progress and takes the - // slice of the edge reaching halfway to each neighbour — disjoint bands are - // what let several radial masks union inside one layer, since a `dstIn` - // draw multiplies and would otherwise erase its neighbours. - List<_Traveller> _travellers(Rect rect, BeamFramePhases phases) { - final progress = phases.travellers; - if (progress.length <= 1) { - return [ - ( - x: phases.lineX, - w: phases.lineW, - fade: phases.edge, - band: null, - fraction: null, - pathBand: null, - ), - ]; - } - final sorted = [...progress] - ..sort( - (a, b) => sampleKeyframes( - lineTravelX, - a, - ).compareTo(sampleKeyframes(lineTravelX, b)), - ); - final xs = [for (final p in sorted) sampleKeyframes(lineTravelX, p)]; - final result = <_Traveller>[]; - for (var i = 0; i < sorted.length; i++) { - final centre = rect.left + xs[i] * rect.width; - final left = i == 0 - ? rect.left - _bandOverhang - : (centre + rect.left + xs[i - 1] * rect.width) / 2; - final right = i == sorted.length - 1 - ? rect.right + _bandOverhang - : (centre + rect.left + xs[i + 1] * rect.width) / 2; - result.add(( - x: xs[i], - w: sampleKeyframes(lineTravelW, sorted[i]), - fade: sampleKeyframes(lineEdgeFade, sorted[i]), - band: Rect.fromLTRB( - left, - rect.top - _bandOverhang, - right, - rect.bottom + _bandOverhang, - ), - fraction: null, - pathBand: null, - )); - } - return result; - } - - List<_Traveller> _pathTravellers(_PathContext path, BeamFramePhases phases) { - final sorted = [...phases.travellers]..sort(); - return [ - for (var i = 0; i < sorted.length; i++) - ( - x: sampleKeyframes(lineTravelX, sorted[i]), - w: sampleKeyframes(lineTravelW, sorted[i]), - fade: sampleKeyframes(lineEdgeFade, sorted[i]), - band: null, - fraction: _pathFraction(path, sorted[i]), - pathBand: sorted.length == 1 - ? null - : _pathBand( - path, - // The halfway points to each neighbour in travel order. A - // mirrored range reverses them on the perimeter, so the - // clockwise band runs from the later progress to the - // earlier one. - lower: i == 0 ? 0 : (sorted[i - 1] + sorted[i]) / 2, - upper: i == sorted.length - 1 - ? 1 - : (sorted[i] + sorted[i + 1]) / 2, - ), - ), - ]; - } - - Path _pathBand( - _PathContext path, { - required double lower, - required double upper, - }) => path.geometry.perimeter.band( - from: _pathFraction(path, path.mirrored ? upper : lower), - to: _pathFraction(path, path.mirrored ? lower : upper), - inward: _bandOverhang, - outward: _bandOverhang, - ); - - Offset _anchor( - Rect rect, - _Traveller beam, { - double dy = 0, - _PathContext? path, - }) => path == null - ? Offset(rect.left + beam.x * rect.width, rect.bottom + dy) - : path.geometry.perimeter.offsetPointAt(beam.fraction!, -dy); - - Offset _blobAnchor( - Rect rect, - _Traveller beam, { - required double offsetX, - required double inward, - _PathContext? path, - }) => path == null - ? Offset(rect.left + beam.x * rect.width + offsetX, rect.bottom - inward) - : path.geometry.perimeter.offsetPointAt( - // A blob's offsetX runs along the direction of travel, which is - // against the clockwise parameterisation on a mirrored range. - beam.fraction! + - (path.geometry.perimeter.length <= 0 - ? 0 - : (path.mirrored ? -offsetX : offsetX) / - path.geometry.perimeter.length), - inward, - ); - - double _rotation(_Traveller beam, _PathContext? path) { - if (path == null) return 0; - final tangent = path.geometry.perimeter.tangentAt(beam.fraction!); - return math.atan2(tangent.dy, tangent.dx); - } - - // The widest a traveller's mask may reach without spilling into a - // neighbour's band, where the clip would cut it while it is still opaque. - double _maskRadiusX(Rect rect, _Traveller beam, double wanted) { - final band = beam.band; - if (band == null) return wanted; - final centre = rect.left + beam.x * rect.width; - return math.min(wanted, math.min(centre - band.left, band.right - centre)); - } - - // Runs [paint] for one traveller, inside its own slice of the edge. - void _forEachTraveller( - Canvas canvas, - List<_Traveller> beams, - void Function(_Traveller beam) paint, - ) { - for (final beam in beams) { - final band = beam.band; - final pathBand = beam.pathBand; - if (band == null && pathBand == null) { - paint(beam); - continue; - } - canvas.save(); - if (band != null) canvas.clipRect(band); - if (pathBand != null) canvas.clipPath(pathBand); - paint(beam); - canvas.restore(); - } - } - - // ─── Layers ───────────────────────────────────────────────────────────── - - void _paintInner( - Canvas canvas, - Rect rect, - BeamRingGeometry geometry, - BeamConfig config, - BeamFramePhases phases, - Color Function(Color) fold, - List<_Traveller> beams, - double fadeMax, { - _PathContext? path, - }) { - // The line variant does not apply the mono ×0.5 multiplier — its mono - // treatment lives in the bloom spike attenuation. - final opacity = - (phases.fadeOpacity * - fadeMax * - config.theme.innerOpacity * - config.innerOpacityFactor * - config.strength) - .clamp(0.0, 1.0); - if (opacity <= 0) return; - - canvas.save(); - canvas.clipPath(geometry.outer); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: rect.shortestSide / 2, - outward: 0, - ); - canvas.saveLayer(rect, Paint()..color = _white.withValues(alpha: opacity)); - - _forEachTraveller(canvas, beams, (beam) { - final tint = _tint(fold, beam, fadeMax); - for (final blob in config.palette.data.lineInner) { - BeamGradients.paintBlob( - canvas, - center: _blobAnchor( - rect, - beam, - offsetX: blob.offsetX, - inward: blob.offsetY.abs(), - path: path, - ), - radiusX: blob.sizeW * beam.w, - radiusY: blob.sizeH * phases.lineH, - color: tint(blob.color), - rotation: _rotation(beam, path), - ); - } - }); - BeamLayerUtils.paintInnerShadow( - canvas, - contour: geometry.outer, - color: fold(config.theme.innerShadow), - blur: lineInnerShadowBlur, - ); - - // Mask: (featherV ∪ featherH) ∩ the union of the travellers' windows. - canvas.saveLayer(rect, Paint()..blendMode = BlendMode.dstIn); - canvas.drawRect( - rect, - Paint()..shader = BeamGradients.verticalEdgeFeather(rect), - ); - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.screen - ..shader = BeamGradients.horizontalEdgeFeather(rect), - ); - _forEachTraveller(canvas, beams, (beam) { - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.dstIn - ..shader = _window(rect, beam, phases, path: path), - ); - }); - canvas.restore(); - - BeamLayerUtils.applySegmentFeather(canvas, rect, geometry); - - canvas.restore(); - canvas.restore(); - } - - void _paintStroke( - Canvas canvas, - Rect rect, - BeamRingGeometry geometry, - BeamConfig config, - BeamFramePhases phases, - Color Function(Color) fold, - bool isDark, - List<_Traveller> beams, - double fadeMax, { - _PathContext? path, - }) { - final opacity = - (phases.fadeOpacity * - fadeMax * - config.theme.strokeOpacity * - config.strokeOpacityFactor * - config.strength) - .clamp(0.0, 1.0); - if (opacity <= 0) return; - - canvas.save(); - canvas.clipPath(geometry.ring); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: geometry.borderWidth, - outward: 0, - ); - canvas.saveLayer(rect, Paint()..color = _white.withValues(alpha: opacity)); - - _forEachTraveller(canvas, beams, (beam) { - final tint = _tint(fold, beam, fadeMax); - // White (dark) / black (light) traveling highlight. - final base = isDark ? _white : _black; - final alphas = isDark - ? lineHighlightAlphasDark - : lineHighlightAlphasLight; - BeamLayerUtils.paintRadial( - canvas, - center: _anchor(rect, beam, dy: lineHighlightOffsetY, path: path), - radiusX: - (isDark ? lineHighlightRadiusXDark : lineHighlightRadiusXLight) * - beam.w, - radiusY: - (isDark ? lineHighlightRadiusYDark : lineHighlightRadiusYLight) * - phases.lineH, - colors: [for (final a in alphas) tint(base.withValues(alpha: a))], - stops: isDark ? lineHighlightStopsDark : lineHighlightStopsLight, - rotation: _rotation(beam, path), - ); - final blobs = isDark - ? config.palette.data.lineDark - : config.palette.data.lineLight; - for (final blob in blobs) { - BeamGradients.paintBlob( - canvas, - center: _blobAnchor( - rect, - beam, - offsetX: blob.offsetX, - inward: -blob.offsetY, - path: path, - ), - radiusX: blob.sizeW * beam.w, - radiusY: blob.sizeH * phases.lineH, - color: tint(blob.color), - rotation: _rotation(beam, path), - ); - } - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.dstIn - ..shader = _window(rect, beam, phases, path: path), - ); - }); - - BeamLayerUtils.applySegmentFeather(canvas, rect, geometry); - - canvas.restore(); - canvas.restore(); - - _paintSparkles( - canvas, - rect, - config, - beams, - opacity, - fadeMax, - isDark, - path: path, - ); - } - - void _paintBloom( - Canvas canvas, - Rect rect, - BeamRingGeometry geometry, - BeamConfig config, - BeamFramePhases phases, - bool isDark, - List<_Traveller> beams, - double fadeMax, { - _PathContext? path, - }) { - final opacity = - (phases.fadeOpacity * - fadeMax * - config.theme.bloomOpacity * - config.bloomOpacityFactor * - config.strength) - .clamp(0.0, 1.0); - if (opacity <= 0) return; - - final mono = config.palette.monoTreatment; - // Bloom filter: blur(8) + hue(range+10) when animating; blur(6) for - // mono; no filter when static non-mono (matching the generated CSS). - // glowSpread scales whichever blur applies. - final blurSigma = - (mono - ? lineBloomBlurSigmaMono - : (config.staticColors ? 0.0 : lineBloomBlurSigma)) * - config.glowSpread; - final matrix = config.staticColors - ? null - : BeamColorMatrix.beamFilter( - hueDegrees: phases.bloomHueDegrees + config.hueBase, - brightness: config.brightnessFactor, - saturation: config.saturation, - ); - Color fold(Color c) => matrix?.transform(c) ?? c; - - final layerPaint = Paint()..color = _white.withValues(alpha: opacity); - if (blurSigma > 0) { - layerPaint.imageFilter = ImageFilter.blur( - sigmaX: blurSigma, - sigmaY: blurSigma, - tileMode: TileMode.decal, - ); - } - - canvas.save(); - canvas.clipPath(geometry.outer); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: rect.shortestSide / 2, - outward: 0, - ); - canvas.saveLayer(rect, layerPaint); - - _forEachTraveller(canvas, beams, (beam) { - _paintSpikes( - canvas, - rect, - config, - phases, - isDark, - mono, - _tint(fold, beam, fadeMax), - beam, - path: path, - ); - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.dstIn - ..shader = BeamGradients.radialWindow( - center: _anchor(rect, beam, path: path), - radiusX: _maskRadiusX(rect, beam, lineBloomWindowRadiusX * beam.w), - radiusY: lineBloomWindowRadiusY * phases.lineH, - midStop: lineBloomWindowMidStop, - midAlpha: lineBloomWindowMidAlpha, - rotation: _rotation(beam, path), - ), - ); - }); - - BeamLayerUtils.applySegmentFeather(canvas, rect, geometry); - - canvas.restore(); - canvas.restore(); - } - - Shader _window( - Rect rect, - _Traveller beam, - BeamFramePhases phases, { - _PathContext? path, - }) => BeamGradients.radialWindow( - center: _anchor(rect, beam, path: path), - radiusX: _maskRadiusX(rect, beam, lineWindowRadiusX * beam.w), - radiusY: lineWindowRadiusY * phases.lineH, - midStop: lineWindowMidStop, - midAlpha: lineWindowMidAlpha, - rotation: _rotation(beam, path), - ); - - // A traveller's colour treatment: the shared fold, then the share of the - // edge fade the group opacity did not already carry. - Color Function(Color) _tint( - Color Function(Color) fold, - _Traveller beam, - double fadeMax, - ) { - final k = fadeMax <= 0 ? 0.0 : (beam.fade / fadeMax).clamp(0.0, 1.0); - if (k >= 1) return fold; - return (c) { - final folded = fold(c); - return folded.withValues(alpha: folded.a * k); - }; - } - - // Twinkles at each traveller, drawn over the stroke without a layer of - // their own. - void _paintSparkles( - Canvas canvas, - Rect rect, - BeamConfig config, - List<_Traveller> beams, - double opacity, - double fadeMax, - bool isDark, { - _PathContext? path, - }) { - if (config.sparkle <= 0 || rect.isEmpty) return; - if (path != null) { - canvas.save(); - canvas.clipPath( - BeamLayerUtils.segmentBandPath( - path.geometry, - inward: _sparkleSpread, - outward: _sparkleSpread, - ), - ); - } - for (var i = 0; i < beams.length; i++) { - final beam = beams[i]; - final weight = path == null - ? 1.0 - : path.geometry.segmentWeightAt(beam.fraction!); - if (weight <= 0) continue; - BeamLayerUtils.paintSparkles( - canvas, - center: _anchor(rect, beam, path: path), - density: config.sparkle, - color: isDark ? _white : _black, - opacity: opacity * (beam.fade / fadeMax) * weight, - spread: _sparkleSpread, - seed: (beam.x * _sparkleSeedSteps).floor() * 7 + i, - ); - } - if (path != null) canvas.restore(); - } - - // The fixed bloom spikes at 8/22/36/50/64/78/92% of the edge, plus the - // traveling dot/ambient (dark) or shadow blob (light). Transcribed from - // getLineBloomGradients. - void _paintSpikes( - Canvas canvas, - Rect rect, - BeamConfig config, - BeamFramePhases phases, - bool isDark, - bool mono, - Color Function(Color) fold, - _Traveller beam, { - _PathContext? path, - }) { - final palette = config.palette.data; - final spikeColors = isDark ? palette.spike : palette.spikeLt; - final table = isDark ? palette.lineBloomDark : palette.lineBloomLight; - - Color att(Color c, double f) => BeamLayerUtils.attenuateSpike(c, f); - final sc1 = mono - ? att(spikeColors.primary, lineMonoSpike1) - : spikeColors.primary; - final sc1MidDark = mono - ? att(spikeColors.primary, lineMonoSpike1MidDark) - : spikeColors.primary; - final sc1MidLight = mono - ? att(spikeColors.primary, lineMonoSpike1MidLight) - : BeamLayerUtils.withAlpha( - spikeColors.primary, - lineSpike1MidLightAlpha, - ); - final sc2 = mono - ? att(spikeColors.secondary, lineMonoSpike2) - : spikeColors.secondary; - final sc2MidDark = mono - ? BeamLayerUtils.withAlpha(spikeColors.secondary, lineMonoSpike2MidDark) - : BeamLayerUtils.withAlpha( - spikeColors.secondary, - lineSpike2MidDarkAlpha, - ); - final sc2MidLight = mono - ? att(spikeColors.secondary, lineMonoSpike2MidLight) - : BeamLayerUtils.withAlpha( - spikeColors.secondary, - lineSpike2MidLightAlpha, - ); - SpikePair spikeAt(int i) => mono - ? SpikePair( - att(table[i].color1, lineMonoTableSpike1), - att(table[i].color2, lineMonoTableSpike2), - ) - : table[i]; - - // Mono widens and shortens the thin spikes into a soft glow. - final thinW = mono ? lineMonoThinSpikeWidths : lineThinSpikeWidths; - final thinH = mono ? lineMonoThinSpikeHeights : lineThinSpikeHeights; - final thinLW = mono - ? lineMonoThinSpikeWidthLight92 - : lineThinSpikeWidthLight92; - - void spike({ - required int index, - required double rx, - required double ry, - required Color c0, - required Color cMid, - }) { - final geometry = lineSpikes[index]; - // The spike table is authored from the start of the planar edge, so on - // a mirrored range its fractions flip with the travel direction and the - // seven spikes keep the screen positions the planar variant gives them. - final fraction = path == null ? 0.0 : _pathFraction(path, geometry.fx); - final center = path == null - ? Offset( - rect.left + geometry.fx * rect.width, - rect.bottom - geometry.yInset, - ) - : path.geometry.perimeter.offsetPointAt(fraction, geometry.yInset); - final rotation = path == null - ? 0.0 - : () { - final tangent = path.geometry.perimeter.tangentAt(fraction); - return math.atan2(tangent.dy, tangent.dx); - }(); - BeamLayerUtils.paintRadial( - canvas, - center: center, - radiusX: rx, - radiusY: ry, - colors: [fold(c0), fold(cMid), fold(cMid.withValues(alpha: 0))], - stops: [0, geometry.midStop, geometry.endStop], - rotation: rotation, - ); - } - - final s = phases.spike; - final s2 = phases.spike2; - final h = phases.lineH; - - spike( - index: 0, - rx: thinW[0] * s, - ry: thinH[0] * h, - c0: sc1, - cMid: isDark ? sc1MidDark : sc1MidLight, - ); - spike( - index: 1, - rx: lineSpikeWideRadiusX22 * s2, - ry: lineSpikeRadiusY22 * h, - c0: sc2, - cMid: isDark ? sc2MidDark : sc2MidLight, - ); - spike( - index: 2, - rx: thinW[1] * (2 - s), - ry: thinH[1] * h, - c0: spikeAt(0).color1, - cMid: spikeAt(0).color2, - ); - spike( - index: 3, - rx: lineSpikeWideRadiusX50 * s2, - ry: lineSpikeRadiusY50 * h, - c0: spikeAt(1).color1, - cMid: spikeAt(1).color2, - ); - spike( - index: 4, - rx: thinW[2] * (2 - s2), - ry: thinH[2] * h, - c0: spikeAt(2).color1, - cMid: spikeAt(2).color2, - ); - spike( - index: 5, - rx: lineSpikeRadiusX78 * s, - ry: lineSpikeRadiusY78 * h, - c0: spikeAt(3).color1, - cMid: spikeAt(3).color2, - ); - spike( - index: 6, - rx: (isDark ? thinW[3] : thinLW) * (2 - s), - ry: thinH[3] * h, - c0: spikeAt(4).color1, - cMid: spikeAt(4).color2, - ); - - if (isDark) { - // Traveling dot + ambient glow. - final dot = mono ? lineDotAlphasMono : lineDotAlphas; - final dotC = _white.withValues(alpha: dot[0]); - final dot20 = _white.withValues(alpha: dot[1]); - final dot50 = _white.withValues(alpha: dot[2]); - BeamLayerUtils.paintRadial( - canvas, - center: _anchor(rect, beam, dy: lineDotOffsetY, path: path), - radiusX: lineDotRadiusX * s, - radiusY: lineDotRadiusY * s2, - colors: [ - fold(dotC), - fold(dot20), - fold(dot50), - fold(dot50.withValues(alpha: 0)), - ], - stops: lineDotStops, - rotation: _rotation(beam, path), - ); - final ambient = mono ? lineAmbientAlphasMono : lineAmbientAlphas; - final ambC = _white.withValues(alpha: ambient[0]); - final amb25 = _white.withValues(alpha: ambient[1]); - final amb55 = _white.withValues(alpha: ambient[2]); - BeamLayerUtils.paintRadial( - canvas, - center: _anchor(rect, beam, path: path), - radiusX: lineAmbientRadiusX * beam.w, - radiusY: lineAmbientRadiusY * h, - colors: [ - fold(ambC), - fold(amb25), - fold(amb55), - fold(amb55.withValues(alpha: 0)), - ], - stops: lineAmbientStops, - rotation: _rotation(beam, path), - ); - } else { - // Light theme: a traveling dark shadow blob instead of the bright dot. - BeamLayerUtils.paintRadial( - canvas, - center: _anchor(rect, beam, path: path), - radiusX: lineShadowRadiusX * beam.w, - radiusY: lineShadowRadiusY * h, - colors: [ - for (final a in lineShadowAlphas) fold(_black.withValues(alpha: a)), - ], - stops: lineShadowStops, - rotation: _rotation(beam, path), - ); - } - } -} - -double _fraction(double value) { - final result = value % 1; - return result < 0 ? result + 1 : result; -} - -// Where progress [t] along a path-mode run lands on the perimeter. A mirrored -// range walks its clockwise span backwards, which is what keeps wrapCorners -// travelling the way the planar variant does. -double _pathFraction(_PathContext path, double t) => - _fraction(path.from + path.span * (path.mirrored ? 1 - t : t)); - -double _clockwiseSpan(double from, double to) { - final span = _fraction(to - from); - return span == 0 ? 1 : span; -} - -BeamSegment _edgeSegment(BeamEdge edge) => switch (edge) { - BeamEdge.top => BeamSegment.topEdge, - BeamEdge.right => BeamSegment.rightEdge, - BeamEdge.bottom => BeamSegment.bottomEdge, - BeamEdge.left => BeamSegment.leftEdge, -}; - -// Turns the canvas so the authored bottom-edge painting lands on [edge], and -// returns the size it should be authored against — swapped for the two -// vertical edges, where the box's height becomes the authored width. -Size _applyEdgeTransform(Canvas canvas, Size size, BeamEdge edge) { - switch (edge) { - case BeamEdge.bottom: - return size; - case BeamEdge.top: - canvas.translate(size.width, size.height); - canvas.rotate(math.pi); - return size; - case BeamEdge.left: - canvas.translate(size.width, 0); - canvas.rotate(math.pi / 2); - return Size(size.height, size.width); - case BeamEdge.right: - canvas.translate(0, size.height); - canvas.rotate(-math.pi / 2); - return Size(size.height, size.width); - } -} - -// The corner radii to author the ring with so that, once the canvas turn is -// applied, every corner lands back on the corner of the child it belongs to. -BorderRadius _rotateRadii(BorderRadius radii, BeamEdge edge) { - switch (edge) { - case BeamEdge.bottom: - return radii; - case BeamEdge.top: - return BorderRadius.only( - topLeft: radii.bottomRight, - topRight: radii.bottomLeft, - bottomLeft: radii.topRight, - bottomRight: radii.topLeft, - ); - case BeamEdge.left: - return BorderRadius.only( - topLeft: _swapAxes(radii.topRight), - topRight: _swapAxes(radii.bottomRight), - bottomRight: _swapAxes(radii.bottomLeft), - bottomLeft: _swapAxes(radii.topLeft), - ); - case BeamEdge.right: - return BorderRadius.only( - topLeft: _swapAxes(radii.bottomLeft), - topRight: _swapAxes(radii.topLeft), - bottomRight: _swapAxes(radii.topRight), - bottomLeft: _swapAxes(radii.bottomRight), - ); - } -} - -// A quarter turn swaps an elliptical radius' two axes. -Radius _swapAxes(Radius r) => Radius.elliptical(r.y, r.x); diff --git a/lib/src/painting/strategies/pulse_common.dart b/lib/src/painting/strategies/pulse_common.dart deleted file mode 100644 index 6bbcdc8..0000000 --- a/lib/src/painting/strategies/pulse_common.dart +++ /dev/null @@ -1,85 +0,0 @@ -import 'dart:ui'; - -import '../../animation/oscillator.dart'; -import '../../models/beam_blob.dart'; -import '../gradient_builders.dart'; - -/// Reads a pulse table's color source, cycling a short custom spec palette. -/// -/// [border] is never empty: every palette that reaches the painter resolves -/// through `BeamColors`, and `validateColorTable` rejects an empty table -/// there — in release builds as well as debug ones. -BeamBlob pulseBlobAt(List border, int index) => - border[index % border.length]; - -/// Resolves a [PulseQuad] to its animated opacity factor. -double quadOpacity(PulsePhaseSet pulse, PulseQuad quad) => switch (quad) { - PulseQuad.tl => pulse.bopTl, - PulseQuad.tr => pulse.bopTr, - PulseQuad.bl => pulse.bopBl, - PulseQuad.br => pulse.bopBr, -}; - -/// Paints one breathing pulse blob (the source's `pulseGrad`): -/// width = `w · bw[region] · sx · boost`, height = `h · bh[region] · bgh · -/// sy · boost`, position = base + region drift, alpha = quadrant factor. -void paintPulseBlob( - Canvas canvas, { - required Rect rect, - required Color color, - required Offset fractionalPos, - required double w, - required double h, - required PulseRegion region, - required PulseQuad quad, - required PulsePhaseSet pulse, - required double sx, - required double sy, - required double boost, - required Color Function(Color) fold, - double alphaScale = 1, -}) { - if (alphaScale <= 0) return; - final r = region.index; - BeamGradients.paintBlob( - canvas, - center: Offset( - rect.left + fractionalPos.dx * rect.width + pulse.bx[r], - rect.top + fractionalPos.dy * rect.height + pulse.by[r], - ), - radiusX: w * pulse.bw[r] * sx * boost, - radiusY: h * pulse.bh[r] * pulse.bgh * sy * boost, - color: fold(color), - alpha: quadOpacity(pulse, quad) * alphaScale, - ); -} - -/// Paints one frozen (non-breathing) pulse blob, as used by the pulse bloom -/// layers (the source's `pulseTableGradientsStatic`): geometry scaled only -/// by sx/sy/boost, alpha fixed at the breathing time-average. -void paintFrozenPulseBlob( - Canvas canvas, { - required Rect rect, - required Color color, - required Offset fractionalPos, - required double w, - required double h, - required double frozenAlpha, - required double sx, - required double sy, - required double boost, - required Color Function(Color) fold, - double alphaScale = 1, -}) { - if (alphaScale <= 0) return; - BeamGradients.paintBlob( - canvas, - center: Offset( - rect.left + fractionalPos.dx * rect.width, - rect.top + fractionalPos.dy * rect.height, - ), - radiusX: w * sx * boost, - radiusY: h * sy * boost, - color: fold(color.withValues(alpha: frozenAlpha * alphaScale)), - ); -} diff --git a/lib/src/painting/strategies/pulse_inner_strategy.dart b/lib/src/painting/strategies/pulse_inner_strategy.dart deleted file mode 100644 index c2e03bc..0000000 --- a/lib/src/painting/strategies/pulse_inner_strategy.dart +++ /dev/null @@ -1,267 +0,0 @@ -import 'dart:ui'; - -import '../../animation/beam_phases.dart'; -import '../../constants/pulse_constants.dart'; -import '../../constants/pulse_params.dart'; -import '../../constants/pulse_tables.dart'; -import '../../models/beam_config.dart'; -import '../../models/beam_variant.dart'; -import '../color_matrix.dart'; -import '../gradient_builders.dart'; -import '../layer_utils.dart'; -import '../variant_strategy.dart'; -import 'pulse_common.dart'; - -const Color _white = Color(0xFFFFFFFF); - -/// The contained breathing glow (React `pulse-inner`): a breathing inner -/// perimeter with corner accents, a colorful perimeter ring, and a frozen -/// blurred bloom, all clipped inside the element. -class PulseInnerStrategy extends BeamVariantStrategy { - /// Const constructor. - const PulseInnerStrategy(); - - @override - double? get preferredFps => 30; - - @override - void paintAbove( - Canvas canvas, - Size size, - BeamConfig config, - BeamFramePhases phases, - ) { - if (phases.fadeOpacity <= 0) return; - final rect = beamRect(size, config); - final geometry = beamGeometry(rect, config); - final isDark = config.brightness == Brightness.dark; - final params = PulseParams.resolve( - BeamVariant.pulseInside, - config.brightness, - config.cycleSeconds, - ); - - // Pulse layers keep brightness/saturation even with static colors; only - // the hue term is dropped (ringAnim in the source). - final ringMatrix = BeamColorMatrix.beamFilter( - hueDegrees: config.staticColors ? 0 : phases.hueDegrees + config.hueBase, - brightness: config.brightnessFactor, - saturation: config.saturation, - ); - Color fold(Color c) => ringMatrix.transform(c); - - final boost = config.glowBoost; - final border = config.palette.data.border; - // The inward wash — its blobs and its corner accents — is the one layer - // innerSizeScale moves; the perimeter ring and the bloom keep their own - // geometry so the border itself stays where it is. - final innerScale = config.innerSizeScale; - double weightAt(Offset point) => - geometry.segmentWeightAt(geometry.perimeter.nearestFraction(point)); - double blobWeight(Rect blobRect, Offset fractionalPos) => weightAt( - Offset( - blobRect.left + fractionalPos.dx * blobRect.width, - blobRect.top + fractionalPos.dy * blobRect.height, - ), - ); - - // ── z1: inner perimeter + corner accents (::before) ── - final innerOpacity = BeamLayerUtils.layerOpacity( - config, - fade: phases.fadeOpacity, - preset: config.theme.innerOpacity, - hookFactor: config.innerOpacityFactor, - ); - if (innerOpacity > 0) { - canvas.save(); - canvas.clipPath(geometry.outer); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: rect.shortestSide / 2, - outward: 0, - ); - canvas.saveLayer( - rect, - Paint()..color = _white.withValues(alpha: innerOpacity), - ); - - for (final (i, blob) in border.indexed) { - final map = pulseRingMap[i]; - paintPulseBlob( - canvas, - rect: rect, - color: blob.color, - fractionalPos: blob.position, - w: pulseInnerSizes[i].width * innerScale, - h: pulseInnerSizes[i].height * innerScale, - region: map.region, - quad: map.quad, - pulse: phases.pulse, - sx: 1, - sy: 1, - boost: boost, - fold: fold, - alphaScale: blobWeight(rect, blob.position), - ); - } - // Corner accents: fixed 60×60 ellipses whose alpha breathes with the - // corner's quadrant oscillator. - final cornerBase = isDark ? _white : const Color(0xFF000000); - final cornerAlpha = isDark - ? pulseInnerCornerAlphaDark - : pulseInnerCornerAlphaLight; - final corners = [ - (pos: rect.topLeft, quad: pulseRingMap[0].quad), - (pos: rect.topRight, quad: pulseRingMap[6].quad), - (pos: rect.bottomLeft, quad: pulseRingMap[2].quad), - (pos: rect.bottomRight, quad: pulseRingMap[4].quad), - ]; - for (final corner in corners) { - final a = - cornerAlpha * - quadOpacity(phases.pulse, corner.quad) * - weightAt(corner.pos); - if (a <= 0) continue; - BeamLayerUtils.paintRadial( - canvas, - center: corner.pos, - radiusX: pulseInnerCornerRadius * innerScale, - radiusY: pulseInnerCornerRadius * innerScale, - colors: [ - fold(cornerBase.withValues(alpha: a)), - fold(cornerBase.withValues(alpha: 0)), - ], - stops: const [0, pulseInnerCornerEndStop], - ); - } - - // Mask: featherV ∪ featherH (edge-hugging inner border). - canvas.saveLayer(rect, Paint()..blendMode = BlendMode.dstIn); - canvas.drawRect( - rect, - Paint()..shader = BeamGradients.verticalEdgeFeather(rect), - ); - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.screen - ..shader = BeamGradients.horizontalEdgeFeather(rect), - ); - canvas.restore(); - - BeamLayerUtils.applySegmentFeather(canvas, rect, geometry); - - canvas.restore(); - canvas.restore(); - } - - // ── z2: perimeter ring (::after) ── - final strokeOpacity = BeamLayerUtils.layerOpacity( - config, - fade: phases.fadeOpacity, - preset: config.theme.strokeOpacity, - hookFactor: config.strokeOpacityFactor, - ); - if (strokeOpacity > 0) { - canvas.save(); - canvas.clipPath(geometry.ring); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: geometry.borderWidth, - outward: 0, - ); - canvas.saveLayer( - rect, - Paint()..color = _white.withValues(alpha: strokeOpacity), - ); - for (final (i, blob) in border.indexed) { - final map = pulseRingMap[i]; - paintPulseBlob( - canvas, - rect: rect, - color: blob.color, - fractionalPos: blob.position, - w: blob.size.width, - h: blob.size.height, - region: map.region, - quad: map.quad, - pulse: phases.pulse, - sx: 1, - sy: 1, - boost: boost, - fold: fold, - alphaScale: blobWeight(rect, blob.position), - ); - } - // The dashed-ring mask rides inside the ring layer, the one layer a - // pulse beam draws its border in; the inner glow and the bloom stay - // continuous, since dashing a breathing wash reads as banding. - final segments = config.segments; - if (segments != null && segments >= 2) { - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.dstIn - ..shader = BeamGradients.segmentMask(rect, segments), - ); - } - BeamLayerUtils.applySegmentFeather(canvas, rect, geometry); - canvas.restore(); - canvas.restore(); - } - - // ── z3: frozen bloom in the ring, blurred ── - final bloomOpacity = BeamLayerUtils.layerOpacity( - config, - fade: phases.fadeOpacity, - preset: config.theme.bloomOpacity, - hookFactor: config.bloomOpacityFactor, - ); - if (bloomOpacity > 0) { - final frozenAlpha = 1 - params.op * 0.5; - canvas.save(); - canvas.clipPath(geometry.outer); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: geometry.borderWidth, - outward: 0, - ); - canvas.saveLayer( - rect, - Paint() - ..color = _white.withValues(alpha: bloomOpacity) - ..imageFilter = ImageFilter.blur( - sigmaX: pulseInnerBloomBlurSigma * config.glowSpread, - sigmaY: pulseInnerBloomBlurSigma * config.glowSpread, - tileMode: TileMode.decal, - ), - ); - canvas.save(); - canvas.clipPath(geometry.ring); - for (final spec in pulseInnerBloom) { - final source = pulseBlobAt(border, spec.ci); - paintFrozenPulseBlob( - canvas, - rect: rect, - color: source.color, - fractionalPos: source.position, - w: spec.w, - h: spec.h, - frozenAlpha: frozenAlpha, - sx: 1, - sy: 1, - boost: boost, - fold: fold, - alphaScale: blobWeight(rect, source.position), - ); - } - canvas.restore(); - BeamLayerUtils.applySegmentFeather(canvas, rect, geometry); - canvas.restore(); - canvas.restore(); - } - } -} diff --git a/lib/src/painting/strategies/pulse_outer_strategy.dart b/lib/src/painting/strategies/pulse_outer_strategy.dart deleted file mode 100644 index 7fd6e24..0000000 --- a/lib/src/painting/strategies/pulse_outer_strategy.dart +++ /dev/null @@ -1,384 +0,0 @@ -import 'dart:ui'; - -import '../../animation/beam_phases.dart'; -import '../../constants/pulse_constants.dart'; -import '../../constants/pulse_params.dart'; -import '../../constants/pulse_tables.dart'; -import '../../models/beam_blob.dart'; -import '../../models/beam_config.dart'; -import '../../models/beam_options.dart'; -import '../../models/beam_variant.dart'; -import '../color_matrix.dart'; -import '../gradient_builders.dart'; -import '../layer_utils.dart'; -import '../variant_strategy.dart'; -import 'pulse_common.dart'; - -const Color _white = Color(0xFFFFFFFF); - -// ─── Verbatim: the source's stock outside-glow table ──────────────────────── -// -// The React library's own `outsideConstants`, before the demo page layers -// its tuned recipe over them (that recipe lives in `pulse_constants.dart`). -// These are absolute px: the stock look does not scale its reach or its blur -// with the element's size, which is exactly what BeamPulseOutsideTuning.stock -// selects. - -/// Stock inset the core glow is grown past the child's bounds. -const double _stockCoreInset = 10; - -/// Stock inset the bloom halo is grown past the child's bounds. -const double _stockBloomInset = 30; - -/// Stock core-glow blur on a dark background. -const double _stockCoreBlurDark = 3; - -/// Stock core-glow blur on a light background. -const double _stockCoreBlurLight = 6; - -/// Stock bloom-halo blur on a dark background. -const double _stockBloomBlurDark = 22.5; - -/// Stock bloom-halo blur on a light background. -const double _stockBloomBlurLight = 15; - -/// How far the two outward glow layers reach past the child, and how heavily -/// each is blurred, in the beam's own px. -typedef _GlowGeometry = ({ - double coreInset, - double bloomInset, - double coreBlur, - double bloomBlur, -}); - -/// The outward-blooming breathing halo (React `pulse-outside`): a crisp -/// stroke ring above the child, and a colorful core plus soft halo painted -/// BEHIND and OUTSIDE the child (which must be opaque so only the outward -/// spill shows). -class PulseOuterStrategy extends BeamVariantStrategy { - /// Const constructor. - const PulseOuterStrategy(); - - @override - double? get preferredFps => 30; - - double _sx(Size size) => (size.width / pulseOuterReferenceWidth).clamp( - pulseOuterMinScale, - pulseOuterMaxScale, - ); - double _sy(Size size) => (size.height / pulseOuterReferenceHeight).clamp( - pulseOuterMinScale, - pulseOuterMaxScale, - ); - - // Halo reach/blur scale with element size relative to the demo's Subscribe - // button baseline (measured glow scale 0.35), damped ×0.7 - // (`--sub-glow-unit`). - double _unit(Size size) => - _sx(size) / pulseOuterMinScale * pulseOuterGlowUnitDamping; - - // The demo recipe scales every length by the size-derived unit; the stock - // table is fixed px and picks its blurs by brightness. - _GlowGeometry _geometry(BeamConfig config, Size size) { - if (config.pulseOutsideTuning == BeamPulseOutsideTuning.stock) { - final isDark = config.brightness == Brightness.dark; - return ( - coreInset: _stockCoreInset, - bloomInset: _stockBloomInset, - coreBlur: isDark ? _stockCoreBlurDark : _stockCoreBlurLight, - bloomBlur: isDark ? _stockBloomBlurDark : _stockBloomBlurLight, - ); - } - final unit = _unit(size); - return ( - coreInset: pulseOuterTunedCoreInset * unit, - bloomInset: pulseOuterTunedBloomInset * unit, - coreBlur: pulseOuterTunedCoreBlur * unit, - bloomBlur: pulseOuterTunedBloomBlur * unit, - ); - } - - BeamColorMatrix _matrix( - BeamConfig config, - BeamFramePhases phases, { - double? brightness, - double? saturation, - }) => BeamColorMatrix.beamFilter( - hueDegrees: config.staticColors ? 0 : phases.hueDegrees + config.hueBase, - brightness: brightness ?? config.brightnessFactor, - saturation: saturation ?? config.saturation, - ); - - @override - void paintBehind( - Canvas canvas, - Size size, - BeamConfig config, - BeamFramePhases phases, - ) { - if (phases.fadeOpacity <= 0) return; - final rect = beamRect(size, config); - final geometry = beamGeometry(rect, config); - final params = PulseParams.resolve( - BeamVariant.pulseOutside, - config.brightness, - config.cycleSeconds, - ); - final sx = _sx(size); - final sy = _sy(size); - final glow = _geometry(config, size); - final boost = - config.glowBoost * - (config.pulseOutsideTuning == BeamPulseOutsideTuning.demo - ? pulseOuterTunedBoost - : 1); - final border = config.palette.data.border; - double blobWeight(Rect blobRect, Offset fractionalPos) { - final center = Offset( - blobRect.left + fractionalPos.dx * blobRect.width, - blobRect.top + fractionalPos.dy * blobRect.height, - ); - return geometry.segmentWeightAt( - geometry.perimeter.nearestFraction(center), - ); - } - - // Filter ordering: CSS runs `blur()` before the color terms, and Skia - // runs a paint's colorFilter BEFORE its imageFilter, so the color matrix - // is composed explicitly after the blur (ImageFilter.compose runs - // `inner` first). - final glowMatrix = _matrix( - config, - phases, - brightness: - config.glowBrightness ?? - pulseOuterGlowBrightness * pulseOuterTunedGlowMultiplier, - saturation: - config.glowSaturation ?? - pulseOuterGlowSaturation * pulseOuterTunedGlowMultiplier, - ); - ImageFilter glowBlur(double sigma) => ImageFilter.compose( - outer: glowMatrix.toColorFilter(), - inner: ImageFilter.blur( - sigmaX: sigma, - sigmaY: sigma, - tileMode: TileMode.decal, - ), - ); - Color fold(Color c) => c; - - // ── Core glow: blurred, breathing, hugging the edge ── - final coreOpacity = BeamLayerUtils.layerOpacity( - config, - fade: phases.fadeOpacity, - preset: config.theme.innerOpacity, - hookFactor: config.innerOpacityFactor, - extra: pulseOuterTunedGlowMultiplier, - ); - // glowSpread multiplies how far the halo reaches and how soft it is — - // its insets and both blurs. - final spread = config.glowSpread; - final coreBlur = (config.coreBlur ?? glow.coreBlur) * spread; - if (coreOpacity > 0) { - final coreRect = rect.inflate(glow.coreInset * spread); - final layerBounds = coreRect.inflate(coreBlur * 3); - canvas.save(); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: 0, - outward: glow.coreInset * spread + coreBlur * 3, - ); - canvas.saveLayer( - layerBounds, - Paint() - ..color = _white.withValues(alpha: coreOpacity) - ..imageFilter = glowBlur(coreBlur), - ); - _scaled(canvas, rect.center, () { - for (final spec in pulseOuterCore) { - paintPulseBlob( - canvas, - rect: coreRect, - color: pulseBlobAt(border, spec.ci).color, - fractionalPos: _specPos(spec, border), - w: spec.w, - h: spec.h, - region: spec.region, - quad: spec.quad, - pulse: phases.pulse, - sx: sx, - sy: sy, - boost: boost, - fold: fold, - alphaScale: blobWeight(coreRect, _specPos(spec, border)), - ); - } - }); - BeamLayerUtils.applySegmentFeather(canvas, layerBounds, geometry); - canvas.restore(); - canvas.restore(); - } - - // ── Bloom halo: frozen, heavily blurred ambient wash ── - final bloomOpacity = BeamLayerUtils.layerOpacity( - config, - fade: phases.fadeOpacity, - preset: config.theme.bloomOpacity, - hookFactor: config.bloomOpacityFactor, - extra: pulseOuterTunedGlowMultiplier, - ); - final bloomBlur = (config.bloomBlur ?? glow.bloomBlur) * spread; - if (bloomOpacity > 0) { - final bloomRect = rect.inflate(glow.bloomInset * spread); - final frozenAlpha = 1 - params.op * 0.5; - final layerBounds = bloomRect.inflate(bloomBlur * 3); - canvas.save(); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: 0, - outward: glow.bloomInset * spread + bloomBlur * 3, - ); - canvas.saveLayer( - layerBounds, - Paint() - ..color = _white.withValues(alpha: bloomOpacity) - ..imageFilter = glowBlur(bloomBlur), - ); - _scaled(canvas, rect.center, () { - for (final spec in pulseOuterBloom) { - paintFrozenPulseBlob( - canvas, - rect: bloomRect, - color: pulseBlobAt(border, spec.ci).color, - fractionalPos: _specPos(spec, border), - w: spec.w, - h: spec.h, - frozenAlpha: frozenAlpha, - sx: sx, - sy: sy, - boost: boost, - fold: fold, - alphaScale: blobWeight(bloomRect, _specPos(spec, border)), - ); - } - }); - BeamLayerUtils.applySegmentFeather(canvas, layerBounds, geometry); - canvas.restore(); - canvas.restore(); - } - } - - @override - void paintAbove( - Canvas canvas, - Size size, - BeamConfig config, - BeamFramePhases phases, - ) { - if (phases.fadeOpacity <= 0) return; - final rect = beamRect(size, config); - final isDark = config.brightness == Brightness.dark; - // The stroke ring is always 1px in the source (padding: 1px). - final geometry = beamGeometry(rect, config); - final sx = _sx(size); - final sy = _sy(size); - // Filter applied at layer composite time (post-gradient), matching CSS — - // see paintBehind for why this must not be folded into the colors. - final matrix = _matrix(config, phases); - Color fold(Color c) => c; - final border = config.palette.data.border; - double blobWeight(Offset fractionalPos) { - final center = Offset( - rect.left + fractionalPos.dx * rect.width, - rect.top + fractionalPos.dy * rect.height, - ); - return geometry.segmentWeightAt( - geometry.perimeter.nearestFraction(center), - ); - } - - final strokeOpacity = BeamLayerUtils.layerOpacity( - config, - fade: phases.fadeOpacity, - preset: config.theme.strokeOpacity, - hookFactor: config.strokeOpacityFactor, - extra: pulseOuterTunedGlowMultiplier, - ); - if (strokeOpacity <= 0) return; - - canvas.save(); - canvas.clipPath(geometry.ring); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: geometry.borderWidth, - outward: 0, - ); - canvas.saveLayer( - rect, - Paint() - ..color = _white.withValues(alpha: strokeOpacity) - ..colorFilter = matrix.toColorFilter(), - ); - // Optional static hairline under the colored stroke (preset 0 — the - // wrapped child's own border provides the idle edge). - final hairline = config.theme.hairlineOpacity ?? 0; - if (hairline > 0) { - final hairRGB = isDark - ? const Color(0xFF464646) - : const Color(0xFF000000); - canvas.drawRect( - rect, - Paint()..color = hairRGB.withValues(alpha: hairline), - ); - } - for (final spec in pulseOuterCore) { - paintPulseBlob( - canvas, - rect: rect, - color: pulseBlobAt(border, spec.ci).color, - fractionalPos: _specPos(spec, border), - w: spec.w, - h: spec.h, - region: spec.region, - quad: spec.quad, - pulse: phases.pulse, - sx: sx, - sy: sy, - boost: config.glowBoost, - fold: fold, - alphaScale: blobWeight(_specPos(spec, border)), - ); - } - // The dashed-ring mask rides inside the ring layer; the outward glows are - // left continuous, since dashing a soft halo reads as banding. - final segments = config.segments; - if (segments != null && segments >= 2) { - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.dstIn - ..shader = BeamGradients.segmentMask(rect, segments), - ); - } - BeamLayerUtils.applySegmentFeather(canvas, rect, geometry); - canvas.restore(); - canvas.restore(); - } - - Offset _specPos(PulseBlobSpec spec, List border) => - spec.x != null && spec.y != null - ? Offset(spec.x!, spec.y!) - : pulseBlobAt(border, spec.ci).position; - - void _scaled(Canvas canvas, Offset center, void Function() paint) { - canvas.save(); - canvas.translate(center.dx, center.dy); - canvas.scale(pulseOuterScaleX, pulseOuterScaleY); - canvas.translate(-center.dx, -center.dy); - paint(); - canvas.restore(); - } -} diff --git a/lib/src/painting/strategies/rotate_strategy.dart b/lib/src/painting/strategies/rotate_strategy.dart deleted file mode 100644 index 529d96b..0000000 --- a/lib/src/painting/strategies/rotate_strategy.dart +++ /dev/null @@ -1,458 +0,0 @@ -import 'dart:math' as math; -import 'dart:ui'; - -import '../../animation/beam_phases.dart'; -import '../../constants/rotate_stops.dart'; -import '../../models/beam_config.dart'; -import '../color_matrix.dart'; -import '../gradient_builders.dart'; -import '../layer_utils.dart'; -import '../ring_geometry.dart'; -import '../variant_strategy.dart'; - -const Color _white = Color(0xFFFFFFFF); -const Color _black = Color(0xFF000000); - -// How far past the ring the comet halo reaches at glowSpread 1, and how much -// wider its band runs than the plain bloom's — the halo is the same layer, -// re-clipped and stretched, so it has to read as a trail rather than as an -// edge highlight. -const double _cometReach = 12; -const double _cometBandFactor = 1.6; - -// The stop the rotate window's bright core ends at: the beam's head, and so -// where the sparkles gather. -const double _windowHeadStop = 0.80; - -// The sparkle scatter's radius around the head, and how finely travel -// progress is quantised into its seed (higher re-rolls the twinkles more -// often). -const double _sparkleSpread = 14; -const int _sparkleSeedSteps = 16; - -/// The traveling-beam strategy shared by [BeamVariant.rotate] (React `md`) -/// and [BeamVariant.small] (React `sm`) — a conic highlight and color blobs -/// revealed through a rotating soft window. -class RotateStrategy extends BeamVariantStrategy { - /// Creates the strategy. [compact] selects the small variant's gradient - /// tables and masks. - const RotateStrategy({required this.compact}); - - /// Whether this paints the small (`sm`) variant. - final bool compact; - - @override - void paintAbove( - Canvas canvas, - Size size, - BeamConfig config, - BeamFramePhases phases, - ) { - if (phases.fadeOpacity <= 0) return; - final rect = beamRect(size, config); - final geometry = beamGeometry(rect, config); - final isDark = config.brightness == Brightness.dark; - - // CPU color folding: when hue animation runs, the whole - // hue/brightness/saturation chain is baked into gradient colors, so the - // stroke/inner layers need no per-frame ColorFilter saveLayer. With - // static colors the source omits the filter entirely. - final strokeMatrix = config.staticColors - ? null - : BeamColorMatrix.beamFilter( - hueDegrees: phases.hueDegrees + config.hueBase, - brightness: config.brightnessFactor, - saturation: config.saturation, - ); - Color fold(Color c) => strokeMatrix?.transform(c) ?? c; - - _paintInner(canvas, rect, geometry, config, phases, fold, isDark); - _paintStroke(canvas, rect, geometry, config, phases, fold, isDark); - _paintBloom(canvas, rect, geometry, config, phases, isDark); - } - - void _paintInner( - Canvas canvas, - Rect rect, - BeamRingGeometry geometry, - BeamConfig config, - BeamFramePhases phases, - Color Function(Color) fold, - bool isDark, - ) { - final opacity = BeamLayerUtils.layerOpacity( - config, - fade: phases.fadeOpacity, - preset: config.theme.innerOpacity, - hookFactor: config.innerOpacityFactor, - ); - if (opacity <= 0) return; - - canvas.save(); - canvas.clipPath(geometry.outer); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: rect.shortestSide / 2, - outward: 0, - ); - canvas.saveLayer(rect, Paint()..color = _white.withValues(alpha: opacity)); - - if (compact) { - for (final blob in config.palette.data.smallInner) { - BeamGradients.paintBlob( - canvas, - center: _blobCenter(rect, blob.position), - radiusX: blob.size.width, - radiusY: blob.size.height, - color: fold(blob.color), - ); - } - } else { - // md derives its inner blobs from the border table: 0.9× size and a - // fixed alpha (0.45, or 0.225 for mono). - final alpha = config.palette.monoTreatment - ? rotateInnerBlobAlphaMono - : rotateInnerBlobAlpha; - for (final blob in config.palette.data.border) { - BeamGradients.paintBlob( - canvas, - center: _blobCenter(rect, blob.position), - radiusX: (blob.size.width * rotateInnerBlobScale).roundToDouble(), - radiusY: (blob.size.height * rotateInnerBlobScale).roundToDouble(), - color: fold(blob.color.withValues(alpha: alpha)), - ); - } - } - BeamLayerUtils.paintInnerShadow( - canvas, - contour: geometry.outer, - color: fold(config.theme.innerShadow), - blur: compact ? smallInnerShadowBlur : rotateInnerShadowBlur, - ); - - // Mask pass. - if (compact) { - // Single wide conic window, additive. - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.dstIn - ..shader = _window( - rect, - config, - phases, - stops: smallWindowStops, - alphas: smallWindowAlphas, - ), - ); - } else { - // (featherV ∪ featherH) ∩ conic window, built in a mask sub-layer. - canvas.saveLayer(rect, Paint()..blendMode = BlendMode.dstIn); - canvas.drawRect( - rect, - Paint()..shader = BeamGradients.verticalEdgeFeather(rect), - ); - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.screen - ..shader = BeamGradients.horizontalEdgeFeather(rect), - ); - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.dstIn - ..shader = _window( - rect, - config, - phases, - stops: rotateWindowStops, - alphas: rotateWindowAlphas, - ), - ); - canvas.restore(); - } - - BeamLayerUtils.applySegmentFeather(canvas, rect, geometry); - - canvas.restore(); - canvas.restore(); - } - - void _paintStroke( - Canvas canvas, - Rect rect, - BeamRingGeometry geometry, - BeamConfig config, - BeamFramePhases phases, - Color Function(Color) fold, - bool isDark, - ) { - final opacity = BeamLayerUtils.layerOpacity( - config, - fade: phases.fadeOpacity, - preset: config.theme.strokeOpacity, - hookFactor: config.strokeOpacityFactor, - ); - if (opacity <= 0) return; - final highlightBase = isDark ? _white : _black; - - canvas.save(); - canvas.clipPath(geometry.ring); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: geometry.borderWidth, - outward: 0, - ); - canvas.saveLayer(rect, Paint()..color = _white.withValues(alpha: opacity)); - - // Highlight sweep (white on dark, black on light). - final highlight = BeamConicWindow.resolve( - rotateHighlightStops, - isDark ? rotateHighlightAlphasDark : rotateHighlightAlphasLight, - reversed: phases.reversedNow, - tailLength: config.tailLength, - beamCount: config.beamCount, - ); - canvas.drawRect( - rect, - Paint() - ..shader = BeamGradients.conic( - rect: rect, - cssFromRadians: phases.angleRadians, - colors: [ - for (final a in highlight.alphas) - fold(highlightBase.withValues(alpha: a)), - ], - stops: highlight.stops, - ), - ); - final blobs = compact - ? config.palette.data.smallBorder - : config.palette.data.border; - for (final blob in blobs) { - BeamGradients.paintBlob( - canvas, - center: _blobCenter(rect, blob.position), - radiusX: blob.size.width, - radiusY: blob.size.height, - color: fold(blob.color), - ); - } - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.dstIn - ..shader = _window( - rect, - config, - phases, - stops: rotateWindowStops, - alphas: rotateWindowAlphas, - ), - ); - _applySegments(canvas, rect, config); - BeamLayerUtils.applySegmentFeather(canvas, rect, geometry); - - canvas.restore(); - canvas.restore(); - - _paintSparkles( - canvas, - rect, - geometry, - config, - phases, - opacity, - highlightBase, - ); - } - - void _paintBloom( - Canvas canvas, - Rect rect, - BeamRingGeometry geometry, - BeamConfig config, - BeamFramePhases phases, - bool isDark, - ) { - final opacity = BeamLayerUtils.layerOpacity( - config, - fade: phases.fadeOpacity, - preset: config.theme.bloomOpacity, - hookFactor: config.bloomOpacityFactor, - ); - if (opacity <= 0) return; - - // Bloom filter chain: blur(8px · glowSpread) brightness saturate (no - // hue). - final matrix = BeamColorMatrix.beamFilter( - hueDegrees: 0, - brightness: config.brightnessFactor, - saturation: config.saturation, - ); - final base = isDark ? _white : _black; - - // The comet is this same layer, re-aimed: instead of the thin ring it - // fills a halo reaching past the border, and its band runs wider so the - // glow trails the head. One clip swapped and one band stretched — no - // second layer. - final reach = _cometReach * config.glowSpread; - final region = config.comet ? geometry.halo(reach) : geometry.outer; - final band = config.comet ? region : geometry.ring; - final bounds = config.comet ? rect.inflate(reach) : rect; - final table = BeamConicWindow.resolve( - rotateBloomStops, - isDark ? rotateBloomAlphasDark : rotateBloomAlphasLight, - reversed: phases.reversedNow, - tailLength: config.tailLength * (config.comet ? _cometBandFactor : 1.0), - beamCount: config.beamCount, - ); - - canvas.save(); - canvas.clipPath(region); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: 0, - outward: config.comet ? reach : 0, - ); - canvas.saveLayer( - bounds, - Paint() - ..color = _white.withValues(alpha: opacity) - ..imageFilter = ImageFilter.blur( - sigmaX: rotateBloomBlurSigma * config.glowSpread, - sigmaY: rotateBloomBlurSigma * config.glowSpread, - tileMode: TileMode.decal, - ), - ); - canvas.save(); - canvas.clipPath(band); - canvas.drawRect( - bounds, - Paint() - ..shader = BeamGradients.conic( - rect: rect, - cssFromRadians: phases.angleRadians, - colors: [ - for (final a in table.alphas) - matrix.transform(base.withValues(alpha: a)), - ], - stops: table.stops, - ), - ); - canvas.restore(); - _applySegments(canvas, bounds, config); - BeamLayerUtils.applySegmentFeather(canvas, bounds, geometry); - canvas.restore(); - canvas.restore(); - } - - // The dashed-ring mask: one repeating conic multiplied into a layer that - // exists anyway, so a dashed ring costs no more than a solid one. - void _applySegments(Canvas canvas, Rect rect, BeamConfig config) { - final segments = config.segments; - if (segments == null || segments < 2) return; - canvas.drawRect( - rect, - Paint() - ..blendMode = BlendMode.dstIn - ..shader = BeamGradients.segmentMask(rect, segments), - ); - } - - // Twinkles at each beam head, drawn over the stroke without a layer of - // their own. They live in the foreground pass, so nothing about them - // touches the child. - void _paintSparkles( - Canvas canvas, - Rect rect, - BeamRingGeometry geometry, - BeamConfig config, - BeamFramePhases phases, - double opacity, - Color color, - ) { - if (config.sparkle <= 0 || rect.isEmpty) return; - final turn = phases.angleRadians / (2 * math.pi); - final seed = (turn * _sparkleSeedSteps).floor(); - final head = phases.reversedNow ? 1 - _windowHeadStop : _windowHeadStop; - canvas.save(); - canvas.clipPath(_sparkleBand(rect, config)); - BeamLayerUtils.clipSegment( - canvas, - geometry, - inward: _sparkleSpread, - outward: _sparkleSpread, - ); - for (var k = 0; k < config.beamCount; k++) { - final stop = (head + k) / config.beamCount; - final edgePoint = BeamLayerUtils.edgePointAt( - rect, - phases.angleRadians + stop * 2 * math.pi, - ); - final headFraction = geometry.perimeter.nearestFraction(edgePoint); - final weight = geometry.segmentWeightAt(headFraction); - if (weight == 0) continue; - BeamLayerUtils.paintSparkles( - canvas, - center: edgePoint, - density: config.sparkle, - color: color, - opacity: opacity * weight, - spread: _sparkleSpread, - seed: seed * 7 + k, - ); - } - canvas.restore(); - } - - // Sparkles scatter around the border, so they are held to a band straddling - // it rather than allowed to drift into the middle of the child. - Path _sparkleBand(Rect rect, BeamConfig config) { - final outside = beamGeometry(rect.inflate(_sparkleSpread), config).outer; - final inside = rect.deflate(_sparkleSpread).isEmpty - ? Path() - : beamGeometry(rect.deflate(_sparkleSpread), config).outer; - return Path.combine(PathOperation.difference, outside, inside); - } - - Shader _window( - Rect rect, - BeamConfig config, - BeamFramePhases phases, { - required List stops, - required List alphas, - }) { - final table = BeamConicWindow.resolve( - stops, - alphas, - reversed: phases.reversedNow, - tailLength: config.tailLength, - beamCount: config.beamCount, - ); - return BeamGradients.conic( - rect: rect, - cssFromRadians: phases.angleRadians, - colors: [for (final a in table.alphas) _white.withValues(alpha: a)], - stops: table.stops, - ); - } - - static Offset _blobCenter(Rect rect, Offset fractional) => Offset( - rect.left + fractional.dx * rect.width, - rect.top + fractional.dy * rect.height, - ); -} - -/// Reusable blob-center math for other strategies. -Offset blobCenter(Rect rect, Offset fractional) => Offset( - rect.left + fractional.dx * rect.width, - rect.top + fractional.dy * rect.height, -); - -/// Clamp helper mirroring CSS `max(0, ...)` for derived radii. -double nonNegative(double v) => math.max(0, v); diff --git a/lib/src/painting/variant_strategy.dart b/lib/src/painting/variant_strategy.dart deleted file mode 100644 index 82f0d8a..0000000 --- a/lib/src/painting/variant_strategy.dart +++ /dev/null @@ -1,79 +0,0 @@ -import 'dart:ui'; - -import '../animation/beam_phases.dart'; -import '../models/beam_config.dart'; -import 'ring_geometry.dart'; - -/// The rect the beam's geometry occupies: the child's bounds, pushed outward -/// or pulled inward by `BeamShape.ringOffset`. -/// -/// A positive offset paints outside [size]; nothing in the beam's own render -/// tree clips that away (the `CustomPaint` clips neither painter), so the -/// ring can orbit at a distance as long as the surrounding layout leaves it -/// room. -Rect beamRect(Size size, BeamConfig config) => - (Offset.zero & size).inflate(config.ringOffset); - -const int _geometryCacheCapacity = 16; -final List<({Rect rect, BeamConfig config, BeamRingGeometry geometry})> -_geometryCache = []; - -/// The ring geometry [config] describes over [rect]. -/// -/// Strategies request geometry on every paint. A tiny LRU retains the recent -/// frame boundaries so path metrics and perimeter alignment are measured once -/// for equal layout and resolved-config values. -BeamRingGeometry beamGeometry(Rect rect, BeamConfig config) { - for (var i = 0; i < _geometryCache.length; i++) { - final entry = _geometryCache[i]; - if (entry.rect == rect && entry.config == config) { - _geometryCache.removeAt(i); - _geometryCache.add(entry); - return entry.geometry; - } - } - final geometry = BeamRingGeometry( - rect: rect, - radius: config.borderRadius, - borderWidth: config.borderWidth, - useSuperellipse: config.useSuperellipse, - contour: config.contour, - segment: config.segment, - ); - _geometryCache.add((rect: rect, config: config, geometry: geometry)); - if (_geometryCache.length > _geometryCacheCapacity) { - _geometryCache.removeAt(0); - } - return geometry; -} - -/// Paints one beam variant. -/// -/// The child sits between the two passes: [paintBehind] renders layers that -/// must show through from behind the (opaque) child — only the -/// pulse-outside halo uses it — while [paintAbove] renders the decorative -/// layers stacked over the child (every other layer in every variant). -abstract class BeamVariantStrategy { - /// Const constructor for subclasses. - const BeamVariantStrategy(); - - /// Paint-notification cap in frames/second, mirroring the source's ~30fps - /// pulse driver; null runs at display rate. - double? get preferredFps => null; - - /// Layers painted behind the child (may exceed [size] bounds). - void paintBehind( - Canvas canvas, - Size size, - BeamConfig config, - BeamFramePhases phases, - ) {} - - /// Layers painted over the child. - void paintAbove( - Canvas canvas, - Size size, - BeamConfig config, - BeamFramePhases phases, - ); -} diff --git a/lib/src/render/beam_frame.dart b/lib/src/render/beam_frame.dart new file mode 100644 index 0000000..85493fa --- /dev/null +++ b/lib/src/render/beam_frame.dart @@ -0,0 +1,662 @@ +import 'dart:math' as math; +import 'dart:typed_data'; +import 'dart:ui'; + +import 'beam_outline.dart'; + +/// Floats in the shader's uniform block (`shaders/beam.frag`). +const int beamUniformFloats = _blobsC + blobSlotsC * 12; + +/// Layers a frame composites, bottom to top. +const int beamLayerCount = 3; + +/// Blob slots of layer 0. +const int blobSlotsA = 14; + +/// Blob slots of layer 1. +const int blobSlotsB = 10; + +/// Blob slots of layer 2. +const int blobSlotsC = 10; + +/// Stops a conic table holds. +const int tableStops = 16; + +// Float offsets of each uniform, in declaration order. +const int _rect = 0; +const int _radii = 4; +const int _shape = 8; +const int _perim = 12; +const int _quads = 16; +const int _mask = 20; +const int _conic = 24; +const int _layers = 28; +const int _layerFloats = 36; +const int _tables = _layers + beamLayerCount * _layerFloats; +const int _tableFloats = tableStops * 2; +const int _blobsA = _tables + 4 * _tableFloats; +const int _blobsB = _blobsA + blobSlotsA * 12; +const int _blobsC = _blobsB + blobSlotsB * 12; + +const List _blobBase = [_blobsA, _blobsB, _blobsC]; +const List _blobSlots = [blobSlotsA, blobSlotsB, blobSlotsC]; + +/// What part of the box a layer covers. +enum BeamGeometry { + /// Nothing: the layer is off. + none, + + /// The hairline ring just inside the outline. + ring, + + /// The filled shape. + fill, + + /// The ring blurred by the layer's sigma, clipped to the shape. + blurredRing, + + /// Outside the outline, fading out: the shape grown by the layer's + /// inflate and blurred by its sigma. + glow, +} + +/// How a layer's blobs are placed and shaded. +enum BeamBlobSpace { + /// Planar ellipses with a piecewise-linear falloff. + planar, + + /// Ellipses in path space: arc length along the outline × depth inward. + path, + + /// Planar gaussians — blobs blurred by the layer's blob blur. + blurred, + + /// Path-space gaussians. + blurredPath, +} + +/// Which window a layer is seen through. +enum BeamWindow { + /// No window. + none, + + /// Conic table A. + conicA, + + /// Conic table B. + conicB, + + /// A radial ellipse. + radial, +} + +/// The four conic tables. +enum BeamTable { + /// Window table A. + windowA, + + /// Window table B. + windowB, + + /// Overlay table A. + overlayA, + + /// Overlay table B. + overlayB, +} + +/// One frame's uniforms, written in place. +/// +/// Reused frame after frame by its renderer, so writing a frame allocates +/// nothing. [reset] turns every layer off; effects then switch on and fill +/// the layers they draw. +final class BeamFrameData { + /// The uniform floats, in the shader's order. + final Float32List data = Float32List(beamUniformFloats); + + final List _counts = [0, 0, 0]; + final List _fold = [ + Float64List(9), + Float64List(9), + Float64List(9), + ]; + final List _folded = [false, false, false]; + final List _brightness = [1, 1, 1]; + final List _blobBlur = [0, 0, 0]; + final List _space = [ + BeamBlobSpace.planar, + BeamBlobSpace.planar, + BeamBlobSpace.planar, + ]; + + /// How far light reaches outside the outline, in logical px. + double reachOutside = 0; + + /// How far light reaches inside the outline, in logical px (infinity: + /// across the whole box). + double reachInside = 0; + + /// Turns every layer off and clears the tables and blobs. + void reset() { + data.fillRange(0, beamUniformFloats, 0); + for (var k = 0; k < beamLayerCount; k++) { + _counts[k] = 0; + _blobBlur[k] = 0; + _space[k] = BeamBlobSpace.planar; + _folded[k] = false; + _identity(k); + } + for (final t in BeamTable.values) { + clearTable(t); + } + data[_conic + 3] = 1; + reachOutside = 0; + reachInside = 0; + } + + // ─── Header ────────────────────────────────────────────────────────────── + + /// Writes the outline, stroke width, and anti-aliasing width. + void setOutline(BeamOutline o, double borderWidth, double px) { + final r = o.rect; + _v4(_rect, r.left, r.top, r.width, r.height); + _v4(_radii, o.radii[0], o.radii[1], o.radii[2], o.radii[3]); + _v4(_shape, o.superellipse ? 1 : 0, 0, borderWidth, px); + _v4(_perim, o.length, 0, 1, 0); + _v4( + _quads, + o.quadStarts[0], + o.quadStarts[1], + o.quadStarts[2], + o.quadStarts[3], + ); + } + + /// The visible track: start and span in `u` (span 0 = all of it; a span + /// of 1, a whole turn from [start], has no ends to feather), the feather + /// at its ends, and the dash count. + void setTrack(double start, double span, double feather, int dashes) => + _v4(_mask, start, span, feather, dashes.toDouble()); + + /// The visible track's start (`u`). + double get trackStart => data[_mask]; + + /// The visible track's span (`u`; 0 = the whole border). + double get trackSpan => data[_mask + 1]; + + /// The visible track's end feather (`u`). + double get trackFeather => data[_mask + 2]; + + /// The conic coordinate: its [centre], the angle its tables start at (in + /// turns, clockwise from 12 o'clock), and how many times they repeat + /// around the turn. + void setConic(Offset centre, double start, int repeats) => _v4( + _conic, + centre.dx, + centre.dy, + start - start.floorToDouble(), + math.max(repeats, 1).toDouble(), + ); + + /// The outline box. + Rect get outlineRect => Rect.fromLTWH( + data[_rect], + data[_rect + 1], + data[_rect + 2], + data[_rect + 3], + ); + + /// The angle the conic tables start at, in turns. + double get conicStart => data[_conic + 2]; + + /// How many times the conic tables repeat around the turn. + int get conicRepeats => data[_conic + 3].round(); + + // ─── Tables ────────────────────────────────────────────────────────────── + + /// Marks [table] unused (it costs the shader one comparison). + void clearTable(BeamTable table) { + final base = _tables + table.index * _tableFloats; + for (var i = 0; i < tableStops; i++) { + data[base + 2 * i] = 2; + data[base + 2 * i + 1] = 0; + } + } + + /// Writes [table] from the first [count] of parallel [stops] (ascending, + /// 0–1) and [alphas]. At most [tableStops] stops; the rest pad with the + /// last one. + void setTable( + BeamTable table, + List stops, + List alphas, + int count, + ) { + final base = _tables + table.index * _tableFloats; + final n = math.min(count, tableStops); + for (var i = 0; i < tableStops; i++) { + final j = i < n ? i : n - 1; + data[base + 2 * i] = i < n ? stops[j] : math.max(stops[j], 1); + data[base + 2 * i + 1] = alphas[j].clamp(0.0, 1.0); + } + } + + /// The [i]th stop position of [table] (unused tables report 2). + double tableStop(BeamTable table, int i) => + data[_tables + table.index * _tableFloats + 2 * i]; + + /// The alpha of [table] at [t], as the shader reads it. + double tableAt(BeamTable table, double t) { + final base = _tables + table.index * _tableFloats; + var pp = data[base]; + var pa = data[base + 1]; + if (t <= pp || pp > 1) return pa; + for (var i = 0; i < tableStops; i++) { + final s = data[base + 2 * i]; + final a = data[base + 2 * i + 1]; + if (t <= s) { + final span = math.max(s - pp, 1e-5); + return pa + (a - pa) * ((t - pp) / span).clamp(0.0, 1.0); + } + pp = s; + pa = a; + } + return data[base + 2 * tableStops - 1]; + } + + // ─── Layers ────────────────────────────────────────────────────────────── + + int _h(int k, int row) => _layers + k * _layerFloats + row * 4; + + /// Switches layer [k] on with [geometry] and [opacity] (clamped to 0–1 + /// when painted). [sigma] blurs the blurred geometries; [inflate] grows a + /// glow's shape. + void setLayer( + int k, + BeamGeometry geometry, { + required double opacity, + double sigma = 0, + double inflate = 0, + }) { + _v4( + _h(k, 0), + geometry.index.toDouble(), + sigma, + inflate, + opacity.clamp(0.0, 1.0), + ); + } + + /// Layer [k]'s geometry. + BeamGeometry geometryOf(int k) => BeamGeometry.values[data[_h(k, 0)].round()]; + + /// Layer [k]'s opacity. + double opacityOf(int k) => data[_h(k, 0) + 3]; + + /// Layer [k]'s blur sigma. + double sigmaOf(int k) => data[_h(k, 0) + 1]; + + /// Layer [k]'s inflate. + double inflateOf(int k) => data[_h(k, 0) + 2]; + + /// Fades layer [k] out [px] in from the edge. + void setEdgeFade(int k, double px) => data[_h(k, 1)] = px; + + /// Layer [k]'s edge fade, px (0 = none). + double edgeFadeOf(int k) => data[_h(k, 1)]; + + /// Shows layer [k] through a conic window table. + void setConicWindow(int k, BeamTable table) { + assert(table == BeamTable.windowA || table == BeamTable.windowB); + data[_h(k, 1) + 1] = table == BeamTable.windowA + ? BeamWindow.conicA.index.toDouble() + : BeamWindow.conicB.index.toDouble(); + } + + /// Shows layer [k] through a radial ellipse at [centre] with radii [rx] × + /// [ry]: 1 at the centre, [midAlpha] at [midStop], 0 at the rim. In path + /// space the centre is (arc length, depth) and the radii (along, inward). + void setRadialWindow( + int k, + Offset centre, + double rx, + double ry, { + required double midStop, + required double midAlpha, + }) { + data[_h(k, 1) + 1] = BeamWindow.radial.index.toDouble(); + _v4(_h(k, 2), centre.dx, centre.dy, rx, ry); + data[_h(k, 3)] = midStop; + data[_h(k, 3) + 1] = midAlpha; + } + + /// Layer [k]'s window. + BeamWindow windowOf(int k) => BeamWindow.values[data[_h(k, 1) + 1].round()]; + + /// Layer [k]'s window parameters (see [setRadialWindow]). + List windowParamsOf(int k) => [ + for (var i = 0; i < 4; i++) data[_h(k, 2) + i], + ]; + + /// Lays an overlay table under layer [k]'s blobs, in white or black. + void setOverlay(int k, BeamTable table, {required bool white}) { + assert(table == BeamTable.overlayA || table == BeamTable.overlayB); + data[_h(k, 1) + 2] = table == BeamTable.overlayA ? 1 : 2; + data[_h(k, 1) + 3] = white ? 1 : 0; + } + + /// How layer [k]'s blobs are placed; [blur] (px) blurs them in the + /// blurred spaces. Set before adding blobs. + void setBlobSpace(int k, BeamBlobSpace space, {double blur = 0}) { + _space[k] = space; + _blobBlur[k] = blur; + data[_h(k, 3) + 2] = space.index.toDouble(); + } + + /// Layer [k]'s blob space. + BeamBlobSpace blobSpaceOf(int k) => _space[k]; + + /// Layer [k]'s blob blur, px (see [setBlobSpace]). + double blobBlurOf(int k) => _blobBlur[k]; + + /// An inset shadow on layer [k]: [color], solid to [depth] px in, blurred + /// by [sigma]. + void setShadow( + int k, + Color color, { + required double depth, + required double sigma, + }) { + _v4(_h(k, 4), color.r, color.g, color.b, color.a); + data[_h(k, 5)] = depth; + data[_h(k, 5) + 1] = sigma; + } + + /// Cuts layer [k] into the configured dashes. + void setDashed(int k) => data[_h(k, 5) + 2] = 1; + + /// Layer [k]'s colour filter: CSS `hue-rotate(hue) brightness(b) + /// saturate(s)`, applied left to right. + /// + /// The filter is folded into each colour of the layer — every blob, the + /// overlay ink, and the shadow — before they are composited, which keeps + /// overlapping colours saturated; call [finish] once the layer is written. + /// The layer's own colour matrix stays the identity [reset] wrote. + void setFilter( + int k, { + double hue = 0, + double brightness = 1, + double saturation = 1, + }) { + final rad = hue * math.pi / 180; + final c = math.cos(rad); + final s = math.sin(rad); + // Hue rotation (Filter Effects feColorMatrix), scaled by brightness. + final h00 = (0.213 + c * 0.787 - s * 0.213) * brightness; + final h01 = (0.715 - c * 0.715 - s * 0.715) * brightness; + final h02 = (0.072 - c * 0.072 + s * 0.928) * brightness; + final h10 = (0.213 - c * 0.213 + s * 0.143) * brightness; + final h11 = (0.715 + c * 0.285 + s * 0.140) * brightness; + final h12 = (0.072 - c * 0.072 - s * 0.283) * brightness; + final h20 = (0.213 - c * 0.213 - s * 0.787) * brightness; + final h21 = (0.715 - c * 0.715 + s * 0.715) * brightness; + final h22 = (0.072 + c * 0.928 + s * 0.072) * brightness; + final t = saturation; + final s00 = 0.213 + 0.787 * t; + final s01 = 0.715 - 0.715 * t; + final s02 = 0.072 - 0.072 * t; + final s10 = 0.213 - 0.213 * t; + final s11 = 0.715 + 0.285 * t; + final s12 = 0.072 - 0.072 * t; + final s20 = 0.213 - 0.213 * t; + final s21 = 0.715 - 0.715 * t; + final s22 = 0.072 + 0.928 * t; + final m = _fold[k]; + m[0] = s00 * h00 + s01 * h10 + s02 * h20; + m[1] = s00 * h01 + s01 * h11 + s02 * h21; + m[2] = s00 * h02 + s01 * h12 + s02 * h22; + m[3] = s10 * h00 + s11 * h10 + s12 * h20; + m[4] = s10 * h01 + s11 * h11 + s12 * h21; + m[5] = s10 * h02 + s11 * h12 + s12 * h22; + m[6] = s20 * h00 + s21 * h10 + s22 * h20; + m[7] = s20 * h01 + s21 * h11 + s22 * h21; + m[8] = s20 * h02 + s21 * h12 + s22 * h22; + _brightness[k] = brightness; + _folded[k] = true; + } + + /// Folds each layer's filter into its colours (see [setFilter]). + void finish() { + for (var k = 0; k < beamLayerCount; k++) { + if (!_folded[k]) continue; + _folded[k] = false; + final base = _blobBase[k]; + for (var i = 0; i < _counts[k]; i++) { + _foldAt(k, base + i * 12 + 4); + } + _foldAt(k, _h(k, 4)); + final ink = _h(k, 1) + 3; + data[ink] = (data[ink] * _brightness[k]).clamp(0.0, 1.0); + } + } + + void _foldAt(int k, int i) { + final m = _fold[k]; + final r = data[i]; + final g = data[i + 1]; + final b = data[i + 2]; + data[i] = (m[0] * r + m[1] * g + m[2] * b).clamp(0.0, 1.0); + data[i + 1] = (m[3] * r + m[4] * g + m[5] * b).clamp(0.0, 1.0); + data[i + 2] = (m[6] * r + m[7] * g + m[8] * b).clamp(0.0, 1.0); + } + + void _identity(int k) { + _v4(_h(k, 6), 1, 0, 0, 0); + _v4(_h(k, 7), 0, 1, 0, 0); + _v4(_h(k, 8), 0, 0, 1, 0); + } + + // ─── Blobs ─────────────────────────────────────────────────────────────── + + /// Blobs in layer [k]. + int blobCount(int k) => _counts[k]; + + /// Layer [k]'s [i]th blob as the shader reads it: centre, radii (sigmas + /// for a blurred blob), straight colour, and peak alpha. + ({ + double cx, + double cy, + double rx, + double ry, + double r, + double g, + double b, + double alpha, + }) + blob(int k, int i) { + final o = _blobBase[k] + i * 12; + return ( + cx: data[o], + cy: data[o + 1], + rx: data[o + 2], + ry: data[o + 3], + r: data[o + 4], + g: data[o + 5], + b: data[o + 6], + alpha: data[o + 7], + ); + } + + /// Layer [k]'s overlay table, or null for none. + BeamTable? overlayOf(int k) => switch (data[_h(k, 1) + 2].round()) { + 1 => BeamTable.overlayA, + 2 => BeamTable.overlayB, + _ => null, + }; + + /// Whether layer [k]'s shadow is set. + bool hasShadow(int k) => data[_h(k, 4) + 3] > 0; + + /// Adds a blob to layer [k], in painting order: each blob is drawn over + /// the ones added before it. + /// + /// The blob is an ellipse of radii [rx] × [ry] centred at [cx], [cy] (in + /// path space: arc length and depth), coloured [rgb], with alpha [a0] at + /// the centre falling through [a1] at [p1] and [a2] at [p2] to 0 at [p3] + /// (fractions of the radii). Ignored once the layer's slots are used. + /// + /// In the blurred spaces, [clip] cuts the blob along a line before + /// it is blurred, keeping the side where the coordinate on `axis` (0 = x, + /// 1 = y) is below `at` (`keepBelow`) or above it. + void addBlob( + int k, { + required double cx, + required double cy, + required double rx, + required double ry, + required Color rgb, + required double a0, + required double p1, + required double a1, + required double p2, + required double a2, + double p3 = 1, + ({int axis, double at, bool keepBelow})? clip, + }) { + if (_counts[k] >= _blobSlots[k] || a0 <= 0 && a1 <= 0 && a2 <= 0) return; + final end = p3 <= 0 ? 1e-3 : p3; + var x = cx; + var y = cy; + var sx = math.max(rx * end, 1e-3); + var sy = math.max(ry * end, 1e-3); + var q1 = (p1 / end).clamp(0.0, 1.0); + var q2 = (p2 / end).clamp(q1, 1.0); + var peak = a0; + if (_space[k] == BeamBlobSpace.blurred || + _space[k] == BeamBlobSpace.blurredPath) { + // The energy-preserving gaussian of the blob blurred by the layer's + // blob blur: the profile's mass and variance, plus the blur's. + final m0 = _moment(1, a0, q1, a1, q2, a2); + final m2 = _moment(3, a0, q1, a1, q2, a2); + if (m0 <= 0) return; + final spread = math.sqrt(m2 / (2 * m0)); + var gx = sx * spread; + var gy = sy * spread; + var mass = m0 * sx * sy; + if (clip != null) { + // Cut along the line: the kept part's mass, mean, and variance + // across it (a truncated normal). + final s = clip.axis == 0 ? gx : gy; + final c = clip.axis == 0 ? x : y; + final inside = clip.keepBelow ? clip.at - c : c - clip.at; + final a = -inside / s; + final kept = _cdf(inside / s); + if (kept <= 1e-4) return; + final lambda = _pdf(a) / kept; + final shift = s * lambda; + final spreadAcross = + s * math.sqrt(math.max(1 + a * lambda - lambda * lambda, 1e-4)); + mass *= kept; + if (clip.axis == 0) { + x += clip.keepBelow ? -shift : shift; + gx = spreadAcross; + } else { + y += clip.keepBelow ? -shift : shift; + gy = spreadAcross; + } + } + final blur = _blobBlur[k]; + final bx = math.sqrt(gx * gx + blur * blur); + final by = math.sqrt(gy * gy + blur * blur); + peak = math.min(mass / (bx * by), math.max(a0, math.max(a1, a2))); + sx = bx; + sy = by; + q1 = 0; + q2 = 0; + } + final base = _blobBase[k] + _counts[k] * 12; + _v4(base, x, y, sx, sy); + _v4(base + 4, rgb.r, rgb.g, rgb.b, peak); + _v4(base + 8, q1, a1, q2, a2); + _counts[k]++; + data[_h(k, 3) + 3] = _counts[k].toDouble(); + } + + // The standard normal density and distribution. + static double _pdf(double z) => 0.3989422804 * math.exp(-0.5 * z * z); + + static double _cdf(double z) { + // Abramowitz & Stegun 7.1.26 (|error| < 1.5e-7). + final x = z.abs() / math.sqrt2; + final t = 1 / (1 + 0.3275911 * x); + final y = + 1 - + ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - + 0.284496736) * + t + + 0.254829592) * + t * + math.exp(-x * x); + return z >= 0 ? 0.5 * (1 + y) : 0.5 * (1 - y); + } + + /// Adds a CSS `color → transparent` blob: alpha falls linearly from the + /// colour's own alpha times [alpha] at the centre to 0 at the rim. + void addSimpleBlob( + int k, { + required double cx, + required double cy, + required double rx, + required double ry, + required Color color, + double alpha = 1, + double end = 1, + ({int axis, double at, bool keepBelow})? clip, + }) { + final a = color.a * alpha; + addBlob( + k, + cx: cx, + cy: cy, + rx: rx, + ry: ry, + rgb: color, + a0: a, + p1: end / 3, + a1: a * 2 / 3, + p2: end * 2 / 3, + a2: a / 3, + p3: end, + clip: clip, + ); + } + + // ∫ f(t) t^n dt over the piecewise-linear profile 0:a0 → q1:a1 → q2:a2 → + // 1:0. + static double _moment( + int n, + double a0, + double q1, + double a1, + double q2, + double a2, + ) { + double seg(double t0, double f0, double t1, double f1) { + if (t1 <= t0) return 0; + final beta = (f1 - f0) / (t1 - t0); + final alpha = f0 - beta * t0; + double pw(double t, int e) => math.pow(t, e).toDouble(); + return alpha * (pw(t1, n + 1) - pw(t0, n + 1)) / (n + 1) + + beta * (pw(t1, n + 2) - pw(t0, n + 2)) / (n + 2); + } + + return seg(0, a0, q1, a1) + seg(q1, a1, q2, a2) + seg(q2, a2, 1, 0); + } + + void _v4(int i, double a, double b, double c, double d) { + data[i] = a; + data[i + 1] = b; + data[i + 2] = c; + data[i + 3] = d; + } +} diff --git a/lib/src/render/beam_outline.dart b/lib/src/render/beam_outline.dart new file mode 100644 index 0000000..0fde920 --- /dev/null +++ b/lib/src/render/beam_outline.dart @@ -0,0 +1,559 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; + +import '../models/beam_options.dart'; +import '../models/beam_segment.dart'; + +/// How far a superellipse corner reaches along each edge, in corner radii +/// (capped at half that side). +/// +/// Flutter's rounded superellipse never runs exactly straight: its corner +/// eases into each edge over a long tail. Past this reach the tail is under +/// 1.4e-4 radii from the edge (0.004 px at a 28 px radius), so the outline +/// runs straight from there. +const double squircleReach = 2.5; + +/// The outline every beam is drawn along, and the perimeter coordinate the +/// shader shades by — mirrored here in Dart so the CPU can place lights, +/// resolve anchors, and map a pointer to the border with the same numbers the +/// GPU uses (`shaders/beam.frag`, `outline()`). +/// +/// The outline is a rectangle with four corners, each either a circular arc +/// or Flutter's rounded superellipse (`RSuperellipse`, as drawn by +/// `RoundedSuperellipseBorder`). The perimeter coordinate `u` runs over +/// `[0, 1)` from top-centre, clockwise, by arc length. +/// +/// Each corner is two halves, each running from the middle of one edge to the +/// corner's diagonal. A circular half is a straight run and an eighth of a +/// circle. A superellipse half is Flutter's construction +/// (`impeller/geometry/round_superellipse_param.cc`): a superellipse whose +/// exponent and hand-over point come from Flutter's own table for the +/// ratio of that edge to the radius, then a circular arc to the diagonal, where +/// it meets the other half. So the outline sits on a child clipped or +/// decorated with `RoundedSuperellipseBorder` of the same radii at every +/// aspect ratio — a card, a pill, a circle. +@immutable +class BeamOutline { + /// The outline of [rect] with [radii], scaled the way `RRect.scaleRadii` + /// scales them when two radii on one side add up to more than that side. + /// + /// Elliptical radii are approximated by the mean of their two axes, and a + /// corner's radius is capped at half the shorter side. + /// + /// Each corner keeps to its own quarter of the box. Flutter instead splits + /// each side between its two corners in proportion to their radii, so with + /// uneven superellipse radii the two shapes part slightly: within ~0.1 px + /// for ordinary mixes, up to ~2% of the radius where a corner of half the + /// short side meets a square corner across that side. + factory BeamOutline( + Rect rect, + BorderRadius radii, { + bool superellipse = false, + }) { + final scaled = _scaleRadii(rect, radii); + return BeamOutline._(rect, scaled, superellipse); + } + + BeamOutline._(this.rect, this.radii, this.superellipse) { + final hx = rect.width / 2; + final hy = rect.height / 2; + final limit = math.min(hx, hy); + final horizontal = <_Half>[]; + final vertical = <_Half>[]; + // Quadrant order used by the shader: 0 TR, 1 BR, 2 BL, 3 TL. Radii are + // stored TL, TR, BR, BL. + for (var quad = 0; quad < 4; quad++) { + final r = math.min(radii[(quad + 1) % 4], limit); + if (superellipse && r >= 0.5) { + horizontal.add(_Half.superellipse(hx, r)); + vertical.add(_Half.superellipse(hy, r)); + } else { + final size = math.max(r, 1e-3); + horizontal.add(_Half.circular(hx, size)); + vertical.add(_Half.circular(hy, size)); + } + } + _horizontal = List.unmodifiable(horizontal); + _vertical = List.unmodifiable(vertical); + final lengths = [ + for (var quad = 0; quad < 4; quad++) + _horizontal[quad].length + _vertical[quad].length, + ]; + quadStarts = List.unmodifiable([ + 0.0, + lengths[0], + lengths[0] + lengths[1], + lengths[0] + lengths[1] + lengths[2], + ]); + length = lengths[0] + lengths[1] + lengths[2] + lengths[3]; + double corner(int quad) => + math.max(_horizontal[quad].reach, _vertical[quad].reach); + double arc(int quad) => + lengths[quad] - + (hx - _horizontal[quad].reach) - + (hy - _vertical[quad].reach); + cornerSizes = List.unmodifiable([ + corner(3), + corner(0), + corner(1), + corner(2), + ]); + cornerArcs = List.unmodifiable([arc(3), arc(0), arc(1), arc(2)]); + } + + /// The box the outline is inscribed in. + final Rect rect; + + /// Resolved corner radii in clockwise order: top-left, top-right, + /// bottom-right, bottom-left. + final List radii; + + /// Whether the corners are Flutter's rounded superellipse rather than + /// circular arcs. + final bool superellipse; + + // Each quadrant's two halves (0 TR, 1 BR, 2 BL, 3 TL): the one along the + // horizontal edge and the one along the vertical edge. + late final List<_Half> _horizontal; + late final List<_Half> _vertical; + + /// How far each corner's curve reaches along the edges from the box's + /// corner, in the order of [radii]: the radius for a circular corner, + /// radius × [squircleReach] for a superellipse — each capped at half the + /// side it runs along; where the two sides differ, the longer reach. + late final List cornerSizes; + + /// The arc length of each corner's curve between the straight runs it + /// joins, in the order of [radii]. + late final List cornerArcs; + + /// Arc length at which each quadrant starts: top-right, bottom-right, + /// bottom-left, top-left. + late final List quadStarts; + + /// Total perimeter length in logical px. + late final double length; + + Offset get _centre => rect.center; + double get _hx => rect.width / 2; + double get _hy => rect.height / 2; + + double _quadLength(int quad) => + _horizontal[quad].length + _vertical[quad].length; + + /// Signed distance from [point] to the outline (negative inside) and the + /// perimeter coordinate of the outline piece nearest to it. + /// + /// Matches the shader's `outline()` exactly, including the nearest-piece + /// choice: inside the shape the coordinate jumps across the medial axis, so + /// only use it on or near the border. + ({double distance, double u}) locate(Offset point) { + final p = point - _centre; + final right = p.dx > 0; + final bottom = p.dy > 0; + final quad = right ? (bottom ? 1 : 0) : (bottom ? 2 : 3); + final ax = p.dx.abs(); + final ay = p.dy.abs(); + // The halves meet on the 45° line through the corner's diagonal. + final c = _hx - _hy; + final quadLength = _quadLength(quad); + double d; + double s; + if (ax - ay <= c) { + final hit = _horizontal[quad].locate(ax, ay + c); + d = hit.d; + s = hit.s; + } else { + final hit = _vertical[quad].locate(ay, ax - c); + d = hit.d; + s = quadLength - hit.s; + } + // TR and BL run horizontal edge → vertical edge clockwise; BR and TL run + // the other way, so their local arc length is mirrored. + final mirrored = quad == 1 || quad == 3; + if (mirrored) s = quadLength - s; + final u = length <= 0 ? 0.0 : _wrap((quadStarts[quad] + s) / length); + return (distance: d, u: u); + } + + /// The perimeter coordinate nearest [point] (see [locate]). + double nearestFraction(Offset point) => locate(point).u; + + /// The point on the outline at perimeter coordinate [u]. + Offset pointAt(double u) => _sample(u).point; + + /// The outward unit normal at perimeter coordinate [u]. + Offset normalAt(double u) => _sample(u).normal; + + ({Offset point, Offset normal}) _sample(double u) { + if (length <= 0) { + return (point: rect.topCenter, normal: const Offset(0, -1)); + } + var s = _wrap(u) * length; + var quad = 3; + for (var i = 1; i < 4; i++) { + if (s < quadStarts[i]) { + quad = i - 1; + break; + } + } + s -= quadStarts[quad]; + final quadLength = _quadLength(quad); + final mirrored = quad == 1 || quad == 3; + if (mirrored) s = quadLength - s; + final c = _hx - _hy; + double ax; + double ay; + double nx; + double ny; + final horizontal = _horizontal[quad]; + if (s <= horizontal.length) { + final at = horizontal.sample(s); + ax = at.x; + ay = at.y - c; + nx = at.nx; + ny = at.ny; + } else { + final at = _vertical[quad].sample(quadLength - s); + ax = at.y + c; + ay = at.x; + nx = at.ny; + ny = at.nx; + } + final right = quad == 0 || quad == 1; + final bottom = quad == 1 || quad == 2; + final sx = right ? 1.0 : -1.0; + final sy = bottom ? 1.0 : -1.0; + return ( + point: _centre + Offset(ax * sx, ay * sy), + normal: Offset(nx * sx, ny * sy), + ); + } + + /// The perimeter coordinates at which the straight run of [edge] starts and + /// ends, clockwise. + ({double from, double to}) edgeRange(BeamEdge edge) { + // Where each quadrant's run along its horizontal or vertical edge ends, + // as arc length from the start of the quadrant. + double horizontal(int quad) { + final run = _hx - _horizontal[quad].reach; + return quad == 1 || quad == 3 ? _quadLength(quad) - run : run; + } + + double vertical(int quad) { + final run = _hy - _vertical[quad].reach; + return quad == 1 || quad == 3 ? run : _quadLength(quad) - run; + } + + final (fromQuad, from, toQuad, to) = switch (edge) { + BeamEdge.top => (3, horizontal(3), 0, horizontal(0)), + BeamEdge.right => (0, vertical(0), 1, vertical(1)), + BeamEdge.bottom => (1, horizontal(1), 2, horizontal(2)), + BeamEdge.left => (2, vertical(2), 3, vertical(3)), + }; + return (from: _fraction(fromQuad, from), to: _fraction(toQuad, to)); + } + + double _fraction(int quad, double s) => + length <= 0 ? 0.0 : _wrap((quadStarts[quad] + s) / length); + + /// The perimeter coordinates at which [corner]'s curve starts and ends, + /// clockwise. + ({double from, double to}) cornerRange(BeamCorner corner) => switch (corner) { + BeamCorner.topLeft => ( + from: edgeRange(BeamEdge.left).to, + to: edgeRange(BeamEdge.top).from, + ), + BeamCorner.topRight => ( + from: edgeRange(BeamEdge.top).to, + to: edgeRange(BeamEdge.right).from, + ), + BeamCorner.bottomRight => ( + from: edgeRange(BeamEdge.right).to, + to: edgeRange(BeamEdge.bottom).from, + ), + BeamCorner.bottomLeft => ( + from: edgeRange(BeamEdge.bottom).to, + to: edgeRange(BeamEdge.left).from, + ), + }; + + /// The coordinate [t] of the way along [edge]'s straight run, clockwise. + double fractionOfEdge(BeamEdge edge, double t) { + final range = edgeRange(edge); + return _along(range.from, range.to, t); + } + + /// The coordinate [t] of the way through [corner]'s curve, clockwise. + double fractionOfCorner(BeamCorner corner, double t) { + final range = cornerRange(corner); + return _along(range.from, range.to, t); + } + + static double _along(double from, double to, double t) { + final span = _wrap(to - from); + return _wrap(from + span * t.clamp(0.0, 1.0)); + } + + /// Wraps [x] into `[0, 1)`. + static double wrapFraction(double x) => _wrap(x); + + static double _wrap(double x) { + final r = x % 1; + return r < 0 ? r + 1 : r; + } + + /// The `RRect.scaleRadii` clamp, then each corner's elliptical radius + /// reduced to the mean of its axes. Order: TL, TR, BR, BL. + static List _scaleRadii(Rect rect, BorderRadius radii) { + final half = rect.shortestSide / 2; + double axis(double v) { + final floored = math.max(0.0, v); + return floored.isFinite ? floored : half; + } + + final tl = Offset(axis(radii.topLeft.x), axis(radii.topLeft.y)); + final tr = Offset(axis(radii.topRight.x), axis(radii.topRight.y)); + final br = Offset(axis(radii.bottomRight.x), axis(radii.bottomRight.y)); + final bl = Offset(axis(radii.bottomLeft.x), axis(radii.bottomLeft.y)); + var scale = 1.0; + double limit(double side, double sum) => + sum <= 0 ? scale : math.min(scale, side / sum); + scale = limit(rect.width, tl.dx + tr.dx); + scale = limit(rect.height, tr.dy + br.dy); + scale = limit(rect.width, bl.dx + br.dx); + scale = limit(rect.height, tl.dy + bl.dy); + double mean(Offset r) => (r.dx + r.dy) / 2 * scale; + return List.unmodifiable([mean(tl), mean(tr), mean(br), mean(bl)]); + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is BeamOutline && + other.rect == rect && + other.superellipse == superellipse && + listEquals(other.radii, radii); + + @override + int get hashCode => Object.hash(rect, superellipse, Object.hashAll(radii)); +} + +/// Flutter's `kGapFactor`: the corner's diagonal point sits this many radii +/// in from both sides, where a circular corner of the same radius would. +const double _gapFactor = 0.29289321881; + +/// Flutter's precomputed `(n, 1 / (1 - xJ / a))` for ratios `2a / radius` of +/// 2.0–2.5 in steps of 0.1, then 3.0–5.0 in steps of 0.5; linear beyond. +const List<(double, double)> _rseTable = [ + (2.00000000, 1.13276676), + (2.18349805, 1.20311921), + (2.33888662, 1.28698796), + (2.48660575, 1.36351941), + (2.62226596, 1.44717976), + (2.75148990, 1.53385819), + (3.36298265, 1.98288283), + (4.08649929, 2.23811846), + (4.85481134, 2.47563463), + (5.62945551, 2.72948597), + (6.43023796, 2.98020421), +]; + +/// Half of a corner, in a frame where its edge runs along `y = a`, `x` is +/// measured from the middle of that edge, and the corner's diagonal is the +/// line `x = y`. +/// +/// Along the edge the outline runs straight to [a] − [reach], then curves — +/// for a superellipse half along `|x/a|ⁿ + |y/a|ⁿ = 1` to the joint `(xJ, +/// yJ)` — and finishes with a circular arc of [radius] about `(cx, cy)` through +/// [span] radians to the diagonal. A circular half is the straight run and an +/// eighth of a circle. +@immutable +class _Half { + const _Half._({ + required this.a, + required this.reach, + required this.n, + required this.xJ, + required this.yJ, + required this.nJx, + required this.nJy, + required this.cx, + required this.cy, + required this.radius, + required this.span, + }); + + /// A circular half of radius [r]. + factory _Half.circular(double a, double r) => _Half._( + a: a, + reach: r, + n: 0, + xJ: a - r, + yJ: a, + nJx: 0, + nJy: 1, + cx: a - r, + cy: a - r, + radius: r, + span: math.pi / 4, + ); + + /// Flutter's superellipse half for radius [r] (`ComputeOctant`). + factory _Half.superellipse(double a, double r) { + final (n, xJOverA) = _exponentAndJoint(2 * a / r); + final joint = _onCurve(xJOverA, n); + final xJ = xJOverA * a; + final yJ = joint.y * a; + // Flutter sizes the arc by where the superellipse's normal at the joint + // crosses the diagonal, then centres it on the joint and the diagonal + // point `g` in from both sides. + final tanPhi = joint.nx / joint.ny; + final onDiagonal = (xJ - tanPhi * yJ) / (1 - tanPhi); + final g = _gapFactor * r; + final radius = (a - onDiagonal - g) * math.sqrt2; + final mx = a - g; + final chordX = mx - xJ; + final chordY = mx - yJ; + final chord = math.sqrt(chordX * chordX + chordY * chordY); + final rise = math.sqrt(math.max(radius * radius - chord * chord / 4, 0)); + final cx = (xJ + mx) / 2 + rise * chordY / chord; + final cy = (yJ + mx) / 2 - rise * chordX / chord; + // The arc turns clockwise from the joint to the diagonal point. + final jx = xJ - cx; + final jy = yJ - cy; + final ex = mx - cx; + final ey = mx - cy; + final span = math.atan2(jy * ex - jx * ey, jx * ex + jy * ey); + return _Half._( + a: a, + reach: math.min(squircleReach * r, a), + n: n, + xJ: xJ, + yJ: yJ, + nJx: joint.nx, + nJy: joint.ny, + cx: cx, + cy: cy, + radius: radius, + span: span, + ); + } + + /// Flutter's `ComputeNAndXj`: the exponent and `xJ / a` for [ratio]. + static (double, double) _exponentAndJoint(double ratio) { + double n; + double k; + if (ratio > 5) { + final (n5, k5) = _rseTable.last; + n = n5 + 1.559599389 * (ratio - 5); + k = k5 + 0.522807185 * (ratio - 5); + } else { + final clamped = ratio.clamp(2.0, 5.0); + final steps = clamped < 2.5 + ? (clamped - 2) * 10 + : (clamped - 2.5) * 2 + 5; + final left = steps.floor().clamp(0, _rseTable.length - 2); + final frac = steps - left; + final (n0, k0) = _rseTable[left]; + final (n1, k1) = _rseTable[left + 1]; + n = n0 + (n1 - n0) * frac; + k = k0 + (k1 - k0) * frac; + } + return (n, 1 - 1 / k); + } + + /// The unit superellipse of exponent [n] above `x = t` (`0 < t < 1`): its + /// height and outward normal. + static ({double y, double nx, double ny}) _onCurve(double t, double n) { + final tn = math.pow(t, n).toDouble(); + final y = math.pow(1 - tn, 1 / n).toDouble(); + final gx = tn / t; + final gy = (1 - tn) / y; + final gl = math.sqrt(gx * gx + gy * gy); + return (y: y, nx: gx / gl, ny: gy / gl); + } + + final double a; + final double reach; + + /// The superellipse exponent, or 0 for a circular half. + final double n; + final double xJ; + final double yJ; + + /// The superellipse's outward normal at the joint. + final double nJx; + final double nJy; + final double cx; + final double cy; + final double radius; + final double span; + + /// Arc length from the middle of the edge to the diagonal. The run up to + /// the joint is measured along `x`: the superellipse there stays within a + /// few degrees of level, so this is short of its true length by under + /// 0.1 px. + double get length => xJ + radius * span; + + /// Signed distance to this half, arc length from the middle of the edge, + /// and outward normal, for a point `(x, y)` on its side of the diagonal. + /// + /// The shape is convex, so the signed distance to any line it rests + /// against never exceeds the signed distance to the shape. Off the arc the + /// distance is the largest of a few such lines: the tangent above or below + /// the point, the tangent at the joint, and the box's two sides — exact on + /// the curve, and continuous across the joint inside and out. + ({double d, double s, double nx, double ny}) locate(double x, double y) { + if (x <= a - reach) return (d: y - a, s: x, nx: 0, ny: 1); + final box = math.max(x - a, y - a); + final jx = xJ - cx; + final jy = yJ - cy; + final px = x - cx; + final py = y - cy; + if (n == 0 || jx * py - jy * px <= 0) { + // Past the joint, clockwise: the arc. + final l = math.max(math.sqrt(px * px + py * py), 1e-4); + final theta = math.atan2(jy * px - jx * py, jx * px + jy * py); + return ( + d: math.max(l - radius, box), + s: xJ + radius * theta, + nx: px / l, + ny: py / l, + ); + } + // The superellipse: the tangent at the curve point straight above or + // below, up to the joint. + final xb = math.min(x, xJ); + final b = _onCurve(math.max(xb / a, 1e-4), n); + final along = (x - xb) * b.nx + (y - b.y * a) * b.ny; + final atJoint = (x - xJ) * nJx + (y - yJ) * nJy; + return ( + d: math.max(math.max(along, atJoint), box), + s: x - along * b.nx, + nx: b.nx, + ny: b.ny, + ); + } + + /// The point at arc length [s] from the middle of the edge, and the + /// outward normal there. + ({double x, double y, double nx, double ny}) sample(double s) { + if (s <= xJ) { + if (n == 0 || s <= a - reach) return (x: s, y: a, nx: 0, ny: 1); + final b = _onCurve(math.max(s / a, 1e-4), n); + return (x: s, y: b.y * a, nx: b.nx, ny: b.ny); + } + final theta = (s - xJ) / radius; + final cos = math.cos(theta); + final sin = math.sin(theta); + final jx = (xJ - cx) / radius; + final jy = (yJ - cy) / radius; + // Rotate the joint's radius clockwise by theta. + final vx = jx * cos + jy * sin; + final vy = jy * cos - jx * sin; + return (x: cx + radius * vx, y: cy + radius * vy, nx: vx, ny: vy); + } +} diff --git a/lib/src/render/beam_painter.dart b/lib/src/render/beam_painter.dart new file mode 100644 index 0000000..46957e6 --- /dev/null +++ b/lib/src/render/beam_painter.dart @@ -0,0 +1,122 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; + +import '../animation/beam_clock.dart'; +import '../animation/beam_phases.dart'; +import '../models/beam_config.dart'; +import 'beam_program.dart'; +import 'beam_renderer.dart'; + +/// The beam's [CustomPainter]: samples the phases for this frame and hands +/// them to the [BeamRenderer]. Repaints are driven directly by the +/// [BeamClock] — no widget rebuilds per frame. +class BeamPainter extends CustomPainter with Diagnosticable { + /// Creates a painter bound to [clock]. + BeamPainter({ + required this.renderer, + required this.clock, + required this.config, + required this.resolver, + required this.staticMode, + required this.devicePixelRatio, + this.progress, + this.strength, + this.frozenAt, + }) : super( + repaint: Listenable.merge([ + clock, + BeamProgram.ready, + ?progress, + ?strength, + ]), + ); + + /// Draws the frames; owned by the widget's state. + final BeamRenderer renderer; + + /// The time source; also the repaint trigger. + final BeamClock clock; + + /// Resolved beam configuration. + final BeamConfig config; + + /// Phase computer. + final BeamPhaseResolver resolver; + + /// Reduced-motion mode: paint one static frame, ignore the clock. + final bool staticMode; + + /// Device pixels per logical pixel, for anti-aliasing. + final double devicePixelRatio; + + /// The externally driven sweep position (0–1), or null when nothing + /// drives it. + final ValueListenable? progress; + + /// A per-frame multiplier on the beam's opacity, or null for none. + final ValueListenable? strength; + + /// The timeline position every frame is sampled at, or null to follow the + /// clock (`BeamPlayback.debugFrozenAt`). + final Duration? frozenAt; + + @override + void paint(Canvas canvas, Size size) { + final driven = progress?.value; + final BeamFramePhases phases; + final frozen = frozenAt; + if (frozen != null) { + phases = resolver.sample( + frozen.inMicroseconds / Duration.microsecondsPerSecond, + strength?.value ?? 1, + progress: driven, + ); + } else if (staticMode) { + phases = resolver.staticFrame(progress: driven); + } else { + if (!clock.isVisible) return; + final amplitude = clock.boost * (strength?.value ?? 1); + phases = resolver.sample( + clock.elapsedSeconds, + clock.fadeOpacity * amplitude, + progress: driven, + ); + } + renderer.paint( + canvas, + Offset.zero & size, + config, + phases, + devicePixelRatio: devicePixelRatio, + ); + } + + @override + bool shouldRepaint(BeamPainter oldDelegate) => + oldDelegate.config != config || + oldDelegate.renderer != renderer || + oldDelegate.staticMode != staticMode || + oldDelegate.clock != clock || + oldDelegate.devicePixelRatio != devicePixelRatio || + oldDelegate.progress != progress || + oldDelegate.strength != strength || + oldDelegate.frozenAt != frozenAt; + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties + ..add(DiagnosticsProperty('config', config)) + ..add( + FlagProperty('staticMode', value: staticMode, ifTrue: 'static frame'), + ) + ..add(DoubleProperty('elapsedSeconds', clock.elapsedSeconds)) + ..add(DoubleProperty('fadeOpacity', clock.fadeOpacity)) + ..add(DoubleProperty('boost', clock.boost, defaultValue: 1.0)) + ..add(DoubleProperty('progress', progress?.value, defaultValue: null)) + ..add(DoubleProperty('strength', strength?.value, defaultValue: null)) + ..add( + DiagnosticsProperty('frozenAt', frozenAt, defaultValue: null), + ); + } +} diff --git a/lib/src/render/beam_program.dart b/lib/src/render/beam_program.dart new file mode 100644 index 0000000..62bca3c --- /dev/null +++ b/lib/src/render/beam_program.dart @@ -0,0 +1,82 @@ +import 'dart:async'; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; + +/// Loads the beam shader once per process and shares it. +/// +/// `FragmentProgram.fromAsset` is asynchronous. Until it resolves, beams +/// paint nothing — their fade-in hides the few milliseconds this takes — and +/// [ready] flips once it has, so a painter that is not ticking (a static +/// reduced-motion frame) still repaints when the program arrives. +abstract final class BeamProgram { + // A consuming app resolves package assets under `packages//`; the + // package's own tests resolve them at the bare path. + static const List _keys = [ + 'packages/flutter_border_beam/shaders/beam.frag', + 'shaders/beam.frag', + ]; + + static ui.FragmentProgram? _program; + static Future? _loading; + static Zone? _loadingZone; + static bool _reported = false; + static final ValueNotifier _ready = ValueNotifier(false); + + /// The loaded program, or null until [load] completes. + static ui.FragmentProgram? get program => _program; + + /// Becomes true once the program has loaded. + static ValueListenable get ready => _ready; + + /// Starts loading the program if it has not been loaded yet, and completes + /// when it is available (or when loading failed). + /// + /// Safe to call repeatedly: a call while a load is in flight shares that + /// load. Only a load started in the same zone is shared. One started in a + /// zone that has since gone away, as in a widget test's fake clock, may + /// never complete, so a caller in another zone starts its own rather than + /// awaiting it forever. + static Future load() { + if (_program != null) return Future.value(); + final pending = _loading; + if (pending != null && identical(_loadingZone, Zone.current)) { + return pending; + } + late final Future loading; + loading = _load().whenComplete(() { + // A failed load is forgotten, so a later call retries. + if (identical(_loading, loading)) _loading = null; + }); + _loadingZone = Zone.current; + return _loading = loading; + } + + static Future _load() async { + Object? lastError; + StackTrace? lastStack; + for (final key in _keys) { + try { + final program = await ui.FragmentProgram.fromAsset(key); + // A load from another zone may have finished first; keep its program. + _program ??= program; + _ready.value = true; + return; + } on Object catch (error, stack) { + lastError = error; + lastStack = stack; + } + } + if (!_reported && lastError != null) { + _reported = true; + FlutterError.reportError( + FlutterErrorDetails( + exception: lastError, + stack: lastStack, + library: 'flutter_border_beam', + context: ErrorDescription('while loading the beam shader'), + ), + ); + } + } +} diff --git a/lib/src/render/beam_renderer.dart b/lib/src/render/beam_renderer.dart new file mode 100644 index 0000000..c5e0b7c --- /dev/null +++ b/lib/src/render/beam_renderer.dart @@ -0,0 +1,162 @@ +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flutter/painting.dart'; + +import '../animation/beam_phases.dart'; +import '../effects/effect_emitters.dart'; +import '../models/beam_config.dart'; +import 'beam_frame.dart'; +import 'beam_outline.dart'; +import 'beam_program.dart'; + +export 'beam_frame.dart' show beamUniformFloats; + +/// Paints beam frames with the shared shader. +/// +/// One renderer per beam: it owns a `FragmentShader` (reused every frame, its +/// uniforms rewritten in place), a `Paint`, and a [BeamFrameData], so a frame +/// allocates almost nothing. A frame is one `drawDRRect` — the ring of the +/// canvas where light can reach — with no layers, clips, or filters. +class BeamRenderer { + ui.FragmentShader? _shader; + final Paint _paint = Paint()..isAntiAlias = false; + final BeamFrameData _frame = BeamFrameData(); + BeamOutline? _outline; + + /// The uniforms of the last painted frame, for tests. + BeamFrameData get debugFrame => _frame; + + /// Paints one frame of [config] at [phases] over [box] (the child's + /// bounds in canvas coordinates). + /// + /// The frame's opacity is `phases.fadeOpacity` — which already carries the + /// fade, any boost, and the live strength — times `config.strength`; a + /// frame at zero opacity draws nothing. [devicePixelRatio] sets the + /// anti-aliasing width; the canvas's own scale is folded in. + void paint( + Canvas canvas, + Rect box, + BeamConfig config, + BeamFramePhases phases, { + required double devicePixelRatio, + }) { + final program = BeamProgram.program; + if (program == null) return; + final alpha = phases.fadeOpacity * config.strength; + // Also rejects NaN, which a live strength could hand in. + if (!(alpha > 0)) return; + final rect = box.inflate(config.ringOffset); + if (rect.width < 1 || rect.height < 1) return; + + final outline = _outlineFor(rect, config); + if (outline.length <= 0) return; + + final px = 1 / math.max(devicePixelRatio * _canvasScale(canvas), 0.25); + final d = _frame..reset(); + d.setOutline(outline, config.borderWidth, px); + applyTrack(d, config.segment, outline, config.dashes); + emitEffect( + BeamFrame( + config: config, + phases: phases, + outline: outline, + data: d, + alpha: alpha, + ), + ); + d.finish(); + _measure(d, config.borderWidth); + var lit = false; + for (var k = 0; k < beamLayerCount; k++) { + if (d.geometryOf(k) != BeamGeometry.none && d.opacityOf(k) > 0) { + lit = true; + } + } + if (!lit) return; + + final shader = _shader ??= program.fragmentShader(); + final data = d.data; + for (var i = 0; i < beamUniformFloats; i++) { + shader.setFloat(i, data[i]); + } + + // Fragment work only where light can land: the box grown by the furthest + // outward reach, minus the interior beyond the furthest inward reach. + _paint.shader = shader; + final outer = rect.inflate(d.reachOutside + 2); + final inside = d.reachInside + 2; + final maxCorner = outline.cornerSizes.reduce(math.max); + final hole = math.max(inside, inside / math.sqrt2 + 0.3 * maxCorner); + if (!hole.isFinite || 2 * hole >= rect.shortestSide) { + canvas.drawRect(outer, _paint); + } else { + canvas.drawDRRect( + RRect.fromRectAndRadius(outer, Radius.zero), + RRect.fromRectAndRadius(rect.deflate(hole), Radius.zero), + _paint, + ); + } + } + + // How far the frame's layers reach either side of the outline. + static void _measure(BeamFrameData d, double borderWidth) { + var outside = 0.0; + var inside = borderWidth + 1; + for (var k = 0; k < beamLayerCount; k++) { + if (d.opacityOf(k) <= 0) continue; + final sigma = d.sigmaOf(k); + switch (d.geometryOf(k)) { + case BeamGeometry.none: + break; + case BeamGeometry.ring: + break; + case BeamGeometry.fill: + final edge = d.edgeFadeOf(k); + inside = math.max(inside, edge > 0 ? edge + 1 : double.infinity); + case BeamGeometry.blurredRing: + inside = math.max(inside, 3 * sigma + borderWidth); + case BeamGeometry.glow: + outside = math.max(outside, d.inflateOf(k) + 3 * sigma); + } + } + d + ..reachOutside = outside + ..reachInside = inside; + } + + BeamOutline _outlineFor(Rect rect, BeamConfig config) { + final cached = _outline; + if (cached != null && + cached.rect == rect && + cached.superellipse == config.superellipse && + _outlineRadius == config.borderRadius) { + return cached; + } + _outlineRadius = config.borderRadius; + return _outline = BeamOutline( + rect, + config.borderRadius, + superellipse: config.superellipse, + ); + } + + // The radius the cached outline was built from. + BorderRadius? _outlineRadius; + + // The canvas's own scale (a Transform painted into the same layer), so the + // anti-aliasing width stays one device pixel under it. + static double _canvasScale(Canvas canvas) { + final m = canvas.getTransform(); + final sx = math.sqrt(m[0] * m[0] + m[1] * m[1]); + final sy = math.sqrt(m[4] * m[4] + m[5] * m[5]); + final s = math.sqrt(sx * sy); + return s.isFinite && s > 0 ? s : 1; + } + + /// Releases the shader. + void dispose() { + _shader?.dispose(); + _shader = null; + } +} diff --git a/lib/src/render/color_math.dart b/lib/src/render/color_math.dart new file mode 100644 index 0000000..4180498 --- /dev/null +++ b/lib/src/render/color_math.dart @@ -0,0 +1,46 @@ +import 'dart:math' as math; +import 'dart:ui'; + +/// Gamma-aware mix of two colours: squared channels (≈ linear light) are +/// interpolated, so the midpoint of two saturated colours stays bright. +Color mixColor(Color a, Color b, double t) { + double ch(double x, double y) => + math.sqrt(math.max(0, x * x + (y * y - x * x) * t)); + return Color.from( + alpha: a.a + (b.a - a.a) * t, + red: ch(a.r, b.r), + green: ch(a.g, b.g), + blue: ch(a.b, b.b), + ); +} + +/// Samples a cyclic (or clamped) list of colour [stops] at [cu], blending +/// the two stops either side of it with [mixColor]. +/// +/// With [wrap] the ring is seamless: past the last stop the colour blends +/// back into the first. Palettes are blended here, on the CPU, when they are +/// sampled into blob tables — palette stops never reach the shader. +Color samplePalette( + List colors, + List stops, + double cu, { + required bool wrap, +}) { + final n = colors.length; + if (n == 1) return colors.first; + var prevC = wrap ? colors[n - 1] : colors[0]; + var prevS = wrap ? stops[n - 1] - 1 : stops[0] - 1; + for (var i = 0; i < n; i++) { + final s = stops[i]; + if (cu < s) { + final span = math.max(s - prevS, 1e-5); + return mixColor(prevC, colors[i], ((cu - prevS) / span).clamp(0.0, 1.0)); + } + prevC = colors[i]; + prevS = s; + } + final nextC = wrap ? colors[0] : prevC; + final nextS = wrap ? stops[0] + 1 : prevS + 1; + final span = math.max(nextS - prevS, 1e-5); + return mixColor(prevC, nextC, ((cu - prevS) / span).clamp(0.0, 1.0)); +} diff --git a/lib/src/widgets/beam_decoration.dart b/lib/src/widgets/beam_decoration.dart index ab95766..7499829 100644 --- a/lib/src/widgets/beam_decoration.dart +++ b/lib/src/widgets/beam_decoration.dart @@ -7,6 +7,7 @@ import 'package:flutter/scheduler.dart'; import '../animation/beam_clock.dart'; import '../animation/beam_phases.dart'; import '../border_beam_theme.dart'; +import '../effects/beam_effect.dart'; import '../models/beam_colors.dart'; import '../models/beam_config.dart'; import '../models/beam_playback.dart'; @@ -14,10 +15,9 @@ import '../models/beam_shape.dart'; import '../models/beam_style.dart'; import '../models/beam_theme.dart'; import '../models/beam_timing.dart'; -import '../models/beam_variant.dart'; import '../models/model_validation.dart'; -import '../painting/beam_painter.dart'; -import '../painting/variant_strategy.dart'; +import '../render/beam_program.dart'; +import '../render/beam_renderer.dart'; /// A beam as a [Decoration], for dropping into an existing /// `Container`/`DecoratedBox` instead of wrapping the subtree in a @@ -26,7 +26,7 @@ import '../painting/variant_strategy.dart'; /// ```dart /// Container( /// foregroundDecoration: BeamDecoration( -/// variant: BeamVariant.rotate, +/// effect: const BeamEffect.rotate(), /// brightness: Theme.of(context).brightness, /// colors: BeamColors.ocean, /// borderRadius: 16, @@ -45,19 +45,12 @@ import '../painting/variant_strategy.dart'; /// /// ## Which slot /// -/// A decoration paints in exactly one slot, so the variant decides which: -/// -/// | Variant | Slot | -/// | --- | --- | -/// | [BeamVariant.rotate], [BeamVariant.small], [BeamVariant.line], [BeamVariant.pulseInside] | `foregroundDecoration:` | -/// | [BeamVariant.pulseOutside] | `decoration:` | -/// -/// `BorderBeam` paints every layer of the first four *over* its child, which -/// is what `foregroundDecoration:` does — put them in `decoration:` only when -/// the beam is meant to sit under opaque content. -/// [BeamVariant.pulseOutside] is the opposite case: its halo blooms behind -/// and outside the child, so it belongs in `decoration:`, and the child needs -/// the same clip-free room around it that the widget form requires. +/// The beam draws its light over whatever is beneath it, so put it in +/// `foregroundDecoration:` — the same place `BorderBeam` paints, over the +/// child. Use `decoration:` only when the beam should sit under opaque +/// content. Light that reaches outward — rotate's `comet`, a positive +/// `shape.ringOffset` — paints past the box, so leave clip-free room around +/// it either way. /// /// ## Limits of the decoration form /// @@ -89,15 +82,15 @@ import '../painting/variant_strategy.dart'; /// hits fall through to the child exactly as they do under `BorderBeam`. @immutable class BeamDecoration extends Decoration { - /// Creates a beam decoration for [variant]. + /// Creates a beam decoration painting [effect]. /// /// [brightness] is the ambient brightness the beam adapts to — normally /// `Theme.of(context).brightness`; `style.theme` still overrides it. /// [theme] stands in for the enclosing `BorderBeamTheme`: pass /// `BorderBeamTheme.of(context)` to inherit app-wide defaults. const BeamDecoration({ - required this.variant, required this.brightness, + this.effect, this.theme, this.colors, this.active, @@ -108,8 +101,12 @@ class BeamDecoration extends Decoration { this.playback, }); - /// Which effect this decoration paints. - final BeamVariant variant; + /// What the light does. Null inherits [theme]'s effect, and then + /// [BeamEffect.rotate]. + final BeamEffect? effect; + + BeamEffect get _effect => + effect ?? theme?.effect ?? const BeamEffect.rotate(); /// The ambient brightness the beam adapts to, since a painter cannot read /// one. `style.theme` (a [BeamTheme] other than [BeamTheme.auto]) wins. @@ -130,13 +127,14 @@ class BeamDecoration extends Decoration { /// here wins over it. Match the decorated box's own radius. final double? borderRadius; - /// Colors, theme adaptation, and every filter/opacity tuning hook. + /// Colours, surface brightness, strength, glow, and hue drift. final BeamStyle? style; - /// Corner radii, ring width, and corner family. + /// Corner radii, corner family, stroke width, segment, and dashes. final BeamShape? shape; - /// Cycle length, rest between sweeps, playback rate, and hue periods. + /// Cycle length, rest between sweeps, playback rate, direction, and the + /// hue drift period. final BeamTiming? timing; /// Play state and scheduling. [BeamPlayback.reducedMotion] is inert here. @@ -183,7 +181,7 @@ class BeamDecoration extends Decoration { bool operator ==(Object other) => identical(this, other) || other is BeamDecoration && - other.variant == variant && + other.effect == effect && other.brightness == brightness && other.theme == theme && other.colors == colors && @@ -196,7 +194,7 @@ class BeamDecoration extends Decoration { @override int get hashCode => Object.hash( - variant, + effect, brightness, theme, colors, @@ -212,7 +210,7 @@ class BeamDecoration extends Decoration { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties - ..add(EnumProperty('variant', variant)) + ..add(DiagnosticsProperty('effect', _effect)) ..add(EnumProperty('brightness', brightness)) ..add( DiagnosticsProperty( @@ -235,12 +233,17 @@ class BeamDecoration extends Decoration { // that comes with one (see the class docs on BeamDecoration). class _BeamBoxPainter extends BoxPainter { _BeamBoxPainter(this._decoration, super.onChanged) - : _strategy = strategyFor(_decoration.variant) { + : _repeatCycles = validateRepeat(_decoration._playback.repeat) { validateBeamTiming(_decoration._timing); - validateRepeat(_decoration._playback.repeat); + // The repeat budget is counted on the resolver from the first tick, so + // it exists before anything is painted: a box that ticks through its + // cycles with nothing to paint (an empty size) still runs out of them, + // rather than showing a spent beam the first time it gets a size. Text + // direction moves only the corners, never the count; the first paint + // re-resolves for its own. + _configFor(TextDirection.ltr); _clock = BeamClock( createTicker: Ticker.new, - maxFps: _strategy.preferredFps, fadeCurve: _decoration._playback.fadeCurve, )..speed = _decoration._timing.speed ?? 1; _schedule(); @@ -248,26 +251,29 @@ class _BeamBoxPainter extends BoxPainter { // object's paint, where onChanged (markNeedsPaint) is illegal, and // _schedule may activate the clock synchronously. _clock.addListener(_handleTick); + if (BeamProgram.program == null) { + BeamProgram.ready.addListener(_handleTick); + BeamProgram.load(); + } } final BeamDecoration _decoration; - final BeamVariantStrategy _strategy; + final int? _repeatCycles; late final BeamClock _clock; + final BeamRenderer _renderer = BeamRenderer(); Timer? _startTimer; Timer? _durationTimer; BeamConfig? _config; - // _config re-authored for renderScale, or _config itself at scale 1 — - // built with the config so a frame never allocates one. - BeamConfig? _painted; BeamPhaseResolver? _resolver; TextDirection? _configDirection; bool _disposed = false; // Mirrors BorderBeam's autoplay: `active`/`autoPlay` gate the start, - // `startAfter` delays it, `duration` ends it. There is no controller here — - // a controller attaches to a widget's clock, not a painter's. + // `startAfter` delays it, `duration` and `repeat` end it. There is no + // controller here — a controller attaches to a widget's clock, not a + // painter's. void _schedule() { final playback = _decoration._playback; // A frozen beam paints one instant forever; its clock never starts. @@ -288,14 +294,26 @@ class _BeamBoxPainter extends BoxPainter { if (duration != null) _durationTimer = Timer(duration, _clock.deactivate); } - void _handleTick() => onChanged?.call(); + void _handleTick() { + _checkRepeatBudget(); + onChanged?.call(); + } + + // Once the repeat budget is spent the beam fades out the way an inactive + // one does, so the last cycle ends on a fade rather than a cut. + void _checkRepeatBudget() { + final resolver = _resolver; + if (resolver == null || resolver.repeatCycles == null) return; + if (!_clock.isVisible || _clock.stage == BeamFadeStage.fadingOut) return; + if (resolver.finishedAt(_clock.elapsedSeconds)) _clock.deactivate(); + } BeamConfig _configFor(TextDirection textDirection) { if (_config != null && _configDirection == textDirection) return _config!; final style = _decoration._style; _configDirection = textDirection; _config = BeamConfig.resolve( - variant: _decoration.variant, + effect: _decoration._effect, palette: (style.colors ?? BeamColors.colorful).resolve(), brightness: (style.theme ?? BeamTheme.auto).resolve( _decoration.brightness, @@ -305,9 +323,7 @@ class _BeamBoxPainter extends BoxPainter { timing: _decoration._timing, textDirection: textDirection, ); - _resolver = BeamPhaseResolver(_config!); - final scale = _config!.renderScale; - _painted = scale >= 1 ? _config : _config!.scaledBy(scale); + _resolver = BeamPhaseResolver(_config!)..repeatCycles = _repeatCycles; return _config!; } @@ -324,22 +340,13 @@ class _BeamBoxPainter extends BoxPainter { 1, ) : _resolver!.sample(_clock.elapsedSeconds, _clock.fadeOpacity); - // renderScale paints the beam into a smaller box and magnifies it back, - // so a palette authored for a card reads on a screen-sized one. - final scale = config.renderScale; - final painted = _painted!; - final paintedSize = scale >= 1 - ? size - : Size(size.width * scale, size.height * scale); - canvas.save(); - canvas.translate(offset.dx, offset.dy); - if (scale < 1) canvas.scale(1 / scale); - // Both passes land in this one slot; BeamDecoration's docs say which slot - // to hand the variant so they land on the right side of the child. - _strategy - ..paintBehind(canvas, paintedSize, painted, phases) - ..paintAbove(canvas, paintedSize, painted, phases); - canvas.restore(); + _renderer.paint( + canvas, + offset & size, + config, + phases, + devicePixelRatio: configuration.devicePixelRatio ?? 1, + ); } @override @@ -347,9 +354,11 @@ class _BeamBoxPainter extends BoxPainter { _disposed = true; _startTimer?.cancel(); _durationTimer?.cancel(); + BeamProgram.ready.removeListener(_handleTick); _clock ..removeListener(_handleTick) ..dispose(); + _renderer.dispose(); super.dispose(); } } diff --git a/lib/src/widgets/beam_focus_ring.dart b/lib/src/widgets/beam_focus_ring.dart index 39834d5..233ec13 100644 --- a/lib/src/widgets/beam_focus_ring.dart +++ b/lib/src/widgets/beam_focus_ring.dart @@ -2,11 +2,12 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import '../border_beam.dart'; +import '../border_beam_theme.dart'; +import '../effects/beam_effect.dart'; import '../models/beam_colors.dart'; import '../models/beam_shape.dart'; import '../models/beam_style.dart'; import '../models/beam_timing.dart'; -import '../models/beam_variant.dart'; /// Lights a beam around [child] while it holds keyboard focus. /// @@ -23,8 +24,8 @@ import '../models/beam_variant.dart'; /// form wrapped in one ring should do. Pass [focusNode] to follow one /// specific node instead — including a node that lives outside this subtree. /// -/// Focus comes and goes with the beam's own fades (0.6s in, 0.5s out) rather -/// than a cut, because the ring only flips `BorderBeam`'s `active`. +/// Focus comes and goes with the beam's own fades (about 0.5s in, 0.6s out) +/// rather than a cut, because the ring only flips `BorderBeam`'s `active`. /// /// ## Highlight mode /// @@ -46,8 +47,8 @@ class BeamFocusRing extends StatefulWidget { super.key, required this.child, this.focusNode, - this.variant = BeamVariant.small, - this.colors = BeamColors.ocean, + this.effect = const BeamEffect.rotate(), + this.colors, this.borderRadius, this.style, this.shape, @@ -62,24 +63,31 @@ class BeamFocusRing extends StatefulWidget { /// subtree through an inserted non-focusable [Focus]. final FocusNode? focusNode; - /// Which effect the ring paints. Defaults to [BeamVariant.small], the - /// compact traveling beam. - final BeamVariant variant; + /// Which effect the ring paints. Defaults to [BeamEffect.rotate], which + /// switches to its compact chip look on small controls. + final BeamEffect effect; - /// The ring's palette. Defaults to [BeamColors.ocean]. - final BeamColors colors; + /// The ring's palette; a non-null value wins over `style.colors`. + /// + /// Null inherits `style.colors`, then the enclosing [BorderBeamTheme]'s + /// colours, and only when neither sets one falls back to the ring's own + /// default, [BeamColors.ocean]. + final BeamColors? colors; /// Shorthand for a uniform corner radius in logical px. Match the focused /// widget's own radius. final double? borderRadius; - /// Colors, theme adaptation, and filter hooks, passed straight through. + /// Colours, surface brightness, strength, glow, and hue drift, passed + /// straight through to the `BorderBeam`. final BeamStyle? style; - /// Corner radii, ring width, and corner family, passed straight through. + /// Corner radii, corner family, stroke width, segment, and dashes, passed + /// straight through to the `BorderBeam`. final BeamShape? shape; - /// Cycle length, rest, rate, and hue periods, passed straight through. + /// Cycle length, rest between sweeps, playback rate, direction, and the + /// hue drift period, passed straight through to the `BorderBeam`. final BeamTiming? timing; /// Whether to light the ring even under [FocusHighlightMode.touch]. @@ -92,8 +100,10 @@ class BeamFocusRing extends StatefulWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties - ..add(EnumProperty('variant', variant)) - ..add(DiagnosticsProperty('colors', colors)) + ..add(DiagnosticsProperty('effect', effect)) + ..add( + DiagnosticsProperty('colors', colors, defaultValue: null), + ) ..add(DoubleProperty('borderRadius', borderRadius, defaultValue: null)) ..add( DiagnosticsProperty( @@ -169,11 +179,20 @@ class _BeamFocusRingState extends State { bool get _showHighlight => widget.alwaysShow || _highlightMode == FocusHighlightMode.traditional; + // BorderBeam's colors shorthand wins over style.colors and the theme, so + // the ring passes its ocean default only when nothing else names colours. + BeamColors? _colors(BuildContext context) { + if (widget.colors != null) return widget.colors; + if (widget.style?.colors != null) return null; + if (BorderBeamTheme.of(context).style?.colors != null) return null; + return BeamColors.ocean; + } + @override Widget build(BuildContext context) { final beam = BorderBeam( - variant: widget.variant, - colors: widget.colors, + effect: widget.effect, + colors: _colors(context), active: _focused && _showHighlight, borderRadius: widget.borderRadius, style: widget.style, diff --git a/lib/src/widgets/beam_hover.dart b/lib/src/widgets/beam_hover.dart index c78cce2..c1e2403 100644 --- a/lib/src/widgets/beam_hover.dart +++ b/lib/src/widgets/beam_hover.dart @@ -5,11 +5,11 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import '../border_beam.dart'; +import '../effects/beam_effect.dart'; import '../models/beam_colors.dart'; import '../models/beam_shape.dart'; import '../models/beam_style.dart'; import '../models/beam_timing.dart'; -import '../models/beam_variant.dart'; /// Lights a beam around [child] while the cursor is over it, and pulls the /// sweep toward the cursor — the "spotlight border" effect. @@ -37,7 +37,7 @@ class BeamHover extends StatefulWidget { const BeamHover({ super.key, required this.child, - this.variant = BeamVariant.rotate, + this.effect = const BeamEffect.rotate(), this.colors, this.borderRadius, this.style, @@ -50,9 +50,9 @@ class BeamHover extends StatefulWidget { /// The hovered content. Laid out and hit-tested normally. final Widget child; - /// Which effect the hover paints. Defaults to [BeamVariant.rotate]; only - /// the traveling variants can follow a pointer. - final BeamVariant variant; + /// Which effect the hover paints. Defaults to [BeamEffect.rotate]; only + /// the travelling effects can follow a pointer. + final BeamEffect effect; /// Shorthand for `style.colors`; a non-null value here wins over it. final BeamColors? colors; @@ -61,13 +61,16 @@ class BeamHover extends StatefulWidget { /// radius. final double? borderRadius; - /// Colors, theme adaptation, and filter hooks, passed straight through. + /// Colours, surface brightness, strength, glow, and hue drift, passed + /// straight through to the `BorderBeam`. final BeamStyle? style; - /// Corner radii, ring width, and corner family, passed straight through. + /// Corner radii, corner family, stroke width, ring offset, segment, and + /// dashes, passed straight through to the `BorderBeam`. final BeamShape? shape; - /// Cycle length, rest, rate, and hue periods, passed straight through. + /// Cycle length, rest between sweeps, playback rate, direction, and the + /// hue drift period, passed straight through to the `BorderBeam`. final BeamTiming? timing; /// Whether the sweep gravitates to the cursor. False lights the beam on @@ -84,7 +87,7 @@ class BeamHover extends StatefulWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties - ..add(EnumProperty('variant', variant)) + ..add(DiagnosticsProperty('effect', effect)) ..add( DiagnosticsProperty('colors', colors, defaultValue: null), ) @@ -180,7 +183,7 @@ class _BeamHoverState extends State { onHover: _handleHover, onExit: _handleExit, child: BorderBeam( - variant: widget.variant, + effect: widget.effect, colors: widget.colors, active: _active, follow: _follow, diff --git a/lib/src/widgets/beam_press.dart b/lib/src/widgets/beam_press.dart index 9ac8348..176c73e 100644 --- a/lib/src/widgets/beam_press.dart +++ b/lib/src/widgets/beam_press.dart @@ -4,11 +4,11 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import '../border_beam.dart'; +import '../effects/beam_effect.dart'; import '../models/beam_colors.dart'; import '../models/beam_shape.dart'; import '../models/beam_style.dart'; import '../models/beam_timing.dart'; -import '../models/beam_variant.dart'; /// Lights a beam around [child] while a finger is down on it. /// @@ -43,7 +43,7 @@ class BeamPress extends StatefulWidget { const BeamPress({ super.key, required this.child, - this.variant = BeamVariant.pulseInside, + this.effect = const BeamEffect.pulse(), this.colors, this.borderRadius, this.style, @@ -56,9 +56,8 @@ class BeamPress extends StatefulWidget { /// The pressed content. Laid out and hit-tested normally. final Widget child; - /// Which effect the press paints. Defaults to [BeamVariant.pulseInside], - /// whose breathing glow reads as "held". - final BeamVariant variant; + /// Which effect the press paints. Defaults to [BeamEffect.pulse]. + final BeamEffect effect; /// Shorthand for `style.colors`; a non-null value here wins over it. final BeamColors? colors; @@ -67,13 +66,16 @@ class BeamPress extends StatefulWidget { /// radius. final double? borderRadius; - /// Colors, theme adaptation, and filter hooks, passed straight through. + /// Colours, surface brightness, strength, glow, and hue drift, passed + /// straight through to the `BorderBeam`. final BeamStyle? style; - /// Corner radii, ring width, and corner family, passed straight through. + /// Corner radii, corner family, stroke width, segment, and dashes, passed + /// straight through to the `BorderBeam`. final BeamShape? shape; - /// Cycle length, rest, rate, and hue periods, passed straight through. + /// Cycle length, rest between sweeps, playback rate, direction, and the + /// hue drift period, passed straight through to the `BorderBeam`. final BeamTiming? timing; /// How long the beam stays lit from pointer-down, however early the pointer @@ -91,7 +93,7 @@ class BeamPress extends StatefulWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties - ..add(EnumProperty('variant', variant)) + ..add(DiagnosticsProperty('effect', effect)) ..add( DiagnosticsProperty('colors', colors, defaultValue: null), ) @@ -180,7 +182,7 @@ class _BeamPressState extends State { onPointerUp: _handleUp, onPointerCancel: _handleCancel, child: BorderBeam( - variant: widget.variant, + effect: widget.effect, colors: widget.colors, active: _active, borderRadius: widget.borderRadius, diff --git a/pubspec.yaml b/pubspec.yaml index e6f394e..70c9e2c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,9 +1,9 @@ name: flutter_border_beam description: >- - A traveling or breathing glow around any widget: five beam variants, eleven - palettes, squircle and custom contours, theming, playback control, and - hover/press/focus wrappers. -version: 0.1.0 + Animated light around any widget's border: three effects drawn by a + single-pass fragment shader at the display rate, 19 palettes, squircle + corners, and theming. +version: 0.2.0 repository: https://github.com/SimplifyJobs/flutter_border_beam issue_tracker: https://github.com/SimplifyJobs/flutter_border_beam/issues homepage: https://github.com/SimplifyJobs/flutter_border_beam @@ -16,23 +16,28 @@ topics: - ui screenshots: - path: screenshots/rotate.png - description: Rotate variant — a beam travels around the full border of a card. - - path: screenshots/pulse_outside.png - description: Pulse-outside variant — a breathing halo blooms behind the child. + description: Rotate effect — a beam travels around the full border of a card. - path: screenshots/line.png - description: Line variant — the beam rides the bottom edge of an input. + description: Line effect — a streak rides the bottom edge of an input. + - path: screenshots/pulse.png + description: Pulse effect — colour breathes in from the border of a card. - path: screenshots/squircle.png - description: Superellipse borders in the ocean palette — Apple-style squircle contour. + description: Superellipse corners in the ocean palette — an Apple-style squircle outline. environment: - sdk: ^3.9.0 - flutter: ">=3.35.0" + sdk: ^3.13.0 + flutter: ">=3.47.0" dependencies: flutter: sdk: flutter + material_ui: ^1.11.1 dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^6.0.0 + +flutter: + shaders: + - shaders/beam.frag diff --git a/screenshots/line.png b/screenshots/line.png index 6c6514d..a2f073a 100644 Binary files a/screenshots/line.png and b/screenshots/line.png differ diff --git a/screenshots/pulse.png b/screenshots/pulse.png new file mode 100644 index 0000000..49cce8b Binary files /dev/null and b/screenshots/pulse.png differ diff --git a/screenshots/pulse_outside.png b/screenshots/pulse_outside.png deleted file mode 100644 index 517df9c..0000000 Binary files a/screenshots/pulse_outside.png and /dev/null differ diff --git a/screenshots/rotate.png b/screenshots/rotate.png index 583837f..2a328b1 100644 Binary files a/screenshots/rotate.png and b/screenshots/rotate.png differ diff --git a/screenshots/squircle.png b/screenshots/squircle.png index 5077051..15c8b91 100644 Binary files a/screenshots/squircle.png and b/screenshots/squircle.png differ diff --git a/shaders/beam.frag b/shaders/beam.frag new file mode 100644 index 0000000..a27fb22 --- /dev/null +++ b/shaders/beam.frag @@ -0,0 +1,521 @@ +// flutter_border_beam — the whole effect in one fragment shader. +// +// A beam is up to three layers composited bottom to top, each evaluated per +// pixel in this one pass: +// +// layer 0 — the inner glow, +// layer 1 — the hairline stroke, +// layer 2 — the bloom. +// +// A layer is an optional conic overlay (the white or black highlight at the +// head of a beam, or the bloom band) with a stack of soft radial colour blobs +// painted over it (premultiplied source-over, each over the ones before), an +// optional inset shadow, then masks — a geometry mask (the 1px ring, the filled shape, a +// blurred ring, or a glow outside the shape), a window (a rotating conic +// or a radial ellipse), and an edge fade — and finally a 3×3 +// colour matrix (hue rotation, brightness, saturation) and the layer opacity. +// +// Every blur of the reference design is replaced by its analytic equivalent: +// a blurred 1px ring is a gaussian across the distance to the ring, and a +// blurred blob — cut where its layer's shape ends — is an energy-preserving +// gaussian. One draw, no offscreen passes, no filters. +// +// Uniforms are vec4s and vec4 arrays only, so the float layout is identical on +// every backend (Impeller Metal / Vulkan / GLES, and Skia's SkSL). The Dart +// packer (lib/src/render/beam_frame.dart) mirrors this order exactly; +// test/render/ parses this file to keep the two in step. + +#version 460 core + +#include + +precision highp float; + +uniform vec4 uRect; // outline box: left, top, width, height +uniform vec4 uRadii; // corner radii: top-left, top-right, bottom-right, bottom-left +uniform vec4 uShape; // x corners (0 circular, 1 rounded superellipse), y unused, z stroke width, w px per device px +uniform vec4 uPerim; // x perimeter length, y unused, z dither on/off, w unused +uniform vec4 uQuads; // arc length where each quadrant starts: TR, BR, BL, TL +uniform vec4 uMask; // x segment start u, y segment span (0 or 1 = all), z feather (u), w dashes +uniform vec4 uConic; // xy conic centre, z conic start (turns), w repeats around the turn +// Per layer, 9 vec4s: +// 0: x geometry kind, y blur sigma, z reach (glow), w opacity +// 1: x edge fade px, y window kind, z overlay table (0 none, 1 A, 2 B), w overlay ink (0 black, 1 white) +// 2: window parameters (radial: centre, radii) +// 3: x radial mid stop, y radial mid alpha, z blob mode (0 planar, 1 path, +// 2 blurred planar, 3 blurred path), w blob count +// 4: inset shadow colour (straight rgba) +// 5: x shadow solid depth, y shadow sigma, z dashes apply, w unused +// 6-8: colour matrix rows (xyz) +uniform vec4 uLayer[27]; +uniform vec4 uWinA[8]; // conic window tables: (position, alpha) pairs, two per vec4 +uniform vec4 uWinB[8]; +uniform vec4 uOverA[8]; // conic overlay tables +uniform vec4 uOverB[8]; +// Blobs, three vec4s each, in painting order (each over the ones before): +// 0: centre xy, radii xy (profile mode) or sigmas xy (gaussian mode) +// 1: straight rgb, a0 (alpha at the centre; peak in gaussian mode) +// 2: p1, a1, p2, a2 — the alpha profile 0:a0 → p1:a1 → p2:a2 → 1:0 +uniform vec4 uBlobA[42]; // layer 0, 14 blobs +uniform vec4 uBlobB[30]; // layer 1, 10 blobs +uniform vec4 uBlobC[30]; // layer 2, 10 blobs + +out vec4 fragColor; + +const float TAU = 6.283185307; +const float HALF_PI = 1.570796327; +const float INV_SQRT_TAU = 0.3989422804; + +// Flutter's rounded superellipse (RSuperellipse, as RoundedSuperellipseBorder +// draws it; impeller/geometry/round_superellipse_param.cc). Each corner is two +// halves, each running from the middle of one edge to the corner's diagonal: +// a superellipse |x/a|^n + |y/a|^n = 1 that hands over at a joint J to a +// circular arc ending on the diagonal. A half is evaluated in a frame where +// its edge runs along y = a, x is measured from the middle of that edge, and +// the diagonal is x = y. lib/src/render/beam_outline.dart mirrors all of it. + +const float SQUIRCLE_REACH = 2.5; // past this many radii the edge is straight +const float GAP_FACTOR = 0.29289321881; + +// Flutter's ComputeNAndXj: the exponent n and xJ / a for an edge [ratio] +// radii long (2a / r), piecewise linear through Flutter's table. +vec2 rseExponentAndJoint(float ratio) { + vec2 nk; + if (ratio > 5.0) { + nk = vec2(6.43023796, 2.98020421) + (ratio - 5.0) * vec2(1.559599389, 0.522807185); + } else { + float c = clamp(ratio, 2.0, 5.0); + float st = c < 2.5 ? (c - 2.0) * 10.0 : (c - 2.5) * 2.0 + 5.0; + nk = vec2(2.00000000, 1.13276676) * max(1.0 - abs(st), 0.0) + + vec2(2.18349805, 1.20311921) * max(1.0 - abs(st - 1.0), 0.0) + + vec2(2.33888662, 1.28698796) * max(1.0 - abs(st - 2.0), 0.0) + + vec2(2.48660575, 1.36351941) * max(1.0 - abs(st - 3.0), 0.0) + + vec2(2.62226596, 1.44717976) * max(1.0 - abs(st - 4.0), 0.0) + + vec2(2.75148990, 1.53385819) * max(1.0 - abs(st - 5.0), 0.0) + + vec2(3.36298265, 1.98288283) * max(1.0 - abs(st - 6.0), 0.0) + + vec2(4.08649929, 2.23811846) * max(1.0 - abs(st - 7.0), 0.0) + + vec2(4.85481134, 2.47563463) * max(1.0 - abs(st - 8.0), 0.0) + + vec2(5.62945551, 2.72948597) * max(1.0 - abs(st - 9.0), 0.0) + + vec2(6.43023796, 2.98020421) * max(1.0 - abs(st - 10.0), 0.0); + } + return vec2(nk.x, 1.0 - 1.0 / nk.y); +} + +// The unit superellipse of exponent n above x = t (0 < t < 1): its height, +// then its outward normal. +vec3 rseOnCurve(float t, float n) { + float tn = pow(t, n); + float y = pow(1.0 - tn, 1.0 / n); + return vec3(y, normalize(vec2(tn / t, (1.0 - tn) / y))); +} + +// One half of a superellipse corner of radius r, for a point P on its side +// of the diagonal: signed distance, arc length from the middle of the edge, +// and outward normal. The run up to the joint is measured along x. +// +// The shape is convex, so the signed distance to any line it rests against +// never exceeds the signed distance to the shape. Off the arc the distance is +// the largest of a few such lines — the tangent above or below the point, +// the tangent at the joint, and the box's sides — exact on the curve and +// continuous across the joint, inside and out. +vec4 rseHalf(vec2 P, float a, float r) { + if (P.x <= a - min(SQUIRCLE_REACH * r, a)) return vec4(P.y - a, P.x, 0.0, 1.0); + vec2 nj = rseExponentAndJoint(2.0 * a / r); + float n = nj.x; + vec3 joint = rseOnCurve(nj.y, n); + vec2 J = a * vec2(nj.y, joint.x); + // Flutter sizes the arc by where the superellipse's normal at the joint + // crosses the diagonal, then centres it on J and the diagonal point g in + // from both sides. + float tanPhi = joint.y / joint.z; + float onDiagonal = (J.x - tanPhi * J.y) / (1.0 - tanPhi); + float g = GAP_FACTOR * r; + float R = (a - onDiagonal - g) * 1.41421356; + vec2 chord = vec2(a - g) - J; + float cl = length(chord); + float rise = sqrt(max(R * R - 0.25 * cl * cl, 0.0)); + vec2 C = J + 0.5 * chord + rise * vec2(chord.y, -chord.x) / cl; + + float box = max(P.x - a, P.y - a); + vec2 jc = J - C; + vec2 pc = P - C; + if (jc.x * pc.y - jc.y * pc.x <= 0.0) { + // Past the joint, clockwise: the arc. + float l = max(length(pc), 1e-4); + float theta = atan(jc.y * pc.x - jc.x * pc.y, dot(jc, pc)); + return vec4(max(l - R, box), J.x + R * theta, pc / l); + } + // The superellipse: the tangent at the curve point straight above or + // below, up to the joint. + float xb = min(P.x, J.x); + vec3 foot = rseOnCurve(max(xb / a, 1e-4), n); + float along = dot(P - vec2(xb, foot.x * a), foot.yz); + float atJoint = dot(P - J, joint.yz); + return vec4(max(max(along, atJoint), box), P.x - along * foot.y, foot.yz); +} + +// Signed distance to the outline (negative inside), arc length from top-centre +// clockwise, and the outward normal of the nearest piece of the outline. +vec4 outline(vec2 p, vec2 b) { + bool right = p.x > 0.0; + bool bottom = p.y > 0.0; + float r = right ? (bottom ? uRadii.z : uRadii.y) : (bottom ? uRadii.w : uRadii.x); + float R = min(r, min(b.x, b.y)); + vec2 a = abs(p); + float d; + float s; // arc length within the quadrant, starting on the vertical axis + vec2 nrm; + float quadLen; + if (uShape.x > 0.5 && R >= 0.5) { + // A superellipse corner. Its halves meet on the 45° line through the + // corner's diagonal. + quadLen = right ? (bottom ? uQuads.z - uQuads.y : uQuads.y - uQuads.x) + : (bottom ? uQuads.w - uQuads.z : uPerim.x - uQuads.w); + float c = b.x - b.y; + vec4 h; + if (a.x - a.y <= c) { + h = rseHalf(vec2(a.x, a.y + c), b.x, R); + } else { + h = rseHalf(vec2(a.y, a.x - c), b.y, R); + h = vec4(h.x, quadLen - h.y, h.w, h.z); + } + d = h.x; + s = h.y; + nrm = h.zw; + } else { + // A circular corner. + R = max(R, 1e-3); + vec2 q = a - (b - R); + float legX = b.x - R; + float arc = R * HALF_PI; + quadLen = legX + arc + (b.y - R); + if (q.x > 0.0 && q.y > 0.0) { + d = length(q) - R; + s = legX + arc * (atan(q.x, q.y) / HALF_PI); + nrm = q / max(length(q), 1e-4); + } else { + d = max(q.x, q.y) - R; + bool side = q.x > q.y; + s = side ? legX + arc + (b.y - R - a.y) : a.x; + nrm = side ? vec2(1.0, 0.0) : vec2(0.0, 1.0); + } + } + nrm *= vec2(right ? 1.0 : -1.0, bottom ? 1.0 : -1.0); + // TR and BL run vertical axis → horizontal axis clockwise; BR and TL run the + // other way, so their local arc length is mirrored. + float start; + if (right) { + start = bottom ? uQuads.y : uQuads.x; + if (bottom) s = quadLen - s; + } else { + start = bottom ? uQuads.z : uQuads.w; + if (!bottom) s = quadLen - s; + } + return vec4(d, start + s, nrm); +} + +// Standard normal CDF, logistic approximation (max error ~0.01). +float phi(float z) { + return 1.0 / (1.0 + exp(-1.702 * z)); +} + +vec4 srcOver(vec4 src, vec4 dst) { + return src + dst * (1.0 - src.a); +} + +// Piecewise-linear table lookup over (position, alpha) pairs, two per vec4, +// ascending and padded with copies of the last stop. A table whose first +// position is past 1 is unused and costs one comparison. +#define TABLE_STEP(ST, T, PP, PA, OUT, DONE) \ + if (!DONE) { \ + if (T <= ST.x) { \ + OUT = mix(PA, ST.y, clamp((T - PP) / max(ST.x - PP, 1e-5), 0.0, 1.0)); \ + DONE = true; \ + } else { \ + PP = ST.x; \ + PA = ST.y; \ + } \ + } + +#define TABLE_LOOKUP(TABLE, T, OUT) \ + { \ + float pp = TABLE[0].x; \ + float pa = TABLE[0].y; \ + OUT = pa; \ + if (T > pp && pp <= 1.0) { \ + OUT = TABLE[7].w; \ + bool done = false; \ + for (int i = 0; i < 8; i++) { \ + vec4 e = TABLE[i]; \ + TABLE_STEP(e.xy, T, pp, pa, OUT, done) \ + TABLE_STEP(e.zw, T, pp, pa, OUT, done) \ + if (done) break; \ + } \ + } \ + } + +// One blob's premultiplied colour at offset [o] from its centre. +vec4 blob(vec4 b0, vec4 b1, vec4 b2, vec2 o, bool gaussian) { + vec2 q = o / max(b0.zw, vec2(1e-3)); + float t2 = dot(q, q); + float alpha; + if (gaussian) { + if (t2 > 25.0) return vec4(0.0); + alpha = b1.a * exp(-0.5 * t2); + } else { + if (t2 >= 1.0) return vec4(0.0); + float t = sqrt(t2); + if (t < b2.x) { + alpha = mix(b1.a, b2.y, t / max(b2.x, 1e-5)); + } else if (t < b2.z) { + alpha = mix(b2.y, b2.w, (t - b2.x) / max(b2.z - b2.x, 1e-5)); + } else { + alpha = mix(b2.w, 0.0, (t - b2.z) / max(1.0 - b2.z, 1e-5)); + } + } + return vec4(b1.rgb * alpha, alpha); +} + +// The offset from a blob centre [c] to the shaded point [p]: planar, or in +// path space (arc length along the outline, depth inward) wrapped around the +// perimeter. +vec2 blobOffset(vec2 p, vec2 c, bool path) { + vec2 o = p - c; + if (path) { + float L = max(uPerim.x, 1e-3); + o.x -= L * floor(o.x / L + 0.5); + } + return o; +} + +#define BLOB_STACK(ARRAY, SLOTS, COUNT, P, MODE, OUT) \ + { \ + bool path = MODE > 0.5 && (MODE < 1.5 || MODE > 2.5); \ + bool gauss = MODE > 1.5; \ + for (int i = 0; i < SLOTS; i++) { \ + if (float(i) >= COUNT) break; \ + vec4 b0 = ARRAY[i * 3]; \ + OUT = srcOver( \ + blob(b0, ARRAY[i * 3 + 1], ARRAY[i * 3 + 2], blobOffset(P, b0.xy, path), gauss), \ + OUT); \ + } \ + } + +// The visible track. Its ends soften with [spread] (px from the stroke), so a +// glow fades out toward the end of the track instead of stopping at a line. +// A track of a whole turn (a segment whose ends meet) has no ends to soften. +float segmentMask(float u, float spread) { + if (uMask.y > 0.0 && uMask.y < 1.0) { + float x = fract(u - uMask.x); + if (x > uMask.y) return 0.0; + float fe = max(uMask.z + spread / uPerim.x, 1e-5); + return smoothstep(0.0, fe, x) * smoothstep(0.0, fe, uMask.y - x); + } + return 1.0; +} + +// Dashes cover 60% of each period, softened the further light is from the +// stroke. +float dashMask(float u, float px, float spread) { + if (uMask.w < 2.0) return 1.0; + float t = abs(fract(u * uMask.w + 0.2) - 0.5); // distance from dash centre + float aa = max((1.5 * px + spread) * uMask.w / uPerim.x, 1e-4); + return 1.0 - smoothstep(0.3 - 0.5 * aa, 0.3 + 0.5 * aa, t); +} + +// Everything about a layer except its colour: geometry, window, edge fade. +float layerMask(vec4 h0, vec4 h1, vec4 h2, vec4 h3, vec2 pos, vec2 pathP, float d, + float tw, float px, vec4 winA, vec4 winB) { + float kind = h0.x; + if (kind < 0.5 || h0.w <= 0.0) return 0.0; + float w = uShape.z; + float inside = clamp(0.5 - d / px, 0.0, 1.0); + float m; + if (kind < 1.5) { + // The hairline ring, just inside the outline. + float c = d + 0.5 * w; + m = clamp((0.5 * w - abs(c)) / px + 0.5, 0.0, 1.0); + } else if (kind < 2.5) { + m = inside; + } else if (kind < 3.5) { + // A blurred ring, clipped to the shape: the 1px band convolved with a + // gaussian is the band's width times the normal density across it. + float sigma = max(h0.y, 1e-3); + float c = (d + 0.5 * w) / sigma; + m = w / sigma * INV_SQRT_TAU * exp(-0.5 * c * c) * inside; + } else { + // A glow outside the outline that fades out: the shape grown by + // [inflate] and blurred by [sigma]. + float sigma = max(h0.y, 1e-3); + m = phi((h0.z - d) / sigma) * (1.0 - inside); + } + if (m <= 0.0) return 0.0; + + bool path = h3.z > 0.5 && (h3.z < 1.5 || h3.z > 2.5); + // Edge fade: opaque at the outline, transparent [h1.x] px in. Planar + // layers fade from each side of the box (the two directions screened); + // path-space layers fade by depth. + if (h1.x > 0.0) { + float e; + if (path) { + e = clamp(1.0 + d / h1.x, 0.0, 1.0); + } else { + vec2 rel = pos - uRect.xy; + vec2 near = min(rel, uRect.zw - rel); + vec2 f = clamp(1.0 - near / h1.x, 0.0, 1.0); + e = f.x + f.y - f.x * f.y; + } + m *= e; + } + + float win = h1.y; + if (win > 0.5) { + if (win < 1.5) { + m *= winA.x; + } else if (win < 2.5) { + m *= winB.x; + } else { + // Radial ellipse window: 1 at the centre, mid alpha at the mid stop, + // 0 at the rim. + vec2 o = blobOffset(path ? pathP : pos, h2.xy, path); + float t = length(o / max(h2.zw, vec2(1e-3))); + float r; + if (t >= 1.0) { + r = 0.0; + } else if (t < h3.x) { + r = mix(1.0, h3.y, t / max(h3.x, 1e-5)); + } else { + r = mix(h3.y, 0.0, (t - h3.x) / max(1.0 - h3.x, 1e-5)); + } + m *= r; + } + } + return m; +} + +// A layer's overlay, at the bottom of its stack. +vec4 overlay(vec4 h1, vec4 overA, vec4 overB) { + if (h1.z > 0.5) { + float a = h1.z < 1.5 ? overA.x : overB.x; + return vec4(vec3(h1.w) * a, a); + } + return vec4(0.0); +} + +// A layer's shadow over its overlay and blobs, then its matrix. +vec4 finishLayer(vec4 acc, vec4 h4, vec4 h5, vec4 h6, vec4 h7, vec4 h8, float d) { + if (h4.a > 0.0) { + // Inset shadow: solid to [h5.x] px in, blurred by [h5.y]. + float a = h4.a * phi((h5.x + d) / max(h5.y, 1e-3)); + acc = srcOver(vec4(h4.rgb * a, a), acc); + } + if (acc.a > 1e-4) { + vec3 rgb = acc.rgb / acc.a; + rgb = clamp(vec3(dot(h6.xyz, rgb), dot(h7.xyz, rgb), dot(h8.xyz, rgb)), 0.0, 1.0); + acc = vec4(rgb * acc.a, acc.a); + } else { + acc = vec4(0.0); + } + return acc; +} + +void main() { + vec2 pos = FlutterFragCoord().xy; + vec2 b = uRect.zw * 0.5; + vec2 centre = uRect.xy + b; + vec2 p = pos - centre; + float px = uShape.w; + + vec4 o = outline(p, b); + float d = o.x; + float L = max(uPerim.x, 1e-3); + float u = fract(o.y / L); + vec2 pathP = vec2(o.y, -d); + + // Conic coordinate around the conic centre: 0 at 12 o'clock, clockwise. + vec2 cd = pos - uConic.xy; + float ct = fract(atan(cd.x, -cd.y) / TAU + 1.0); + float tw = fract(ct - uConic.z); + if (uConic.w > 1.5) tw = fract(tw * uConic.w); + + float spread = abs(d + 0.5 * uShape.z); + float seg = segmentMask(u, spread); + if (seg <= 0.0) { + fragColor = vec4(0.0); + return; + } + float dash = dashMask(u, px, spread); + + float wa; + float wb; + float oa; + float ob; + TABLE_LOOKUP(uWinA, tw, wa) + TABLE_LOOKUP(uWinB, tw, wb) + TABLE_LOOKUP(uOverA, tw, oa) + TABLE_LOOKUP(uOverB, tw, ob) + vec4 winA = vec4(wa); + vec4 winB = vec4(wb); + vec4 overA = vec4(oa); + vec4 overB = vec4(ob); + + vec4 colour = vec4(0.0); + + // ── Layer 0 ── + { + float m = layerMask(uLayer[0], uLayer[1], uLayer[2], uLayer[3], pos, pathP, d, tw, px, winA, winB); + if (m > 0.0) { + vec4 acc = overlay(uLayer[1], overA, overB); + vec2 bp = uLayer[3].z > 0.5 && (uLayer[3].z < 1.5 || uLayer[3].z > 2.5) ? pathP : pos; + BLOB_STACK(uBlobA, 14, uLayer[3].w, bp, uLayer[3].z, acc) + acc = finishLayer(acc, uLayer[4], uLayer[5], uLayer[6], uLayer[7], uLayer[8], d); + if (uLayer[5].z > 0.5) m *= dash; + colour = srcOver(acc * (m * min(uLayer[0].w, 1.0)), colour); + } + } + + // ── Layer 1 ── + { + float m = layerMask(uLayer[9], uLayer[10], uLayer[11], uLayer[12], pos, pathP, d, tw, px, winA, winB); + if (m > 0.0) { + vec4 acc = overlay(uLayer[10], overA, overB); + vec2 bp = uLayer[12].z > 0.5 && (uLayer[12].z < 1.5 || uLayer[12].z > 2.5) ? pathP : pos; + BLOB_STACK(uBlobB, 10, uLayer[12].w, bp, uLayer[12].z, acc) + acc = finishLayer(acc, uLayer[13], uLayer[14], uLayer[15], uLayer[16], uLayer[17], d); + if (uLayer[14].z > 0.5) m *= dash; + colour = srcOver(acc * (m * min(uLayer[9].w, 1.0)), colour); + } + } + + // ── Layer 2 ── + { + float m = layerMask(uLayer[18], uLayer[19], uLayer[20], uLayer[21], pos, pathP, d, tw, px, winA, winB); + if (m > 0.0) { + vec4 acc = overlay(uLayer[19], overA, overB); + // A blurred ring samples its colour where the ring is, not where the + // light spread to. + vec2 ringPoint = pos - o.zw * d; + vec2 bp = uLayer[21].z > 0.5 && (uLayer[21].z < 1.5 || uLayer[21].z > 2.5) + ? pathP + : (uLayer[18].x > 2.5 && uLayer[18].x < 3.5 ? ringPoint : pos); + BLOB_STACK(uBlobC, 10, uLayer[21].w, bp, uLayer[21].z, acc) + acc = finishLayer(acc, uLayer[22], uLayer[23], uLayer[24], uLayer[25], uLayer[26], d); + if (uLayer[23].z > 0.5) m *= dash; + colour = srcOver(acc * (m * min(uLayer[18].w, 1.0)), colour); + } + } + + colour *= seg; + if (colour.a <= 0.0) { + fragColor = vec4(0.0); + return; + } + // Interleaved-gradient dither on the soft tails, so 8-bit targets don't band. + if (uPerim.z > 0.0 && colour.a > 0.004) { + vec2 dev = pos / px; + float ign = fract(52.9829189 * fract(dot(dev, vec2(0.06711056, 0.00583715)))); + float a = clamp(colour.a + (ign - 0.5) / 255.0, 0.0, 1.0); + colour *= a / colour.a; + } + fragColor = colour; +} diff --git a/test/animation/beam_clock_test.dart b/test/animation/beam_clock_test.dart index 5f740be..994dd41 100644 --- a/test/animation/beam_clock_test.dart +++ b/test/animation/beam_clock_test.dart @@ -1,165 +1,576 @@ +import 'package:flutter/animation.dart'; import 'package:flutter/foundation.dart'; -import 'package:flutter/scheduler.dart'; import 'package:flutter_border_beam/src/animation/beam_clock.dart'; import 'package:flutter_test/flutter_test.dart'; +/// A step comfortably below one display frame at 120Hz. +const Duration _frame = Duration(milliseconds: 8); + +/// The clock is the single time source of a beam: one ticker, elapsed time +/// integrated from scaled deltas, and the fade envelopes on top. These tests +/// drive it with the test binding's fake clock — note that the first tick +/// after a ticker starts reports elapsed zero, so each test pumps once +/// before pumping durations. void main() { - late TickerProvider vsync; + // Clocks already disposed, so the tear-down never disposes one twice. + final disposed = Expando('disposed'); - BeamClock makeClock({double? maxFps, ValueChanged? onFadeComplete}) => - BeamClock( - createTicker: vsync.createTicker, - maxFps: maxFps, - onFadeComplete: onFadeComplete, - ); + /// Disposes [clock] unless it already is; safe to call more than once. + void disposeClock(BeamClock clock) { + if (disposed[clock] ?? false) return; + disposed[clock] = true; + clock.dispose(); + } - testWidgets('activate fades in and completes', (tester) async { - vsync = tester; - final events = []; - final clock = makeClock(onFadeComplete: events.add); + /// A clock on the test's ticker provider. Each test still disposes its + /// clock before it returns — flutter_test checks for live tickers before + /// tear-downs run — and the tear-down disposes one a failed expectation + /// left behind. + BeamClock makeClock( + WidgetTester tester, { + ValueChanged? onFadeComplete, + Curve? fadeCurve, + }) { + final clock = BeamClock( + createTicker: tester.createTicker, + onFadeComplete: onFadeComplete, + fadeCurve: fadeCurve, + ); + addTearDown(() => disposeClock(clock)); + return clock; + } - expect(clock.fadeOpacity, 0); + /// Activates [clock] and runs it past the fade-in. + Future runVisible(WidgetTester tester, BeamClock clock) async { clock.activate(); - expect(clock.isRunning, isTrue); - expect(clock.stage, BeamFadeStage.fadingIn); - - // First tick anchors the ticker's start time at elapsed zero. await tester.pump(); - // Sample early: the spring fade converges well before its nominal 0.6s. - await tester.pump(const Duration(milliseconds: 80)); - expect(clock.fadeOpacity, greaterThan(0)); - expect(clock.fadeOpacity, lessThan(1)); - - await tester.pump(const Duration(milliseconds: 620)); + await tester.pump(const Duration(seconds: 1)); expect(clock.stage, BeamFadeStage.none); - expect(clock.fadeOpacity, 1); - expect(events, [true]); - clock.dispose(); - }); + } - testWidgets('deactivate fades out, stops, and resets the timeline', ( - tester, - ) async { - vsync = tester; - final events = []; - final clock = makeClock(onFadeComplete: events.add); + group('fade envelopes', () { + testWidgets('activate fades in from 0 and reports completion', ( + tester, + ) async { + final events = []; + final clock = makeClock(tester, onFadeComplete: events.add); + expect(clock.fadeOpacity, 0); + expect(clock.isVisible, isFalse); - clock.activate(); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - expect(clock.elapsedSeconds, greaterThan(0.9)); + clock.activate(); + expect(clock.isRunning, isTrue); + expect(clock.isVisible, isTrue); + expect(clock.stage, BeamFadeStage.fadingIn); + expect(clock.fadeOpacity, 0); - clock.deactivate(); - expect(clock.stage, BeamFadeStage.fadingOut); - await tester.pump(const Duration(milliseconds: 600)); - expect(clock.isRunning, isFalse); - expect(clock.isVisible, isFalse); - expect(clock.fadeOpacity, 0); - expect(clock.elapsedSeconds, 0, reason: 'timeline resets after fade-out'); - expect(events, [true, false]); - clock.dispose(); - }); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 80)); + expect(clock.fadeOpacity, greaterThan(0)); + expect(clock.fadeOpacity, lessThan(1)); + expect(events, isEmpty); - testWidgets('re-activation restarts the timeline from zero', (tester) async { - vsync = tester; - final clock = makeClock(); + await tester.pump(const Duration(milliseconds: 700)); + expect(clock.stage, BeamFadeStage.none); + expect(clock.fadeOpacity, 1); + expect(clock.isRunning, isTrue, reason: 'keeps animating once lit'); + expect(events, [true]); + disposeClock(clock); + }); - clock.activate(); - await tester.pump(); - await tester.pump(const Duration(seconds: 2)); - clock.deactivate(); - await tester.pump(const Duration(seconds: 1)); - clock.activate(); - expect(clock.elapsedSeconds, 0); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - expect(clock.elapsedSeconds, lessThan(0.2)); - clock.dispose(); - }); + testWidgets('deactivate fades out, stops, and resets the timeline', ( + tester, + ) async { + final events = []; + final clock = makeClock(tester, onFadeComplete: events.add); + await runVisible(tester, clock); + expect(clock.elapsedSeconds, greaterThan(0.9)); - testWidgets('pause freezes and resume continues', (tester) async { - vsync = tester; - final clock = makeClock(); + clock.deactivate(); + expect(clock.stage, BeamFadeStage.fadingOut); + await tester.pump(const Duration(milliseconds: 100)); + expect(clock.fadeOpacity, greaterThan(0)); + expect(clock.fadeOpacity, lessThan(1)); - clock.activate(); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - final at = clock.elapsedSeconds; - expect(at, greaterThan(0.9)); - clock.pause(); - await tester.pump(const Duration(seconds: 1)); - expect(clock.elapsedSeconds, at); - clock.resume(); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - expect(clock.elapsedSeconds, greaterThan(at + 0.9)); - clock.dispose(); + await tester.pump(const Duration(milliseconds: 600)); + expect(clock.isRunning, isFalse); + expect(clock.isVisible, isFalse); + expect(clock.stage, BeamFadeStage.none); + expect(clock.fadeOpacity, 0); + expect(clock.elapsedSeconds, 0, reason: 'the timeline resets'); + expect(events, [true, false]); + expect(tester.binding.transientCallbackCount, 0); + disposeClock(clock); + }); + + testWidgets('fadeOpacity stays inside [0, 1] on every frame', ( + tester, + ) async { + // The default spring overshoots its target; a back-eased curve + // overshoots far more. Both must still read as a valid opacity. + for (final curve in [ + null, + Curves.easeOutBack, + Curves.easeInBack, + ]) { + final clock = makeClock(tester, fadeCurve: curve); + final seen = []; + clock.addListener(() => seen.add(clock.fadeOpacity)); + + clock.activate(); + await tester.pump(); + for (var i = 0; i < 100; i++) { + await tester.pump(_frame); + } + clock.deactivate(); + for (var i = 0; i < 100; i++) { + await tester.pump(_frame); + } + expect(seen, isNotEmpty); + for (final v in seen) { + expect(v, inInclusiveRange(0, 1), reason: 'curve $curve'); + } + disposeClock(clock); + } + }); + + testWidgets('fadeCurve replaces the spring easing', (tester) async { + final clock = makeClock(tester, fadeCurve: Curves.linear); + clock.activate(); + await tester.pump(); + await tester.pump( + Duration(microseconds: (BeamClock.fadeInSeconds / 2 * 1e6).round()), + ); + expect(clock.fadeOpacity, closeTo(0.5, 1e-6)); + + // Settable mid-run: the envelope reads it on every evaluation. + clock.fadeCurve = Curves.easeIn; + expect(clock.fadeOpacity, closeTo(Curves.easeIn.transform(0.5), 1e-6)); + disposeClock(clock); + }); + + testWidgets('activating a visible beam is a no-op', (tester) async { + final clock = makeClock(tester); + await runVisible(tester, clock); + final at = clock.elapsedSeconds; + clock.activate(); + expect(clock.elapsedSeconds, at); + expect(clock.stage, BeamFadeStage.none); + expect(clock.fadeOpacity, 1); + disposeClock(clock); + }); + + testWidgets('deactivating a hidden beam is a no-op', (tester) async { + final events = []; + final clock = makeClock(tester, onFadeComplete: events.add); + clock.deactivate(); + expect(clock.isRunning, isFalse); + expect(clock.stage, BeamFadeStage.none); + await tester.pump(const Duration(seconds: 1)); + expect(events, isEmpty); + disposeClock(clock); + }); + + testWidgets('re-activation after a fade-out restarts from zero', ( + tester, + ) async { + final clock = makeClock(tester); + await runVisible(tester, clock); + clock.deactivate(); + await tester.pump(const Duration(seconds: 1)); + expect(clock.isVisible, isFalse); + + clock.activate(); + expect(clock.elapsedSeconds, 0); + expect(clock.fadeOpacity, 0); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(clock.elapsedSeconds, closeTo(0.1, 1e-6)); + disposeClock(clock); + }); + + testWidgets('re-activation mid-fade-out resumes without a jump', ( + tester, + ) async { + final events = []; + final clock = makeClock(tester, onFadeComplete: events.add); + await runVisible(tester, clock); + clock.deactivate(); + await tester.pump(const Duration(milliseconds: 60)); + final opacity = clock.fadeOpacity; + final elapsed = clock.elapsedSeconds; + expect(opacity, inExclusiveRange(0, 1)); + + clock.activate(); + expect(clock.stage, BeamFadeStage.fadingIn); + expect(clock.fadeOpacity, closeTo(opacity, 1e-9)); + expect( + clock.elapsedSeconds, + elapsed, + reason: 'the timeline continues rather than restarting', + ); + + await tester.pump(const Duration(milliseconds: 700)); + expect(clock.fadeOpacity, 1); + expect(events, [true, true], reason: 'the fade-out never completed'); + disposeClock(clock); + }); + + testWidgets('showStatic is fully visible without a ticker', (tester) async { + final clock = makeClock(tester); + clock.showStatic(); + expect(clock.isVisible, isTrue); + expect(clock.stage, BeamFadeStage.none); + expect(clock.fadeOpacity, 1); + expect(clock.isRunning, isFalse); + expect(tester.binding.transientCallbackCount, 0); + disposeClock(clock); + }); }); - testWidgets('speed scales elapsed time', (tester) async { - vsync = tester; - final clock = makeClock(); + group('timeline', () { + testWidgets('elapsed time follows the frame clock', (tester) async { + final clock = makeClock(tester); + clock.activate(); + await tester.pump(); + for (var i = 0; i < 25; i++) { + await tester.pump(const Duration(milliseconds: 40)); + } + expect(clock.elapsedSeconds, closeTo(1, 1e-6)); + expect(clock.activeSeconds, closeTo(1, 1e-6)); + disposeClock(clock); + }); - clock.activate(); - clock.speed = 2; - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - expect(clock.elapsedSeconds, closeTo(2, 0.1)); - clock.dispose(); + testWidgets('pause freezes and resume continues', (tester) async { + final clock = makeClock(tester); + await runVisible(tester, clock); + final at = clock.elapsedSeconds; + final active = clock.activeSeconds; + + clock.pause(); + expect(clock.isRunning, isFalse); + await tester.pump(const Duration(seconds: 1)); + expect(clock.elapsedSeconds, at); + expect(clock.activeSeconds, active); + + clock.resume(); + expect(clock.isRunning, isTrue); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + expect(clock.elapsedSeconds, closeTo(at + 0.5, 1e-6)); + disposeClock(clock); + }); + + testWidgets('resume does nothing for a hidden beam', (tester) async { + final clock = makeClock(tester); + clock.resume(); + expect(clock.isRunning, isFalse); + expect(tester.binding.transientCallbackCount, 0); + disposeClock(clock); + }); + + testWidgets('seek jumps the timeline and notifies', (tester) async { + final clock = makeClock(tester); + var notified = 0; + clock.addListener(() => notified++); + await runVisible(tester, clock); + notified = 0; + + clock.seek(42); + expect(clock.elapsedSeconds, 42); + expect(notified, 1); + await tester.pump(const Duration(milliseconds: 100)); + expect(clock.elapsedSeconds, closeTo(42.1, 1e-6)); + disposeClock(clock); + }); + + testWidgets('speed scales elapsed time but not active time', ( + tester, + ) async { + final clock = makeClock(tester); + clock.speed = 2; + expect(clock.speed, 2); + clock.activate(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(clock.elapsedSeconds, closeTo(2, 1e-6)); + expect(clock.activeSeconds, closeTo(1, 1e-6)); + + clock.speed = 0.5; + await tester.pump(const Duration(seconds: 1)); + expect(clock.elapsedSeconds, closeTo(2.5, 1e-6)); + expect(clock.activeSeconds, closeTo(2, 1e-6)); + disposeClock(clock); + }); + + for (final speed in [0.25, 4.0]) { + testWidgets('fades take the same real time at speed $speed', ( + tester, + ) async { + final clock = makeClock(tester)..speed = speed; + clock.activate(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(clock.stage, BeamFadeStage.fadingIn); + await tester.pump(const Duration(milliseconds: 400)); + expect(clock.stage, BeamFadeStage.none); + expect(clock.fadeOpacity, 1); + + clock.deactivate(); + await tester.pump(const Duration(milliseconds: 100)); + expect(clock.stage, BeamFadeStage.fadingOut); + await tester.pump(const Duration(milliseconds: 500)); + expect(clock.isVisible, isFalse); + disposeClock(clock); + }); + } + + testWidgets('speed must be positive', (tester) async { + final clock = makeClock(tester); + expect(() => clock.speed = 0, throwsAssertionError); + expect(() => clock.speed = -1, throwsAssertionError); + disposeClock(clock); + }); + + testWidgets('notifies on every frame — no frame-rate cap', (tester) async { + final clock = makeClock(tester); + var notified = 0; + clock.addListener(() => notified++); + await runVisible(tester, clock); + + notified = 0; + const frames = 120; + for (var i = 0; i < frames; i++) { + await tester.pump(_frame); + } + expect(notified, frames); + disposeClock(clock); + }); }); - testWidgets('seek jumps the timeline', (tester) async { - vsync = tester; - final clock = makeClock(); + group('retime', () { + testWidgets('scales elapsed time by the factor', (tester) async { + final clock = makeClock(tester); + await runVisible(tester, clock); + final at = clock.elapsedSeconds; + clock.retime(2.5); + expect(clock.elapsedSeconds, closeTo(at * 2.5, 1e-9)); + clock.retime(0.4); + expect(clock.elapsedSeconds, closeTo(at, 1e-9)); + disposeClock(clock); + }); - clock.activate(); - clock.seek(42); - expect(clock.elapsedSeconds, 42); - clock.dispose(); + testWidgets('keeps the fade opacity and its remaining duration', ( + tester, + ) async { + final events = []; + final clock = makeClock(tester, onFadeComplete: events.add); + clock.activate(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); + final opacity = clock.fadeOpacity; + expect(clock.stage, BeamFadeStage.fadingIn); + + clock.retime(3); + expect(clock.fadeOpacity, closeTo(opacity, 1e-9)); + expect(clock.stage, BeamFadeStage.fadingIn); + + // The rest of the fade remains, exactly as before the retime. + final left = Duration( + microseconds: ((BeamClock.fadeInSeconds - 0.2) * 1e6).round(), + ); + await tester.pump(left - const Duration(milliseconds: 50)); + expect(clock.stage, BeamFadeStage.fadingIn); + await tester.pump(const Duration(milliseconds: 100)); + expect(clock.stage, BeamFadeStage.none); + expect(events, [true]); + disposeClock(clock); + }); + + testWidgets('keeps a playing boost where it was', (tester) async { + final clock = makeClock(tester); + await runVisible(tester, clock); + clock.pulse(); + await tester.pump(const Duration(milliseconds: 100)); + final boost = clock.boost; + expect(boost, greaterThan(1)); + clock.retime(4); + expect(clock.boost, closeTo(boost, 1e-9)); + disposeClock(clock); + }); + + testWidgets('the factor must be positive', (tester) async { + final clock = makeClock(tester); + expect(() => clock.retime(0), throwsAssertionError); + disposeClock(clock); + }); }); - testWidgets('maxFps caps steady-state notifications', (tester) async { - vsync = tester; - final clock = makeClock(maxFps: 30); - var notifications = 0; - clock.addListener(() => notifications++); + group('pulse and flash', () { + Future> playBoost( + WidgetTester tester, + BeamClock clock, + void Function() trigger, + ) async { + final samples = []; + trigger(); + expect(clock.isBoosting, isTrue); + for (var i = 0; i < 150; i++) { + await tester.pump(_frame); + samples.add(clock.boost); + } + return samples; + } - clock.activate(); - await tester.pump(); - // Get past the fade (fade notifies at full rate). - await tester.pump(const Duration(seconds: 1)); - notifications = 0; - // 60 frames at ~8ms ≈ 0.48s of 120fps input. - for (var i = 0; i < 60; i++) { - await tester.pump(const Duration(milliseconds: 8)); + for (final (name, peak) in [ + ('pulse', BeamClock.pulsePeak), + ('flash', BeamClock.flashPeak), + ]) { + testWidgets('$name rises above 1 and returns to exactly 1', ( + tester, + ) async { + final clock = makeClock(tester); + await runVisible(tester, clock); + expect(clock.boost, 1); + expect(clock.isBoosting, isFalse); + + final samples = await playBoost( + tester, + clock, + name == 'pulse' ? clock.pulse : clock.flash, + ); + final top = samples.reduce((a, b) => a > b ? a : b); + expect(top, greaterThan(1)); + expect(top, closeTo(peak, peak * 0.05)); + for (final s in samples) { + expect(s, greaterThanOrEqualTo(1)); + } + expect(samples.last, 1); + expect(clock.boost, 1); + expect(clock.isBoosting, isFalse); + disposeClock(clock); + }); } - // At a 30fps cap that window allows ~15-16 notifications; allow slack. - expect(notifications, lessThan(25)); - expect(notifications, greaterThan(8)); - clock.dispose(); - }); - testWidgets('mid-fade-out re-activation resumes without opacity jump', ( - tester, - ) async { - vsync = tester; - final clock = makeClock(); + test('flash peaks higher than pulse', () { + expect(BeamClock.pulsePeak, greaterThan(1)); + expect(BeamClock.flashPeak, greaterThan(BeamClock.pulsePeak)); + }); - clock.activate(); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); + testWidgets('is a no-op while hidden or paused', (tester) async { + final clock = makeClock(tester); + clock.pulse(); + clock.flash(); + expect(clock.isBoosting, isFalse); + expect(clock.boost, 1); + + await runVisible(tester, clock); + clock.pause(); + clock.pulse(); + expect(clock.isBoosting, isFalse); + disposeClock(clock); + }); + + testWidgets('a restart from hidden drops a boost', (tester) async { + final clock = makeClock(tester); + await runVisible(tester, clock); + clock.deactivate(); + clock.flash(); + expect(clock.isBoosting, isTrue, reason: 'still visible while fading'); + await tester.pump(const Duration(seconds: 1)); + clock.activate(); + expect(clock.isBoosting, isFalse); + expect(clock.boost, 1); + disposeClock(clock); + }); + }); + + testWidgets('a completed fade-out ends any boost', (tester) async { + final clock = makeClock(tester); + await runVisible(tester, clock); clock.deactivate(); - await tester.pump(const Duration(milliseconds: 60)); - final midOpacity = clock.fadeOpacity; - expect(midOpacity, lessThan(1)); - expect(midOpacity, greaterThan(0)); + clock.flash(); + await tester.pump(const Duration(seconds: 1)); + expect(clock.isVisible, isFalse); + expect(clock.isBoosting, isFalse); + expect(clock.boost, 1); - clock.activate(); - expect(clock.stage, BeamFadeStage.fadingIn); - // Fade resumes from the interrupted opacity, not from zero. - expect(clock.fadeOpacity, closeTo(midOpacity, 0.05)); - await tester.pump(const Duration(milliseconds: 700)); - expect(clock.fadeOpacity, 1); - clock.dispose(); + // A static frame shown next must not inherit the stale envelope. + clock.showStatic(); + expect(clock.boost, 1); + disposeClock(clock); + }); + + group('timeline reset listeners', () { + testWidgets('fire on a restart and after a fade-out, not mid-fade', ( + tester, + ) async { + final clock = makeClock(tester); + var resets = 0; + void listener() => resets++; + clock.addTimelineResetListener(listener); + + clock.activate(); + expect(resets, 1, reason: 'activation from hidden restarts at zero'); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(resets, 1, reason: 'ordinary frames never reset'); + + clock.deactivate(); + await tester.pump(const Duration(milliseconds: 100)); + clock.activate(); + expect(resets, 1, reason: 'a mid-fade re-activation continues'); + + await tester.pump(const Duration(seconds: 1)); + clock.deactivate(); + await tester.pump(const Duration(seconds: 1)); + expect(resets, 2, reason: 'the completed fade-out zeroes elapsed'); + + clock.removeTimelineResetListener(listener); + clock.activate(); + expect(resets, 2); + disposeClock(clock); + }); + + testWidgets('a listener may remove itself while being called', ( + tester, + ) async { + final clock = makeClock(tester); + var calls = 0; + late void Function() once; + once = () { + calls++; + clock.removeTimelineResetListener(once); + }; + var other = 0; + clock.addTimelineResetListener(once); + clock.addTimelineResetListener(() => other++); + + clock.activate(); + expect(calls, 1); + expect(other, 1); + clock.deactivate(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(calls, 1); + expect(other, 2); + disposeClock(clock); + }); + }); + + group('dispose', () { + testWidgets('mid-fade leaves no ticker behind', (tester) async { + final clock = makeClock(tester); + clock.activate(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(tester.binding.transientCallbackCount, greaterThan(0)); + disposeClock(clock); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('a never-started clock disposes cleanly', (tester) async { + final clock = makeClock(tester); + expect(() => disposeClock(clock), returnsNormally); + }); }); } diff --git a/test/animation/beam_periods_test.dart b/test/animation/beam_periods_test.dart deleted file mode 100644 index c9ace27..0000000 --- a/test/animation/beam_periods_test.dart +++ /dev/null @@ -1,267 +0,0 @@ -import 'dart:ui'; - -import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/models/beam_colors.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/models/beam_style.dart'; -import 'package:flutter_border_beam/src/models/beam_timing.dart'; -import 'package:flutter_border_beam/src/models/beam_variant.dart'; -import 'package:flutter_test/flutter_test.dart'; - -BeamConfig _config( - BeamVariant variant, { - BeamTiming timing = const BeamTiming(), - double hueRange = 30, -}) => BeamConfig.resolve( - variant: variant, - palette: BeamColors.colorful.resolve(), - brightness: Brightness.dark, - style: BeamStyle(hueRange: hueRange), - timing: timing, -); - -BeamPhaseResolver _resolver( - BeamVariant variant, { - BeamTiming timing = const BeamTiming(), - double hueRange = 30, -}) => BeamPhaseResolver(_config(variant, timing: timing, hueRange: hueRange)); - -/// `BeamTiming` exposes the tracks that do not ride the cycle: the hue -/// ping-pong (or revolution), the line bloom's own hue, and the line's -/// breathe/spike periods expressed as multiples of the cycle. Each was a -/// fixed constant in the phase resolver before; each must now follow what -/// the timing asks for, and only that track. -void main() { - group('huePeriod', () { - test('the traveling default is a 12s ping-pong', () { - final config = _config(BeamVariant.rotate); - expect(config.huePeriodSeconds, 12); - final r = BeamPhaseResolver(config); - expect(r.sample(0, 1).hueDegrees, closeTo(-30, 1e-9)); - expect(r.sample(6, 1).hueDegrees, closeTo(30, 1e-6)); - }); - - test('a custom period puts +hueRange at half of it', () { - const timing = BeamTiming(huePeriod: Duration(seconds: 4)); - final config = _config(BeamVariant.rotate, timing: timing); - expect(config.huePeriodSeconds, closeTo(4, 1e-9)); - final r = BeamPhaseResolver(config); - expect(r.sample(0, 1).hueDegrees, closeTo(-30, 1e-9)); - expect(r.sample(2, 1).hueDegrees, closeTo(30, 1e-6)); - expect(r.sample(4, 1).hueDegrees, closeTo(-30, 1e-6)); - expect( - r.sample(1, 1).hueDegrees, - closeTo(0, 1e-6), - reason: 'the ease-in-out curve crosses zero at a quarter period', - ); - }); - - test('it does not move the cycle-driven tracks', () { - final fast = _resolver( - BeamVariant.rotate, - timing: const BeamTiming(huePeriod: Duration(seconds: 3)), - ); - final slow = _resolver( - BeamVariant.rotate, - timing: const BeamTiming(huePeriod: Duration(seconds: 30)), - ); - expect( - fast.sample(1.2, 1).angleRadians, - closeTo(slow.sample(1.2, 1).angleRadians, 1e-9), - ); - expect( - fast.sample(1.2, 1).hueDegrees, - isNot(closeTo(slow.sample(1.2, 1).hueDegrees, 1e-3)), - ); - }); - - test('the pulse defaults are the preset periods', () { - expect(_config(BeamVariant.pulseInside).huePeriodSeconds, 16); - expect(_config(BeamVariant.pulseOutside).huePeriodSeconds, 14); - // A continuous revolution, not a ping-pong. - expect( - _resolver(BeamVariant.pulseInside).sample(8, 1).hueDegrees, - closeTo(180, 1e-6), - ); - expect( - _resolver(BeamVariant.pulseOutside).sample(7, 1).hueDegrees, - closeTo(180, 1e-6), - ); - }); - - test('a custom period replaces the pulse preset period', () { - const timing = BeamTiming(huePeriod: Duration(seconds: 5)); - for (final variant in [ - BeamVariant.pulseInside, - BeamVariant.pulseOutside, - ]) { - final config = _config(variant, timing: timing); - expect(config.huePeriodSeconds, closeTo(5, 1e-9), reason: '$variant'); - final r = BeamPhaseResolver(config); - expect(r.sample(1.25, 1).hueDegrees, closeTo(90, 1e-6)); - expect(r.sample(2.5, 1).hueDegrees, closeTo(180, 1e-6)); - expect( - r.sample(5, 1).hueDegrees, - closeTo(0, 1e-6), - reason: 'it wraps at the custom period, not at 14s or 16s', - ); - } - }); - - test('a sub-second period is still a full ping-pong', () { - final r = _resolver( - BeamVariant.small, - timing: const BeamTiming(huePeriod: Duration(milliseconds: 200)), - ); - expect(r.sample(0.1, 1).hueDegrees, closeTo(30, 1e-6)); - expect(r.sample(0.2, 1).hueDegrees, closeTo(-30, 1e-6)); - }); - }); - - group('bloomHuePeriod', () { - // The line variant caps hueRange at 13°, so its bloom track spans ±23°. - const bloomRange = 23.0; - - test('the default is an 8s ping-pong over ±(hueRange + 10)', () { - final config = _config(BeamVariant.line); - expect(config.bloomHuePeriodSeconds, 8); - final r = BeamPhaseResolver(config); - expect(r.sample(0, 1).bloomHueDegrees, closeTo(-bloomRange, 1e-9)); - expect(r.sample(4, 1).bloomHueDegrees, closeTo(bloomRange, 1e-6)); - }); - - test('a custom period retimes only the bloom hue', () { - const timing = BeamTiming(bloomHuePeriod: Duration(seconds: 4)); - final config = _config(BeamVariant.line, timing: timing); - expect(config.bloomHuePeriodSeconds, closeTo(4, 1e-9)); - expect(config.huePeriodSeconds, 12, reason: 'the main hue is untouched'); - - final r = BeamPhaseResolver(config); - final reference = _resolver(BeamVariant.line); - expect(r.sample(2, 1).bloomHueDegrees, closeTo(bloomRange, 1e-6)); - expect( - r.sample(1.3, 1).hueDegrees, - closeTo(reference.sample(1.3, 1).hueDegrees, 1e-9), - ); - expect( - r.sample(1.3, 1).lineX, - closeTo(reference.sample(1.3, 1).lineX, 1e-9), - ); - }); - - test('a wider hueRange is capped before the bloom range is derived', () { - final r = _resolver(BeamVariant.line, hueRange: 90); - expect(r.config.hueRange, 13); - expect(r.sample(4, 1).bloomHueDegrees, closeTo(bloomRange, 1e-6)); - }); - }); - - group('line breathe and spike factors', () { - const cycle = Duration(seconds: 2); - const cycleSeconds = 2.0; - - test('the defaults are 1.3, 1.33 and 1.7 cycles', () { - final config = _config( - BeamVariant.line, - timing: const BeamTiming(cycle: cycle), - ); - expect(config.breatheFactor, 1.3); - expect(config.spikeFactor, 1.33); - expect(config.spike2Factor, 1.7); - }); - - test('lineH completes one breathe cycle at cycle × breatheFactor', () { - const factor = 2.0; - final r = _resolver( - BeamVariant.line, - timing: const BeamTiming(cycle: cycle, breatheFactor: factor), - ); - const period = cycleSeconds * factor; - for (final t in [0.0, 0.7, 1.9, 3.4]) { - expect( - r.sample(t + period, 1).lineH, - closeTo(r.sample(t, 1).lineH, 1e-9), - reason: 't=$t repeats after $period s', - ); - } - expect( - r.sample(period / 2, 1).lineH, - isNot(closeTo(r.sample(0, 1).lineH, 1e-3)), - reason: 'the track actually moves inside the period', - ); - }); - - test('halving the factor halves the time to the same breathe phase', () { - final slow = _resolver( - BeamVariant.line, - timing: const BeamTiming(cycle: cycle, breatheFactor: 2), - ); - final fast = _resolver( - BeamVariant.line, - timing: const BeamTiming(cycle: cycle, breatheFactor: 1), - ); - expect(slow.sample(2, 1).lineH, closeTo(fast.sample(1, 1).lineH, 1e-9)); - }); - - test('spikeFactor and spike2Factor drive their own tracks only', () { - final base = _resolver( - BeamVariant.line, - timing: const BeamTiming(cycle: cycle), - ); - final spiked = _resolver( - BeamVariant.line, - timing: const BeamTiming(cycle: cycle, spikeFactor: 3), - ); - final spiked2 = _resolver( - BeamVariant.line, - timing: const BeamTiming(cycle: cycle, spike2Factor: 3), - ); - - const t = 1.1; - expect( - spiked.sample(t, 1).spike, - isNot(closeTo(base.sample(t, 1).spike, 1e-3)), - ); - expect( - spiked.sample(t, 1).spike2, - closeTo(base.sample(t, 1).spike2, 1e-9), - ); - expect(spiked.sample(t, 1).lineH, closeTo(base.sample(t, 1).lineH, 1e-9)); - - expect( - spiked2.sample(t, 1).spike2, - isNot(closeTo(base.sample(t, 1).spike2, 1e-3)), - ); - expect( - spiked2.sample(t, 1).spike, - closeTo(base.sample(t, 1).spike, 1e-9), - ); - - const period = cycleSeconds * 3; - expect( - spiked.sample(0.4 + period, 1).spike, - closeTo(spiked.sample(0.4, 1).spike, 1e-9), - ); - expect( - spiked2.sample(0.4 + period, 1).spike2, - closeTo(spiked2.sample(0.4, 1).spike2, 1e-9), - ); - }); - - test('the factors scale with the cycle they multiply', () { - final short = _resolver( - BeamVariant.line, - timing: const BeamTiming(cycle: Duration(seconds: 1), breatheFactor: 2), - ); - final long = _resolver( - BeamVariant.line, - timing: const BeamTiming(cycle: Duration(seconds: 2), breatheFactor: 2), - ); - expect( - long.sample(2.4, 1).lineH, - closeTo(short.sample(1.2, 1).lineH, 1e-9), - reason: 'twice the cycle is twice the breathe period', - ); - }); - }); -} diff --git a/test/animation/beam_phases_test.dart b/test/animation/beam_phases_test.dart index 4f2ec2c..2c817ee 100644 --- a/test/animation/beam_phases_test.dart +++ b/test/animation/beam_phases_test.dart @@ -1,246 +1,460 @@ import 'dart:math' as math; -import 'dart:ui'; +import 'dart:ui' show Brightness; +import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/constants/line_keyframes.dart'; -import 'package:flutter_border_beam/src/models/beam_colors.dart'; import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/models/beam_style.dart'; -import 'package:flutter_border_beam/src/models/beam_timing.dart'; -import 'package:flutter_border_beam/src/models/beam_variant.dart'; +import 'package:flutter_border_beam/src/models/beam_palette.dart'; import 'package:flutter_test/flutter_test.dart'; -BeamConfig _config( - BeamVariant v, { - bool staticColors = false, - double hueRange = 30, - Duration? cycleDuration, +BeamConfig _config({ + BeamEffect effect = const BeamEffect.rotate(), + BeamPalette? palette, + BeamHueMode? hueMode, + double? hueShift, + Duration? cycle = const Duration(seconds: 2), + Duration? cycleGap, + Duration? huePeriod, + double? phaseOffset, + BeamDirection? direction, }) => BeamConfig.resolve( - variant: v, - palette: BeamColors.colorful.resolve(), + effect: effect, + palette: palette ?? BeamColors.colorful.resolve(), brightness: Brightness.dark, - style: BeamStyle(staticColors: staticColors, hueRange: hueRange), - timing: BeamTiming(cycle: cycleDuration), + style: BeamStyle(hueMode: hueMode, hueShift: hueShift), + timing: BeamTiming( + cycle: cycle, + cycleGap: cycleGap, + huePeriod: huePeriod, + phaseOffset: phaseOffset, + direction: direction, + ), ); -// The retime a widget performs when its cycle duration changes mid-run: -// elapsed time is rescaled by the cycle ratio and the hue clock is shifted -// back by the same amount. -({double t, BeamPhaseResolver resolver}) _retimed( - BeamPhaseResolver from, - double t, - Duration newCycle, -) { - final next = BeamPhaseResolver( - _config(from.config.variant, hueRange: 30, cycleDuration: newCycle), - ); - final scaled = t * next.config.cycleSeconds / from.config.cycleSeconds; - next.hueTimeOffset = from.hueTimeOffset + t - scaled; - return (t: scaled, resolver: next); -} +BeamPhaseResolver _resolver({ + BeamEffect effect = const BeamEffect.rotate(), + BeamPalette? palette, + BeamHueMode? hueMode, + double? hueShift, + Duration? cycle = const Duration(seconds: 2), + Duration? cycleGap, + Duration? huePeriod, + double? phaseOffset, + BeamDirection? direction, +}) => BeamPhaseResolver( + _config( + effect: effect, + palette: palette, + hueMode: hueMode, + hueShift: hueShift, + cycle: cycle, + cycleGap: cycleGap, + huePeriod: huePeriod, + phaseOffset: phaseOffset, + direction: direction, + ), +); +/// The non-travel half of the phase resolver: the hue drift, the ambient +/// cycle count, the per-track time offsets the widget uses to keep tracks +/// continuous, the repeat budget, and the reduced-motion static frame. void main() { - group('sampleKeyframes', () { - test('linear tables hit every stop exactly', () { - for (final f in lineTravelX) { - expect(sampleKeyframes(lineTravelX, f.t), closeTo(f.value, 1e-9)); + final ambient = BeamEffect.values.where((e) => !e.travels).toList(); + const huePeriod = Duration(seconds: 8); + const period = 8.0; + + group('hue', () { + test('none never drifts', () { + final r = _resolver(hueMode: BeamHueMode.none); + for (final t in [0.0, 1.3, 4.0, 99.9]) { + expect(r.sample(t, 1).hueDegrees, 0); } - // Linear midpoint between stops. - expect(sampleKeyframes(lineTravelX, 0.05), closeTo(0.105, 1e-9)); }); - test('eased tables hit stops and ease within segments', () { - for (final f in lineBreatheH) { - expect( - sampleKeyframes(lineBreatheH, f.t, easedSegments: true), - closeTo(f.value, 1e-9), + test('a fixed-hue palette never drifts', () { + for (final colors in [BeamColors.mono, BeamColors.gold]) { + final r = _resolver( + palette: colors.resolve(), + hueMode: BeamHueMode.continuous, ); + expect(r.sample(3.3, 1).hueDegrees, 0, reason: '$colors'); } - // Just after a stop, an eased segment moves slower than linear. - final eased = sampleKeyframes(lineSpike, 0.05, easedSegments: true); - final linear = sampleKeyframes(lineSpike, 0.05); - expect((eased - 0.8).abs(), lessThan((linear - 0.8).abs())); }); - test('clamps outside 0-1', () { - expect(sampleKeyframes(lineEdgeFade, -0.5), 0); - expect(sampleKeyframes(lineEdgeFade, 1.5), 0); + test('continuous revolves through 360° once per hue period', () { + final r = _resolver( + hueMode: BeamHueMode.continuous, + huePeriod: huePeriod, + ); + expect(r.sample(0, 1).hueDegrees, 0); + expect(r.sample(period / 4, 1).hueDegrees, closeTo(90, 1e-9)); + expect(r.sample(period / 2, 1).hueDegrees, closeTo(180, 1e-9)); + expect(r.sample(period * 0.999, 1).hueDegrees, greaterThan(359)); + expect(r.sample(period, 1).hueDegrees, closeTo(0, 1e-9)); + expect(r.sample(period * 1.25, 1).hueDegrees, closeTo(90, 1e-9)); }); - }); - group('BeamPhaseResolver', () { - test('rotate: angle spins one turn per cycle', () { - final r = BeamPhaseResolver(_config(BeamVariant.rotate)); - expect(r.sample(0, 1).angleRadians, closeTo(0, 1e-9)); - expect(r.sample(1.96 / 2, 1).angleRadians, closeTo(math.pi, 1e-6)); - expect(r.sample(1.96, 1).angleRadians, closeTo(0, 1e-6)); - }); - - test('line: travel, edge fade, and hue cap', () { - final config = _config(BeamVariant.line, hueRange: 30); - expect(config.hueRange, 13, reason: 'line caps hueRange at 13°'); - final r = BeamPhaseResolver(config); - final start = r.sample(0, 1); - expect(start.lineX, closeTo(0.06, 1e-9)); - expect(start.edge, 0); - final mid = r.sample(3.1 / 2, 1); - expect(mid.lineX, closeTo(0.5, 1e-6)); - expect(mid.edge, 1); - }); - - test('hue modes: static, ping-pong, continuous', () { - final staticR = BeamPhaseResolver( - _config(BeamVariant.rotate, staticColors: true), + test('continuous ignores hueShift', () { + final narrow = _resolver( + hueMode: BeamHueMode.continuous, + hueShift: 5, + huePeriod: huePeriod, + ); + final wide = _resolver( + hueMode: BeamHueMode.continuous, + hueShift: 90, + huePeriod: huePeriod, ); - expect(staticR.sample(5, 1).hueDegrees, 0); + expect(narrow.sample(3, 1).hueDegrees, wide.sample(3, 1).hueDegrees); + }); - final rotate = BeamPhaseResolver(_config(BeamVariant.rotate)); - expect(rotate.sample(0, 1).hueDegrees, closeTo(-30, 1e-6)); - expect(rotate.sample(6, 1).hueDegrees, closeTo(30, 1e-6)); - expect(rotate.sample(12, 1).hueDegrees, closeTo(-30, 1e-6)); + test('pingPong swings −shift → +shift → −shift over one period', () { + final r = _resolver( + hueMode: BeamHueMode.pingPong, + hueShift: 20, + huePeriod: huePeriod, + ); + expect(r.sample(0, 1).hueDegrees, closeTo(-20, 1e-9)); + expect(r.sample(period / 2, 1).hueDegrees, closeTo(20, 1e-9)); + expect(r.sample(period, 1).hueDegrees, closeTo(-20, 1e-9)); + // Symmetric easing crosses zero at each quarter. + expect(r.sample(period / 4, 1).hueDegrees, closeTo(0, 1e-6)); + expect(r.sample(period * 3 / 4, 1).hueDegrees, closeTo(0, 1e-6)); + }); - final pulse = BeamPhaseResolver(_config(BeamVariant.pulseInside)); - // Continuous sawtooth over 16s: quarter revolution at 4s. - expect(pulse.sample(4, 1).hueDegrees, closeTo(90, 1e-6)); - expect(pulse.sample(16, 1).hueDegrees, closeTo(0, 1e-6)); + test('pingPong stays within ±hueShift and reaches both ends', () { + for (final shift in [0.0, 13.0, 45.0]) { + final r = _resolver( + hueMode: BeamHueMode.pingPong, + hueShift: shift, + huePeriod: huePeriod, + ); + var lo = double.infinity; + var hi = double.negativeInfinity; + for (var i = 0; i <= 800; i++) { + final hue = r.sample(i * 0.01, 1).hueDegrees; + expect(hue, inInclusiveRange(-shift - 1e-9, shift + 1e-9)); + if (hue < lo) lo = hue; + if (hue > hi) hi = hue; + } + expect(lo, closeTo(-shift, 1e-9), reason: 'shift $shift'); + expect(hi, closeTo(shift, 1e-9), reason: 'shift $shift'); + } }); - test('mono palette forces static colors through config', () { - final config = BeamConfig.resolve( - variant: BeamVariant.rotate, - palette: BeamColors.mono.resolve(), - brightness: Brightness.dark, - ); - expect(config.staticColors, isTrue); - expect(BeamPhaseResolver(config).sample(3, 1).hueDegrees, 0); + test('the hue period moves the hue and nothing else', () { + final fast = _resolver(huePeriod: const Duration(seconds: 3)); + final slow = _resolver(huePeriod: const Duration(seconds: 30)); + final a = fast.sample(1.2, 1); + final b = slow.sample(1.2, 1); + expect(a.hueDegrees, isNot(closeTo(b.hueDegrees, 1e-3))); + expect(a.travelProgress, b.travelProgress); + expect(a.cycles, b.cycles); + expect(a.fadeOpacity, b.fadeOpacity); }); - test('hueTimeOffset shifts only the fixed-period hue tracks', () { - final r = BeamPhaseResolver(_config(BeamVariant.rotate)); - final unshifted = BeamPhaseResolver(_config(BeamVariant.rotate)); - r.hueTimeOffset = 2; - expect( - r.sample(3, 1).hueDegrees, - closeTo(unshifted.sample(5, 1).hueDegrees, 1e-9), - ); - expect( - r.sample(3, 1).angleRadians, - closeTo(unshifted.sample(3, 1).angleRadians, 1e-9), - reason: 'the cycle-derived tracks ignore the hue offset', + test('the hue keeps drifting through a cycle gap', () { + final r = _resolver( + cycleGap: const Duration(seconds: 2), + hueMode: BeamHueMode.continuous, + huePeriod: huePeriod, ); + // 3s is mid-gap: the beam is dark, but the colours still move. + expect(r.sample(3, 1).fadeOpacity, 0); + expect(r.sample(3, 1).hueDegrees, isNot(r.sample(2.5, 1).hueDegrees)); + }); - final line = BeamPhaseResolver(_config(BeamVariant.line)) - ..hueTimeOffset = -1.5; - final lineRef = BeamPhaseResolver(_config(BeamVariant.line)); + for (final effect in BeamEffect.values) { + test('${effect.name}: the default mode drifts as configured', () { + final r = _resolver(effect: effect); + final mode = r.config.hueMode; + expect(mode, effect.defaultHueMode); + final p = r.config.huePeriodSeconds; + final shift = r.config.hueShift; + final hues = {}; + for (var i = 0; i < 50; i++) { + final hue = r.sample(i * p / 37, 1).hueDegrees; + hues.add(hue); + switch (mode) { + case BeamHueMode.none: + expect(hue, 0); + case BeamHueMode.continuous: + expect(hue, inInclusiveRange(0, 360)); + expect(hue, lessThan(360)); + case BeamHueMode.pingPong: + expect(hue, inInclusiveRange(-shift - 1e-9, shift + 1e-9)); + } + } + // A drifting mode actually moves: a hue stuck at 0 satisfies every + // range above. + if (mode != BeamHueMode.none) { + expect(hues.length, greaterThan(10), reason: '$mode'); + final span = hues.reduce(math.max) - hues.reduce(math.min); + final expected = mode == BeamHueMode.pingPong ? shift : 180.0; + expect(span, greaterThan(expected), reason: '$mode: span $span'); + } + }); + } + }); + + group('cycles', () { + for (final effect in BeamEffect.values) { + test('${effect.name}: counts elapsed cycles without wrapping', () { + final r = _resolver(effect: effect, cycleGap: Duration.zero); + expect(r.sample(0, 1).cycles, 0); + expect(r.sample(1, 1).cycles, closeTo(0.5, 1e-12)); + expect(r.sample(7.3, 1).cycles, closeTo(3.65, 1e-12)); + expect(r.sample(1000, 1).cycles, closeTo(500, 1e-9)); + }); + } + + test('the gap does not stretch the ambient clock', () { + // Ambient effects ignore the gap outright; a travelling one rests in + // it between sweeps, but its ambient clock runs straight through. + for (final effect in BeamEffect.values) { + final r = _resolver( + effect: effect, + cycleGap: const Duration(seconds: 1), + ); + expect(r.sample(6, 1).cycles, closeTo(3, 1e-12), reason: effect.name); + } + }); + + test('phaseOffset puts an ambient beam out of step', () { + for (final effect in ambient) { + final plain = _resolver(effect: effect); + final shifted = _resolver(effect: effect, phaseOffset: 0.5); + expect( + shifted.sample(1, 1).cycles - plain.sample(1, 1).cycles, + closeTo(0.5, 1e-12), + reason: effect.name, + ); + } + }); + }); + + group('time offsets', () { + test('hueTimeOffset shifts only the hue', () { + final plain = _resolver(effect: const BeamEffect.pulse()); + final shifted = _resolver(effect: const BeamEffect.pulse()) + ..hueTimeOffset = 2; + final a = shifted.sample(3, 1); + expect(a.hueDegrees, closeTo(plain.sample(5, 1).hueDegrees, 1e-9)); + expect(a.cycles, plain.sample(3, 1).cycles); + + final rotate = _resolver()..hueTimeOffset = -1.5; + final rotatePlain = _resolver(); expect( - line.sample(4, 1).bloomHueDegrees, - closeTo(lineRef.sample(2.5, 1).bloomHueDegrees, 1e-9), + rotate.sample(4, 1).hueDegrees, + closeTo(rotatePlain.sample(2.5, 1).hueDegrees, 1e-9), ); expect( - line.sample(4, 1).lineX, - closeTo(lineRef.sample(4, 1).lineX, 1e-9), + rotate.sample(4, 1).travelProgress, + rotatePlain.sample(4, 1).travelProgress, ); + }); - final pulse = BeamPhaseResolver(_config(BeamVariant.pulseInside)) - ..hueTimeOffset = 4; - // Sawtooth over 16s: a 4s shift is a quarter revolution. - expect(pulse.sample(0, 1).hueDegrees, closeTo(90, 1e-6)); + test('breatheTimeOffset shifts only the ambient clock', () { + final plain = _resolver(); + final shifted = _resolver()..breatheTimeOffset = 1; + final a = shifted.sample(3, 1); + final b = plain.sample(3, 1); + expect(a.cycles, closeTo(b.cycles + 0.5, 1e-12)); + expect(a.travelProgress, b.travelProgress); + expect(a.hueDegrees, b.hueDegrees); }); - test('a static palette ignores the hue offset', () { - final r = BeamPhaseResolver( - _config(BeamVariant.rotate, staticColors: true), - )..hueTimeOffset = 3.7; - expect(r.sample(2, 1).hueDegrees, 0); + test('travelTimeOffset shifts only the sweep and the repeat budget', () { + final plain = _resolver()..repeatCycles = 1; + final shifted = _resolver() + ..repeatCycles = 1 + ..travelTimeOffset = 1; + final a = shifted.sample(0.5, 1); + final b = plain.sample(0.5, 1); + expect(a.travelProgress, closeTo(b.travelProgress + 0.5, 1e-12)); + expect(a.hueDegrees, b.hueDegrees); + expect(a.cycles, b.cycles); + expect(plain.finishedAt(1.5), isFalse); + expect(shifted.finishedAt(1.5), isTrue); }); - test('retiming a cycle change holds every rotate track', () { - final before = BeamPhaseResolver( - _config(BeamVariant.rotate, cycleDuration: const Duration(seconds: 2)), - ); - const t = 0.9; - final ref = before.sample(t, 1); - final next = _retimed(before, t, const Duration(seconds: 4)); - final after = next.resolver.sample(next.t, 1); - expect(after.angleRadians, closeTo(ref.angleRadians, 1e-9)); - expect(after.hueDegrees, closeTo(ref.hueDegrees, 1e-9)); + test('a retime with a hue correction holds every track', () { + // What the widget does when the cycle changes mid-run: rescale + // elapsed time by the cycle ratio, and shift the fixed-period hue + // track back by the amount the timeline moved. + for (final effect in BeamEffect.values) { + final before = _resolver( + effect: effect, + cycleGap: Duration.zero, + cycle: const Duration(seconds: 2), + ); + final after = _resolver( + effect: effect, + cycleGap: Duration.zero, + cycle: const Duration(milliseconds: 4500), + ); + const t = 1.3; + final scaled = + t * after.config.cycleSeconds / before.config.cycleSeconds; + after.hueTimeOffset = t - scaled; + final a = before.sample(t, 1); + final b = after.sample(scaled, 1); + expect(b.travelProgress, closeTo(a.travelProgress, 1e-9)); + expect(b.cycles, closeTo(a.cycles, 1e-9), reason: effect.name); + expect(b.hueDegrees, closeTo(a.hueDegrees, 1e-9), reason: effect.name); + } }); + }); - test('retiming a cycle change holds every line track', () { - final before = BeamPhaseResolver( - _config(BeamVariant.line, cycleDuration: const Duration(seconds: 3)), - ); - const t = 2.4; - final ref = before.sample(t, 1); - final next = _retimed(before, t, const Duration(milliseconds: 1500)); - final after = next.resolver.sample(next.t, 1); - expect(after.lineX, closeTo(ref.lineX, 1e-9)); - expect(after.lineW, closeTo(ref.lineW, 1e-9)); - expect(after.lineH, closeTo(ref.lineH, 1e-9)); - expect(after.spike, closeTo(ref.spike, 1e-9)); - expect(after.spike2, closeTo(ref.spike2, 1e-9)); - expect(after.edge, closeTo(ref.edge, 1e-9)); - expect(after.hueDegrees, closeTo(ref.hueDegrees, 1e-9)); - expect(after.bloomHueDegrees, closeTo(ref.bloomHueDegrees, 1e-9)); - }); - - test('retiming a cycle change holds every pulse oscillator', () { - final before = BeamPhaseResolver( - _config( - BeamVariant.pulseInside, - cycleDuration: const Duration(milliseconds: 2300), - ), - ); - const t = 1.7; - final ref = before.sample(t, 1); - final next = _retimed(before, t, const Duration(seconds: 5)); - final after = next.resolver.sample(next.t, 1); - for (var i = 0; i < 3; i++) { - expect(after.pulse.bw[i], closeTo(ref.pulse.bw[i], 1e-9)); - expect(after.pulse.bh[i], closeTo(ref.pulse.bh[i], 1e-9)); - expect(after.pulse.bx[i], closeTo(ref.pulse.bx[i], 1e-9)); - expect(after.pulse.by[i], closeTo(ref.pulse.by[i], 1e-9)); + group('repeat budget', () { + test('no budget never finishes', () { + final r = _resolver(); + expect(r.finishedAt(1e6), isFalse); + expect(r.sample(1e6, 1).finished, isFalse); + }); + + test('a budget of n finishes at the n-th cycle boundary', () { + for (final n in [1, 3]) { + final r = _resolver()..repeatCycles = n; + expect(r.finishedAt(n * 2 - 0.001), isFalse, reason: 'n=$n'); + expect(r.finishedAt(n * 2 + 0.001), isTrue, reason: 'n=$n'); + expect(r.sample(n * 2 + 0.001, 1).finished, isTrue); + expect(r.sample(n * 2 - 0.001, 1).finished, isFalse); } - expect(after.pulse.bgh, closeTo(ref.pulse.bgh, 1e-9)); - expect(after.pulse.bopTl, closeTo(ref.pulse.bopTl, 1e-9)); - expect(after.pulse.bopTr, closeTo(ref.pulse.bopTr, 1e-9)); - expect(after.pulse.bopBl, closeTo(ref.pulse.bopBl, 1e-9)); - expect(after.pulse.bopBr, closeTo(ref.pulse.bopBr, 1e-9)); - expect(after.hueDegrees, closeTo(ref.hueDegrees, 1e-9)); }); - test('static frame is full-opacity and hue-neutral', () { - final pulse = BeamPhaseResolver(_config(BeamVariant.pulseOutside)); - final frame = pulse.staticFrame(); - expect(frame.fadeOpacity, 1); - expect(frame.hueDegrees, 0); - expect(frame.pulse.bgh, 1); + test('a travelling gap counts toward its cycle', () { + final r = _resolver(cycleGap: const Duration(seconds: 1)) + ..repeatCycles = 1; + expect(r.finishedAt(2.5), isFalse); + expect(r.finishedAt(3.01), isTrue); + }); + + test('ambient effects ignore a configured gap', () { + for (final effect in ambient) { + final r = _resolver( + effect: effect, + cycleGap: const Duration(seconds: 1), + )..repeatCycles = 2; + expect(r.sample(3.99, 1).finished, isFalse, reason: effect.name); + expect(r.sample(4.01, 1).finished, isTrue, reason: effect.name); + } + }); + + test('a phase offset moves the finish with the timeline', () { + final r = _resolver(phaseOffset: 0.5)..repeatCycles = 1; + expect(r.finishedAt(0.9), isFalse); + expect(r.finishedAt(1.1), isTrue); + }); + + test('sample and finishedAt agree', () { + for (final effect in BeamEffect.values) { + final r = _resolver(effect: effect)..repeatCycles = 2; + for (var i = 0; i < 40; i++) { + final t = i * 0.37; + expect(r.sample(t, 1).finished, r.finishedAt(t), reason: '$t'); + } + } }); }); - group('BeamConfig.resolve', () { - test('strength clamps and defaults resolve', () { - final c = BeamConfig.resolve( - variant: BeamVariant.small, - palette: BeamColors.colorful.resolve(), - brightness: Brightness.dark, - style: const BeamStyle(strength: 1.7), - ); - expect(c.strength, 1); - expect(c.borderRadius.topLeft.x, 32); - expect(c.cycleSeconds, closeTo(1.96, 1e-9)); - expect(c.brightnessFactor, 1.3); - expect(c.saturation, 1.2); - }); - - test('pulse presets carry brightness overrides', () { - final c = BeamConfig.resolve( - variant: BeamVariant.pulseInside, - palette: BeamColors.colorful.resolve(), - brightness: Brightness.dark, - ); - expect(c.brightnessFactor, 0.75); - expect(c.cycleSeconds, closeTo(2.3, 1e-9)); + group('staticFrame', () { + for (final effect in BeamEffect.values) { + test('${effect.name}: full opacity, hue-neutral, deterministic', () { + final r = _resolver(effect: effect, hueMode: BeamHueMode.continuous); + final a = r.staticFrame(); + final b = r.staticFrame(); + expect(a.fadeOpacity, 1); + expect(a.hueDegrees, 0, reason: 'the palette as given'); + expect(a.hueTime, isNull, reason: "no time for an effect's own drift"); + expect(r.sample(2, 1).hueTime, 2, reason: 'a running frame has one'); + expect(a.driven, isFalse); + expect(a.finished, isFalse); + expect(a.travelProgress, b.travelProgress); + expect(a.travellers, b.travellers); + expect(a.cycles, b.cycles); + expect(a.cycles.isFinite, isTrue); + }); + } + + test('a travelling effect shows the sweep mid-border', () { + for (final effect in BeamEffect.values.where((e) => e.travels)) { + final frame = _resolver(effect: effect).staticFrame(); + expect(frame.travelProgress, inExclusiveRange(0, 1)); + } + final three = _resolver(effect: const BeamEffect.rotate(count: 3)) + .staticFrame(); + expect(three.travellers, hasLength(3)); + expect(three.travellers.first, three.travelProgress); + }); + + test('travels the way the beam does: partway through the first sweep', () { + // Every direction, including a mirrored one, against the frame the + // running beam paints at the same point of its first cycle: the head, + // the order of the beams behind it, and which way it is facing. + for (final effect in [ + ...BeamEffect.values.where((e) => e.travels), + const BeamEffect.rotate(count: 3), + ]) { + for (final direction in BeamDirection.values) { + final r = _resolver(effect: effect, direction: direction); + final still = r.staticFrame(); + final timed = r.sample(0.35 * r.config.cycleSeconds, 1); + final reason = '${effect.name} ${direction.name}'; + expect(still.reversedNow, timed.reversedNow, reason: reason); + expect(still.travellers, hasLength(timed.travellers.length)); + for (var i = 0; i < timed.travellers.length; i++) { + expect( + still.travellers[i], + closeTo(timed.travellers[i], 1e-9), + reason: '$reason, beam $i', + ); + } + } + } + final reversed = _resolver(direction: BeamDirection.reverse) + .staticFrame(); + expect(reversed.reversedNow, isTrue); + expect(reversed.travelProgress, closeTo(0.65, 1e-12)); + }); + + test('a phase offset moves the ambient clock, as it does when running', () { + for (final effect in BeamEffect.values) { + final plain = _resolver(effect: effect); + final shifted = _resolver(effect: effect, phaseOffset: 0.5); + for (final progress in [null, 0.4]) { + expect( + shifted.staticFrame(progress: progress).cycles - + plain.staticFrame(progress: progress).cycles, + closeTo(0.5, 1e-12), + reason: '${effect.name}, progress $progress', + ); + } + // The sweep stays where the frame is lit. + expect( + shifted.staticFrame().travelProgress, + plain.staticFrame().travelProgress, + reason: effect.name, + ); + } + }); + + test('honours a driven progress, clamped', () { + final r = _resolver(); + final frame = r.staticFrame(progress: 0.25); + expect(frame.travelProgress, 0.25); + expect(frame.driven, isTrue); + expect(r.staticFrame(progress: 1.4).travelProgress, 1); + expect(r.staticFrame(progress: -1).travelProgress, 0); + }); + + test('an ambient effect has no travel, driven or not', () { + for (final effect in ambient) { + final frame = _resolver(effect: effect).staticFrame(progress: 0.6); + expect(frame.travelProgress, 0, reason: effect.name); + expect(frame.travellers, [0]); + expect(frame.driven, isFalse); + } }); }); } diff --git a/test/animation/beam_travel_test.dart b/test/animation/beam_travel_test.dart index 0ce24c2..f95ee4f 100644 --- a/test/animation/beam_travel_test.dart +++ b/test/animation/beam_travel_test.dart @@ -1,393 +1,407 @@ -import 'dart:math' as math; -import 'dart:ui'; +import 'dart:ui' show Brightness; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_border_beam/src/animation/beam_phases.dart'; import 'package:flutter_border_beam/src/models/beam_config.dart'; import 'package:flutter_test/flutter_test.dart'; -/// The travel half of the phase resolver: which way the beam runs, where its -/// timeline starts, how many beams share the contour, which shape the hue -/// track takes, and when the repeat budget is spent. -/// -/// Every one of these is a pure function of elapsed time, so they are tested -/// against the resolver directly rather than through a mounted widget. -void main() { - const cycle = Duration(milliseconds: 1960); - const cycleSeconds = 1.96; - - BeamPhaseResolver resolverFor({ - BeamVariant variant = BeamVariant.rotate, - BeamDirection? direction, - double? phaseOffset, - int? beamCount, - Duration? cycleGap, - BeamHueMode? hueMode, - double? hueRange, - BeamEdge? edge, - }) => BeamPhaseResolver( - BeamConfig.resolve( - variant: variant, - palette: BeamColors.colorful.resolve(), - brightness: Brightness.dark, - style: BeamStyle(hueMode: hueMode, hueRange: hueRange), - shape: BeamShape(edge: edge), - timing: BeamTiming( - cycle: cycle, - cycleGap: cycleGap, - direction: direction, - phaseOffset: phaseOffset, - beamCount: beamCount, - ), +const Duration _cycle = Duration(seconds: 2); +const double _cycleSeconds = 2; + +BeamPhaseResolver _resolver({ + BeamEffect effect = const BeamEffect.rotate(), + BeamDirection? direction, + double? phaseOffset, + Duration? cycleGap = Duration.zero, +}) => BeamPhaseResolver( + BeamConfig.resolve( + effect: effect, + palette: BeamColors.colorful.resolve(), + brightness: Brightness.dark, + timing: BeamTiming( + cycle: _cycle, + cycleGap: cycleGap, + direction: direction, + phaseOffset: phaseOffset, ), - ); + ), +); - group('direction', () { - test('forward runs the sweep from 0 to 1 across the cycle', () { - final resolver = resolverFor(); - expect(resolver.sample(0, 1).travelProgress, closeTo(0, 1e-9)); - expect( - resolver.sample(cycleSeconds * 0.25, 1).travelProgress, - closeTo(0.25, 1e-9), - ); - expect( - resolver.sample(cycleSeconds * 0.25, 1).angleRadians, - closeTo(math.pi / 2, 1e-9), - ); - expect(resolver.sample(cycleSeconds * 0.25, 1).reversedNow, isFalse); +/// Distance between two sweep positions around the ring. +double _ringDistance(double a, double b) => ((a - b + 0.5) % 1 - 0.5).abs(); + +/// The travel half of the phase resolver: where a travelling effect's sweep +/// sits, which way it runs, how it rests between sweeps, and how a driven +/// progress takes it over. All of it is a pure function of elapsed time, so +/// it is tested against the resolver directly. +void main() { + final travelling = BeamEffect.values.where((e) => e.travels).toList(); + final ambient = BeamEffect.values.where((e) => !e.travels).toList(); + + group('forward travel', () { + for (final effect in travelling) { + test('${effect.name}: runs 0 → 1 once per cycle', () { + final r = _resolver(effect: effect); + for (final (t, expected) in [ + (0.0, 0.0), + (0.5, 0.25), + (1.0, 0.5), + (1.5, 0.75), + (2.5, 0.25), + (9.0, 0.5), + ]) { + final phases = r.sample(t, 1); + expect( + phases.travelProgress, + closeTo(expected, 1e-9), + reason: 't=$t', + ); + expect(phases.travellers, [phases.travelProgress]); + expect(phases.reversedNow, isFalse); + expect(phases.driven, isFalse); + expect(phases.fadeOpacity, 1, reason: 'no gap, no envelope'); + } + }); + } + + test('the fade passes straight through without a gap', () { + final r = _resolver(); + for (final fade in [0.0, 0.3, 1.0]) { + expect(r.sample(0.7, fade).fadeOpacity, fade); + } }); + }); - test('reverse mirrors every traveller and flags the frame', () { - final forward = resolverFor(); - final reverse = resolverFor(direction: BeamDirection.reverse); - for (final t in [0.0, 0.4, 1.1, cycleSeconds * 0.75, 5.3]) { + group('direction', () { + for (final effect in travelling) { + test('${effect.name}: reverse mirrors the forward sweep and flags the ' + 'frame', () { + final forward = _resolver(effect: effect); + final reverse = _resolver( + effect: effect, + direction: BeamDirection.reverse, + ); + for (final t in [0.1, 0.4, 1.1, 1.5, 5.3]) { + expect( + reverse.sample(t, 1).travelProgress, + closeTo(1 - forward.sample(t, 1).travelProgress, 1e-9), + reason: 't=$t', + ); + expect(reverse.sample(t, 1).reversedNow, isTrue); + } + }); + } + + test('bounce alternates per cycle, starting forward', () { + final r = _resolver(direction: BeamDirection.bounce); + for (final (cycle, reversed) in [(0, false), (1, true), (2, false)]) { + final phases = r.sample((cycle + 0.25) * _cycleSeconds, 1); + expect(phases.reversedNow, reversed, reason: 'cycle $cycle'); expect( - reverse.sample(t, 1).travelProgress, - closeTo(1 - forward.sample(t, 1).travelProgress, 1e-9), - reason: 'the mirror of the forward sweep at ${t}s', + phases.travelProgress, + closeTo(reversed ? 0.75 : 0.25, 1e-9), + reason: 'cycle $cycle', ); } - expect(reverse.sample(1.3, 1).reversedNow, isTrue); - }); - - test('reverse runs the angle counter-clockwise', () { - final resolver = resolverFor(direction: BeamDirection.reverse); - final early = resolver.sample(cycleSeconds * 0.1, 1).angleRadians; - final later = resolver.sample(cycleSeconds * 0.2, 1).angleRadians; - expect(later, lessThan(early)); }); - test('bounce alternates per cycle, starting forward', () { - final resolver = resolverFor(direction: BeamDirection.bounce); - // Quarter of the way into cycles 0, 1, and 2. - expect( - resolver.sample(cycleSeconds * 0.25, 1).travelProgress, - closeTo(0.25, 1e-9), - ); - expect(resolver.sample(cycleSeconds * 0.25, 1).reversedNow, isFalse); + test('bounce turns around where the last sweep ended', () { + final r = _resolver(direction: BeamDirection.bounce); + const eps = 1e-6; expect( - resolver.sample(cycleSeconds * 1.25, 1).travelProgress, - closeTo(0.75, 1e-9), - ); - expect(resolver.sample(cycleSeconds * 1.25, 1).reversedNow, isTrue); - expect( - resolver.sample(cycleSeconds * 2.25, 1).travelProgress, - closeTo(0.25, 1e-9), + r.sample(_cycleSeconds - eps, 1).travelProgress, + closeTo(r.sample(_cycleSeconds + eps, 1).travelProgress, 1e-5), ); - expect(resolver.sample(cycleSeconds * 2.25, 1).reversedNow, isFalse); }); - test('bounce counts cycles including the gap', () { - final resolver = resolverFor( + test('bounce counts the gap as part of the cycle', () { + final r = _resolver( direction: BeamDirection.bounce, cycleGap: const Duration(seconds: 1), ); - // The sweep ends at 1.96s but the cycle only does at 2.96s, so the - // rest between them still belongs to the forward cycle. - expect(resolver.sample(2.5, 1).reversedNow, isFalse); - expect( - resolver.sample(2.96 + cycleSeconds * 0.25, 1).reversedNow, - isTrue, - ); - expect( - resolver.sample(2 * 2.96 + cycleSeconds * 0.25, 1).reversedNow, - isFalse, - ); + // The sweep ends at 2s but the cycle only at 3s: the rest still + // belongs to the forward cycle. + expect(r.sample(2.5, 1).reversedNow, isFalse); + expect(r.sample(3.5, 1).reversedNow, isTrue); + expect(r.sample(6.5, 1).reversedNow, isFalse); }); - test('reverse parks at the mirrored end through a cycle gap', () { - final resolver = resolverFor( - direction: BeamDirection.reverse, - cycleGap: const Duration(seconds: 1), - ); - final resting = resolver.sample(cycleSeconds + 0.5, 1); - expect(resting.travelProgress, closeTo(0, 1e-9)); - expect(resting.fadeOpacity, 0, reason: 'the gap still rests the beam'); + test('ambient effects report reverse but ignore bounce', () { + for (final effect in ambient) { + expect( + _resolver( + effect: effect, + direction: BeamDirection.reverse, + ).sample(1, 1).reversedNow, + isTrue, + reason: effect.name, + ); + expect( + _resolver( + effect: effect, + direction: BeamDirection.bounce, + ).sample(_cycleSeconds * 1.5, 1).reversedNow, + isFalse, + reason: effect.name, + ); + } }); + }); - test('the line variant reverses its travel table', () { - final forward = resolverFor(variant: BeamVariant.line); - final reverse = resolverFor( - variant: BeamVariant.line, - direction: BeamDirection.reverse, - ); - final at = cycleSeconds * 0.3; - expect( - reverse.sample(at, 1).lineX, - closeTo(forward.sample(cycleSeconds * 0.7, 1).lineX, 1e-9), - ); + group('cycle gap', () { + const gap = Duration(seconds: 1); + + test('the sweep runs over the cycle, then parks at its end', () { + final r = _resolver(cycleGap: gap); + expect(r.sample(1, 1).travelProgress, closeTo(0.5, 1e-9)); + for (final t in [2.0, 2.1, 2.5, 2.9]) { + expect(r.sample(t, 1).travelProgress, 1, reason: 't=$t'); + } + // The next sweep starts one cycle + gap later. + expect(r.sample(3, 1).travelProgress, closeTo(0, 1e-9)); + expect(r.sample(4, 1).travelProgress, closeTo(0.5, 1e-9)); + }); + + test('reverse parks at the mirrored end', () { + final r = _resolver(cycleGap: gap, direction: BeamDirection.reverse); + expect(r.sample(2.5, 1).travelProgress, closeTo(0, 1e-9)); + expect(r.sample(2.5, 1).fadeOpacity, 0); + }); + + test('the envelope eases out, rests at 0, and eases back in', () { + final r = _resolver(cycleGap: gap); + double envelope(double t) => r.sample(t, 1).fadeOpacity; + + expect(envelope(1.9), 1, reason: 'full strength while sweeping'); + expect(envelope(2.5), 0, reason: 'dark mid-gap'); + // Eases out across the start of the gap, monotonically. + var last = 1.0; + for (var t = 2.0; t <= 2.5; t += 0.02) { + final e = envelope(t); + expect(e, inInclusiveRange(0, 1)); + expect(e, lessThanOrEqualTo(last + 1e-12), reason: 't=$t'); + last = e; + } + // And back in across its end. + last = 0; + for (var t = 2.5; t < 3.0; t += 0.02) { + final e = envelope(t); + expect(e, greaterThanOrEqualTo(last - 1e-12), reason: 't=$t'); + last = e; + } + expect(envelope(2.02), inExclusiveRange(0, 1)); + expect(envelope(2.98), inExclusiveRange(0, 1)); + expect(envelope(2.999), closeTo(1, 1e-3), reason: 'continuous at wrap'); + expect(envelope(3.0), 1); + // The fade back in mirrors the fade out. + for (final x in [0.05, 0.1, 0.2]) { + expect(envelope(2 + x), closeTo(envelope(3 - x), 1e-9), reason: '$x'); + } + }); + + test('a short gap still goes dark in the middle', () { + final r = _resolver(cycleGap: const Duration(milliseconds: 100)); + expect(r.sample(2.05, 1).fadeOpacity, closeTo(0, 1e-9)); + // The next sweep begins once the 100ms rest is over. + expect(r.sample(2.2, 1).travelProgress, closeTo(0.05, 1e-9)); + }); + + test('the envelope multiplies the fade it is given', () { + final r = _resolver(cycleGap: gap); + final full = r.sample(2.1, 1).fadeOpacity; + expect(r.sample(2.1, 0.5).fadeOpacity, closeTo(full * 0.5, 1e-12)); + }); + + test('ambient effects never rest', () { + for (final effect in ambient) { + final r = _resolver(effect: effect, cycleGap: gap); + for (final t in [0.5, 2.5, 2.9, 7.4]) { + final phases = r.sample(t, 0.8); + expect(phases.fadeOpacity, 0.8, reason: '${effect.name} t=$t'); + expect(phases.travelProgress, 0); + expect(phases.travellers, [0]); + expect( + phases.cycles, + closeTo(t / r.config.cycleSeconds, 1e-9), + reason: '${effect.name}: no pause at t=$t', + ); + } + } }); }); group('phaseOffset', () { - test('starts the timeline that fraction of a cycle in', () { - final resolver = resolverFor(phaseOffset: 0.25); - expect(resolver.sample(0, 1).travelProgress, closeTo(0.25, 1e-9)); - expect( - resolver.sample(cycleSeconds * 0.5, 1).travelProgress, - closeTo(0.75, 1e-9), - ); + test('starts the sweep that fraction of a cycle in', () { + final r = _resolver(phaseOffset: 0.25); + expect(r.sample(0, 1).travelProgress, closeTo(0.25, 1e-9)); + expect(r.sample(1, 1).travelProgress, closeTo(0.75, 1e-9)); }); - test('leaves the hue track where it was', () { - final plain = resolverFor(); - final shifted = resolverFor(phaseOffset: 0.5); - expect( - shifted.sample(1.3, 1).hueDegrees, - closeTo(plain.sample(1.3, 1).hueDegrees, 1e-9), - ); + test('a reversed sweep starts the same fraction into its cycle', () { + final r = _resolver(phaseOffset: 0.25, direction: BeamDirection.reverse); + expect(r.sample(0, 1).travelProgress, closeTo(0.75, 1e-9)); }); test('a whole-cycle offset is the identity', () { - final plain = resolverFor(); - final shifted = resolverFor(phaseOffset: 1); + final plain = _resolver(); + final shifted = _resolver(phaseOffset: 1); + for (final t in [0.3, 0.7, 1.9]) { + expect( + shifted.sample(t, 1).travelProgress, + closeTo(plain.sample(t, 1).travelProgress, 1e-9), + ); + } + }); + + test('leaves the hue alone', () { + final plain = _resolver(); + final shifted = _resolver(phaseOffset: 0.5); expect( - shifted.sample(0.7, 1).travelProgress, - closeTo(plain.sample(0.7, 1).travelProgress, 1e-9), + shifted.sample(1.3, 1).hueDegrees, + plain.sample(1.3, 1).hueDegrees, ); }); }); - group('beamCount', () { - test('one beam is a single-entry list holding the head', () { - final phases = resolverFor().sample(0.5, 1); - expect(phases.travellers, hasLength(1)); - expect(phases.travellers.single, phases.travelProgress); - }); + group('rotate count', () { + BeamPhaseResolver counted(int n, {BeamDirection? direction}) => _resolver( + effect: BeamEffect.rotate(count: n), + direction: direction, + ); - test('spaces the beams evenly and keeps the head first', () { - final phases = resolverFor(beamCount: 3).sample(cycleSeconds * 0.1, 1); + test('spaces the beams evenly, head first', () { + final phases = counted(3).sample(0.2, 1); expect(phases.travellers, hasLength(3)); - expect(phases.travellers.first, closeTo(0.1, 1e-9)); + expect(phases.travelProgress, phases.travellers.first); + expect(phases.travellers[0], closeTo(0.1, 1e-9)); expect(phases.travellers[1], closeTo(0.1 + 1 / 3, 1e-9)); expect(phases.travellers[2], closeTo(0.1 + 2 / 3, 1e-9)); - expect(phases.travelProgress, phases.travellers.first); }); - test('wraps the trailing beams into 0–1', () { - final phases = resolverFor(beamCount: 4).sample(cycleSeconds * 0.9, 1); - expect(phases.travellers, hasLength(4)); + test('wraps trailing beams into [0, 1)', () { + final phases = counted(4).sample(0.9 * _cycleSeconds, 1); for (final p in phases.travellers) { expect(p, inInclusiveRange(0, 1)); + expect(p, lessThan(1)); } expect(phases.travellers[1], closeTo(0.15, 1e-9)); }); - test('reverse spaces the beams the other way round', () { - final phases = resolverFor( - beamCount: 2, - direction: BeamDirection.reverse, - ).sample(cycleSeconds * 0.1, 1); - expect(phases.travellers.first, closeTo(0.9, 1e-9)); - expect(phases.travellers[1], closeTo(0.4, 1e-9)); + test('count 1 is a single beam', () { + expect(counted(1).sample(0.3, 1).travellers, hasLength(1)); }); - test('the spacing holds all the way round the cycle', () { - final resolver = resolverFor(beamCount: 5); - for (final t in [0.0, 0.3, 1.1, 1.9, 4.4]) { - final travellers = resolver.sample(t, 1).travellers; - for (var i = 1; i < travellers.length; i++) { - final gap = (travellers[i] - travellers[i - 1]) % 1.0; - expect(gap, closeTo(0.2, 1e-9), reason: 'beams $i and ${i - 1}'); + test('the spacing holds all the way round', () { + for (var n = 2; n <= 4; n++) { + final r = counted(n); + for (final t in [0.0, 0.3, 1.1, 1.9, 4.4]) { + final travellers = r.sample(t, 1).travellers; + for (var i = 1; i < n; i++) { + expect( + (travellers[i] - travellers[i - 1]) % 1, + closeTo(1 / n, 1e-9), + reason: 'n=$n t=$t beam $i', + ); + } } } }); - }); - - group('hueMode', () { - test('the traveling variants ping-pong by default', () { - final resolver = resolverFor(hueRange: 30); - // 12s period: a quarter in is the middle of the upward swing. - expect(resolver.sample(0, 1).hueDegrees, closeTo(-30, 1e-9)); - expect(resolver.sample(6, 1).hueDegrees, closeTo(30, 1e-9)); - expect(resolver.sample(12, 1).hueDegrees, closeTo(-30, 1e-9)); - }); - test('the pulse variants revolve by default', () { - final resolver = resolverFor(variant: BeamVariant.pulseInside); - // 16s period for pulse-inside. - expect(resolver.sample(0, 1).hueDegrees, closeTo(0, 1e-9)); - expect(resolver.sample(8, 1).hueDegrees, closeTo(180, 1e-9)); - expect(resolver.sample(16, 1).hueDegrees, closeTo(0, 1e-9)); - }); - - for (final variant in BeamVariant.values) { - test('$variant: continuous revolves through 360°', () { - final resolver = resolverFor( - variant: variant, - hueMode: BeamHueMode.continuous, - ); - final period = resolver.config.huePeriodSeconds; - expect(resolver.sample(0, 1).hueDegrees, closeTo(0, 1e-9)); - expect(resolver.sample(period / 4, 1).hueDegrees, closeTo(90, 1e-9)); - expect(resolver.sample(period * 0.999, 1).hueDegrees, greaterThan(359)); - }); - - test('$variant: pingPong stays inside ±hueRange', () { - final resolver = resolverFor( - variant: variant, - hueMode: BeamHueMode.pingPong, - hueRange: 20, + test('reverse spreads the beams the other way round', () { + final phases = counted( + 2, + direction: BeamDirection.reverse, + ).sample(0.2, 1); + expect(phases.travellers.first, closeTo(0.9, 1e-9)); + expect(phases.travellers[1], closeTo(0.4, 1e-9)); + final three = counted(3, direction: BeamDirection.reverse).sample(0.2, 1); + for (var i = 1; i < 3; i++) { + expect( + (three.travellers[i - 1] - three.travellers[i]) % 1, + closeTo(1 / 3, 1e-9), ); - final range = resolver.config.hueRange; - for (var i = 0; i <= 40; i++) { - final hue = resolver.sample(i * 0.7, 1).hueDegrees; - expect(hue, inInclusiveRange(-range - 1e-9, range + 1e-9)); - } - }); - } - - test('static colors beat both modes', () { - final resolver = BeamPhaseResolver( - BeamConfig.resolve( - variant: BeamVariant.rotate, - palette: BeamColors.colorful.resolve(), - brightness: Brightness.dark, - style: const BeamStyle( - staticColors: true, - hueMode: BeamHueMode.continuous, - ), - ), - ); - expect(resolver.sample(5, 1).hueDegrees, 0); - }); - }); - - group('repeat budget', () { - test('no budget never finishes', () { - final resolver = resolverFor(); - expect(resolver.finishedAt(1000), isFalse); - expect(resolver.sample(1000, 1).finished, isFalse); - }); - - test('one cycle finishes at the cycle boundary', () { - final resolver = resolverFor()..repeatCycles = 1; - expect(resolver.finishedAt(cycleSeconds - 0.001), isFalse); - expect(resolver.finishedAt(cycleSeconds + 0.001), isTrue); - expect(resolver.sample(cycleSeconds + 0.001, 1).finished, isTrue); - }); - - test('a count finishes after that many cycles', () { - final resolver = resolverFor()..repeatCycles = 3; - expect(resolver.finishedAt(3 * cycleSeconds - 0.001), isFalse); - expect(resolver.finishedAt(3 * cycleSeconds + 0.001), isTrue); - }); - - test('the gap counts toward a cycle', () { - final resolver = resolverFor(cycleGap: const Duration(seconds: 1)) - ..repeatCycles = 1; - expect(resolver.finishedAt(cycleSeconds + 0.5), isFalse); - expect(resolver.finishedAt(cycleSeconds + 1.1), isTrue); - }); - - test('a phase offset moves the finish with the timeline', () { - final resolver = resolverFor(phaseOffset: 0.5)..repeatCycles = 1; - expect(resolver.finishedAt(cycleSeconds * 0.4), isFalse); - expect(resolver.finishedAt(cycleSeconds * 0.6), isTrue); + } }); - test('pulse repeat ignores a configured cycle gap', () { - final resolver = resolverFor( - variant: BeamVariant.pulseInside, - cycleGap: const Duration(seconds: 1), - )..repeatCycles = 2; - final period = resolver.config.cycleSeconds; - expect(resolver.sample(2 * period - 0.01, 1).finished, isFalse); - expect(resolver.sample(2 * period + 0.01, 1).finished, isTrue); + test('other effects carry a single traveller', () { + for (final effect in BeamEffect.values) { + if (effect is RotateEffect) continue; + expect( + _resolver(effect: effect).sample(0.7, 1).travellers, + hasLength(1), + reason: effect.name, + ); + } }); }); group('driven progress', () { - test('replaces the sweep with the given value', () { - final resolver = resolverFor(); - final phases = resolver.sample(0.9, 1, progress: 0.25); - expect(phases.travelProgress, closeTo(0.25, 1e-9)); - expect(phases.angleRadians, closeTo(math.pi / 2, 1e-9)); - }); - - test('the same value paints the same frame at any time', () { - final resolver = resolverFor(); - expect( - resolver.sample(0.3, 1, progress: 0.6).angleRadians, - closeTo(resolver.sample(7.4, 1, progress: 0.6).angleRadians, 1e-9), - ); - }); - - test('clamps out-of-range values', () { - final resolver = resolverFor(); - expect(resolver.sample(0, 1, progress: 1.4).travelProgress, 1); - expect(resolver.sample(0, 1, progress: -0.3).travelProgress, 0); + test('replaces the sweep with the clamped value', () { + final r = _resolver(); + for (final (p, expected) in [ + (0.25, 0.25), + (0.0, 0.0), + (1.0, 1.0), + (1.4, 1.0), + (-0.3, 0.0), + ]) { + final phases = r.sample(0.9, 1, progress: p); + expect(phases.travelProgress, expected, reason: 'progress $p'); + expect(phases.driven, isTrue); + } }); - test('ignores the cycle gap — a readout never rests', () { - final resolver = resolverFor(cycleGap: const Duration(seconds: 1)); - final resting = resolver.sample(cycleSeconds + 0.5, 1, progress: 0.4); - expect(resting.fadeOpacity, 1); - expect(resting.travelProgress, closeTo(0.4, 1e-9)); + test('holds at any time, through a gap, at full envelope', () { + final r = _resolver(cycleGap: const Duration(seconds: 1)); + for (final t in [0.3, 2.5, 7.4]) { + final phases = r.sample(t, 0.6, progress: 0.4); + expect(phases.travelProgress, closeTo(0.4, 1e-12), reason: 't=$t'); + expect(phases.fadeOpacity, 0.6, reason: 'a readout never rests'); + } }); - test('keeps the hue and the line texture tracks running', () { - final resolver = resolverFor(variant: BeamVariant.line); - final early = resolver.sample(0.4, 1, progress: 0.5); - final late = resolver.sample(3.4, 1, progress: 0.5); - expect(early.hueDegrees, isNot(closeTo(late.hueDegrees, 1e-6))); - expect(early.lineH, isNot(closeTo(late.lineH, 1e-6))); - expect(early.lineX, closeTo(late.lineX, 1e-9)); + test('keeps the hue and the ambient clock running', () { + final r = _resolver(); + final early = r.sample(0.4, 1, progress: 0.5); + final late = r.sample(3.4, 1, progress: 0.5); + expect(early.hueDegrees, isNot(late.hueDegrees)); + expect(late.cycles - early.cycles, closeTo(1.5, 1e-9)); }); - test('spreads multiple beams around the driven position', () { - final phases = resolverFor(beamCount: 2).sample(0, 1, progress: 0.25); + test('spreads several beams around the driven position', () { + final phases = _resolver(effect: const BeamEffect.rotate(count: 2)) + .sample(0, 1, progress: 0.25); expect(phases.travellers, hasLength(2)); - expect(phases.travellers[1], closeTo(0.75, 1e-9)); + expect(phases.travellers[1], closeTo(0.75, 1e-12)); }); - test('the static frame honors it', () { - final resolver = resolverFor(); - expect( - resolver.staticFrame(progress: 0.25).angleRadians, - closeTo(math.pi / 2, 1e-9), - ); - expect(resolver.staticFrame().angleRadians, closeTo(math.pi, 1e-9)); + test('ambient effects ignore it', () { + for (final effect in ambient) { + final phases = _resolver(effect: effect).sample(1, 1, progress: 0.7); + expect(phases.travelProgress, 0, reason: effect.name); + expect(phases.driven, isFalse, reason: effect.name); + } }); }); group('travelTimeOffset', () { - test('shifts the sweep without touching the hue', () { - final plain = resolverFor(); - final shifted = resolverFor()..travelTimeOffset = cycleSeconds * 0.25; + test('shifts the sweep and nothing else', () { + final plain = _resolver(); + final shifted = _resolver()..travelTimeOffset = 0.25 * _cycleSeconds; expect(shifted.sample(0, 1).travelProgress, closeTo(0.25, 1e-9)); + final a = shifted.sample(1.3, 1); + final b = plain.sample(1.3, 1); expect( - shifted.sample(1.3, 1).hueDegrees, - closeTo(plain.sample(1.3, 1).hueDegrees, 1e-9), + _ringDistance(a.travelProgress, b.travelProgress), + closeTo(0.25, 1e-9), ); + expect(a.hueDegrees, b.hueDegrees); + expect(a.cycles, b.cycles); }); test('a negative offset runs the sweep behind', () { - final resolver = resolverFor()..travelTimeOffset = -cycleSeconds * 0.25; - expect( - resolver.sample(cycleSeconds * 0.5, 1).travelProgress, - closeTo(0.25, 1e-9), - ); + final r = _resolver()..travelTimeOffset = -0.25 * _cycleSeconds; + expect(r.sample(1, 1).travelProgress, closeTo(0.25, 1e-9)); }); }); } diff --git a/test/animation/oscillator_test.dart b/test/animation/oscillator_test.dart deleted file mode 100644 index 8615aff..0000000 --- a/test/animation/oscillator_test.dart +++ /dev/null @@ -1,96 +0,0 @@ -import 'dart:ui'; - -import 'package:flutter_border_beam/src/animation/oscillator.dart'; -import 'package:flutter_border_beam/src/constants/pulse_params.dart'; -import 'package:flutter_border_beam/src/models/beam_variant.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('pingPong', () { - test('endpoints and midpoint', () { - expect(pingPong(0), closeTo(0, 1e-12)); - expect(pingPong(0.5), closeTo(1, 1e-12)); - expect(pingPong(1), closeTo(0, 1e-12)); - expect(pingPong(0.25), closeTo(0.5, 1e-12)); - }); - - test('negative phases are valid and symmetric (cosine is even)', () { - expect(pingPong(-0.25), closeTo(pingPong(0.25), 1e-12)); - expect(pingPong(-1.5), closeTo(pingPong(1.5), 1e-12)); - }); - }); - - group('PulseOscillator', () { - test('hits a at phase 0 and b at half period, honoring delay', () { - const osc = PulseOscillator(a: 2, b: 8, period: 4, delay: 1); - expect(osc.sample(1), closeTo(2, 1e-9)); - expect(osc.sample(3), closeTo(8, 1e-9)); - expect(osc.sample(5), closeTo(2, 1e-9)); - // Before the delay: negative phase, still smooth and bounded. - final early = osc.sample(0); - expect(early, inInclusiveRange(2, 8)); - }); - - test('delay desyncs otherwise identical oscillators', () { - const a = PulseOscillator(a: 0, b: 1, period: 2); - const b = PulseOscillator(a: 0, b: 1, period: 2, delay: 0.5); - expect(a.sample(1), isNot(closeTo(b.sample(1), 1e-6))); - }); - }); - - group('PulseOscillatorBank', () { - test('pulse-outside light theme has no opacity breathing (op = 0)', () { - final p = PulseParams.resolve( - BeamVariant.pulseOutside, - Brightness.light, - 2.3, - ); - expect(p.op, 0); - final bank = PulseOscillatorBank(p); - for (final t in [0.0, 0.7, 1.9, 3.4]) { - final s = bank.sample(t); - expect(s.bopTl, closeTo(1, 1e-9)); - expect(s.bopBr, closeTo(1, 1e-9)); - } - }); - - test( - 'dark pulse-inner breathes within [1-op, 1] and sizes within spec', - () { - final p = PulseParams.resolve( - BeamVariant.pulseInside, - Brightness.dark, - 2.3, - ); - final bank = PulseOscillatorBank(p); - for (var t = 0.0; t < 20; t += 0.37) { - final s = bank.sample(t); - expect(s.bopTl, inInclusiveRange(1 - p.op - 1e-9, 1 + 1e-9)); - // bw1 oscillates between 1-sp and 1+sp*1.1. - expect( - s.bw[0], - inInclusiveRange(1 - p.sp - 1e-9, 1 + p.sp * 1.1 + 1e-9), - ); - expect(s.bx[0], inInclusiveRange(-p.dr - 1e-9, p.dr * 0.9 + 1e-9)); - } - }, - ); - - test('durScale stretches periods with cycle duration', () { - final base = PulseParams.resolve( - BeamVariant.pulseInside, - Brightness.dark, - 2.3, - ); - final slow = PulseParams.resolve( - BeamVariant.pulseInside, - Brightness.dark, - 4.6, - ); - expect(slow.bs, closeTo(base.bs * 2, 1e-9)); - expect(slow.ss, closeTo(base.ss * 2, 1e-9)); - // Hue period does NOT scale with duration (fixed 16s/14s). - expect(slow.huePeriod, base.huePeriod); - }); - }); -} diff --git a/test/animation/phase_property_test.dart b/test/animation/phase_property_test.dart index 5c6fd17..7c5347e 100644 --- a/test/animation/phase_property_test.dart +++ b/test/animation/phase_property_test.dart @@ -1,225 +1,220 @@ import 'dart:math' as math; -import 'dart:ui' as ui; +import 'dart:ui' show Brightness; +import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/constants/pulse_params.dart'; -import 'package:flutter_border_beam/src/models/beam_colors.dart'; import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/models/beam_variant.dart'; import 'package:flutter_test/flutter_test.dart'; /// Property tests over [BeamPhaseResolver.sample]. /// /// Every animated value in this package is a pure function of elapsed time, /// which is what lets the painter re-derive a frame from the clock alone. -/// These tests assert that purity, the periodicity the cycle duration -/// promises, and the range each phase field is allowed to occupy — over a -/// seeded random sweep rather than a handful of hand-picked instants. +/// These tests assert that purity, the periodicity the cycle promises, and +/// the range every phase field may occupy — over a seeded random sweep of +/// times across every effect and every timing option that shapes the +/// travel, rather than a handful of hand-picked instants. void main() { - const sampleCount = 500; - - BeamConfig configFor(BeamVariant variant, {ui.Brightness? brightness}) => - BeamConfig.resolve( - variant: variant, - palette: BeamColors.colorful.resolve(), - brightness: brightness ?? ui.Brightness.dark, - ); - - void expectPhasesEqual( - BeamFramePhases a, - BeamFramePhases b, { - required String at, - }) { + const samplesPerConfig = 60; + + // Every effect, with rotate fanned out over its beam counts. + final effects = [ + for (final e in BeamEffect.values) + if (e is RotateEffect) + for (var n = 1; n <= 4; n++) BeamEffect.rotate(count: n) + else + e, + ]; + + /// Every timing/style combination exercised for one effect. + List configsFor(BeamEffect effect) => [ + for (final direction in BeamDirection.values) + for (final gap in const [Duration.zero, Duration(milliseconds: 700)]) + for (final phaseOffset in const [0.0, 0.37]) + for (final hueMode in BeamHueMode.values) + BeamConfig.resolve( + effect: effect, + palette: BeamColors.colorful.resolve(), + brightness: Brightness.dark, + style: BeamStyle(hueMode: hueMode, hueShift: 24), + timing: BeamTiming( + cycle: const Duration(milliseconds: 1700), + cycleGap: gap, + direction: direction, + phaseOffset: phaseOffset, + huePeriod: const Duration(milliseconds: 5300), + ), + ), + ]; + + String describe(BeamConfig c) => + '${c.effect} ${c.direction.name} gap=${c.gapSeconds} ' + 'offset=${c.phaseOffset} hue=${c.hueMode.name}'; + + void expectIdentical(BeamFramePhases a, BeamFramePhases b, String at) { expect(a.fadeOpacity, b.fadeOpacity, reason: 'fadeOpacity $at'); expect(a.hueDegrees, b.hueDegrees, reason: 'hueDegrees $at'); - expect(a.bloomHueDegrees, b.bloomHueDegrees, reason: 'bloomHue $at'); - expect(a.angleRadians, b.angleRadians, reason: 'angleRadians $at'); - expect(a.lineX, b.lineX, reason: 'lineX $at'); - expect(a.lineW, b.lineW, reason: 'lineW $at'); - expect(a.lineH, b.lineH, reason: 'lineH $at'); - expect(a.spike, b.spike, reason: 'spike $at'); - expect(a.spike2, b.spike2, reason: 'spike2 $at'); - expect(a.edge, b.edge, reason: 'edge $at'); - expect(a.pulse.bw, b.pulse.bw, reason: 'pulse.bw $at'); - expect(a.pulse.bh, b.pulse.bh, reason: 'pulse.bh $at'); - expect(a.pulse.bx, b.pulse.bx, reason: 'pulse.bx $at'); - expect(a.pulse.by, b.pulse.by, reason: 'pulse.by $at'); - expect(a.pulse.bgh, b.pulse.bgh, reason: 'pulse.bgh $at'); - expect(a.pulse.bopTl, b.pulse.bopTl, reason: 'pulse.bopTl $at'); - expect(a.pulse.bopTr, b.pulse.bopTr, reason: 'pulse.bopTr $at'); - expect(a.pulse.bopBl, b.pulse.bopBl, reason: 'pulse.bopBl $at'); - expect(a.pulse.bopBr, b.pulse.bopBr, reason: 'pulse.bopBr $at'); + expect(a.travelProgress, b.travelProgress, reason: 'travel $at'); + expect(a.travellers, b.travellers, reason: 'travellers $at'); + expect(a.reversedNow, b.reversedNow, reason: 'reversedNow $at'); + expect(a.finished, b.finished, reason: 'finished $at'); + expect(a.cycles, b.cycles, reason: 'cycles $at'); + expect(a.driven, b.driven, reason: 'driven $at'); } - group('purity', () { - for (final variant in BeamVariant.values) { - test('$variant: the same t yields the same frame', () { - final config = configFor(variant); - final resolver = BeamPhaseResolver(config); - // A second resolver over the same config must agree too: the - // oscillator bank carries no per-frame state. - final twin = BeamPhaseResolver(config); - final random = math.Random(0x5EED); - for (var i = 0; i < sampleCount; i++) { - final t = random.nextDouble() * 1000; - final fade = random.nextDouble(); - expectPhasesEqual( - resolver.sample(t, fade), - resolver.sample(t, fade), - at: 'at t=$t', - ); - expectPhasesEqual( - resolver.sample(t, fade), - twin.sample(t, fade), - at: 'across resolvers at t=$t', - ); - } - }); + /// Distance between two sweep positions around the ring. + double ringDistance(double a, double b) => ((a - b + 0.5) % 1 - 0.5).abs(); - test('$variant: fadeOpacity passes straight through', () { - final resolver = BeamPhaseResolver(configFor(variant)); - final random = math.Random(0xFADE); - for (var i = 0; i < sampleCount; i++) { - final fade = random.nextDouble(); - expect( - resolver.sample(random.nextDouble() * 1000, fade).fadeOpacity, - fade, - ); - } - }); - } - }); - - group('cycle periodicity', () { - // Only the tracks driven by the cycle duration itself repeat every - // cycle. The line variant's breathe/spike tracks run at ×1.3/×1.33/×1.7 - // of it, and the hue ping-pong has its own 12s period, so neither is - // expected to line up here. - // - // Samples stay clear of the wrap (fraction 0.02–0.98) so a float - // rounding of the modulo cannot land the two reads on opposite sides of - // a keyframe seam. - ({double a, double b}) pairFor(math.Random random, double cycleSeconds) { - final fraction = 0.02 + random.nextDouble() * 0.96; - final t = fraction * cycleSeconds; - final k = 1 + random.nextInt(20); - return (a: t, b: t + k * cycleSeconds); - } - - for (final variant in [BeamVariant.rotate, BeamVariant.small]) { - test('$variant: the conic angle repeats every cycle', () { - final config = configFor(variant); - final resolver = BeamPhaseResolver(config); - final random = math.Random(0xC0FFEE); - for (var i = 0; i < sampleCount; i++) { - final (a: t, b: later) = pairFor(random, config.cycleSeconds); - expect( - resolver.sample(later, 1).angleRadians, - closeTo(resolver.sample(t, 1).angleRadians, 1e-6), - reason: 'angleRadians at t=$t vs $later', - ); - } - }); - } - - test('line: travel, width and edge fade repeat every cycle', () { - final config = configFor(BeamVariant.line); - final resolver = BeamPhaseResolver(config); - final random = math.Random(0xBEEF); - for (var i = 0; i < sampleCount; i++) { - final (a: t, b: later) = pairFor(random, config.cycleSeconds); - final first = resolver.sample(t, 1); - final second = resolver.sample(later, 1); - expect(second.lineX, closeTo(first.lineX, 1e-6), reason: 'lineX @$t'); - expect(second.lineW, closeTo(first.lineW, 1e-6), reason: 'lineW @$t'); - expect(second.edge, closeTo(first.edge, 1e-6), reason: 'edge @$t'); - } - }); - }); + for (final effect in effects) { + final configs = configsFor(effect); - group('ranges', () { - for (final variant in BeamVariant.values) { - test('$variant: the conic angle stays in [0, 2pi)', () { - final resolver = BeamPhaseResolver(configFor(variant)); - final random = math.Random(0xA11CE); - for (var i = 0; i < sampleCount; i++) { - final angle = resolver - .sample(random.nextDouble() * 5000, 1) - .angleRadians; - expect(angle, greaterThanOrEqualTo(0)); - expect(angle, lessThan(2 * math.pi)); + group('$effect', () { + test('purity: the same inputs give the same frame', () { + final random = math.Random(0x5EED); + for (final config in configs) { + final resolver = BeamPhaseResolver(config)..repeatCycles = 3; + // A second resolver over the same config must agree too: nothing + // is carried from one frame to the next. + final twin = BeamPhaseResolver(config)..repeatCycles = 3; + for (var i = 0; i < samplesPerConfig; i++) { + final t = random.nextDouble() * 1000; + final fade = random.nextDouble(); + final progress = random.nextBool() ? random.nextDouble() : null; + final first = resolver.sample(t, fade, progress: progress); + final at = '${describe(config)} t=$t'; + expectIdentical( + first, + resolver.sample(t, fade, progress: progress), + at, + ); + expectIdentical( + first, + twin.sample(t, fade, progress: progress), + at, + ); + } } }); - } - - test('line: the edge fade stays in [0, 1]', () { - final resolver = BeamPhaseResolver(configFor(BeamVariant.line)); - final random = math.Random(0xED6E); - for (var i = 0; i < sampleCount; i++) { - final edge = resolver.sample(random.nextDouble() * 5000, 1).edge; - expect(edge, inInclusiveRange(0, 1)); - } - }); - for (final variant in [BeamVariant.pulseInside, BeamVariant.pulseOutside]) { - for (final brightness in ui.Brightness.values) { - test('$variant/$brightness: breathing stays inside its params', () { - final config = configFor(variant, brightness: brightness); - final params = PulseParams.resolve( - variant, - brightness, - config.cycleSeconds, - ); + test('ranges: every field stays in bounds', () { + final random = math.Random(0xA11CE); + for (final config in configs) { final resolver = BeamPhaseResolver(config); - final random = math.Random(0xDEC0DE); - // The widest oscillator in the size bank swings to 1 + sp × 1.15. - final sizeSpan = params.sp * 1.15; - for (var i = 0; i < sampleCount; i++) { - final pulse = resolver.sample(random.nextDouble() * 5000, 1).pulse; - for (final v in pulse.bw) { - expect(v, inInclusiveRange(1 - sizeSpan, 1 + sizeSpan)); + for (var i = 0; i < samplesPerConfig; i++) { + final t = random.nextDouble() * 5000; + final fade = random.nextDouble(); + final p = resolver.sample(t, fade); + final at = '${describe(config)} t=$t'; + + expect(p.fadeOpacity.isFinite, isTrue, reason: at); + expect(p.fadeOpacity, inInclusiveRange(0, 1), reason: at); + expect(p.fadeOpacity, lessThanOrEqualTo(fade), reason: at); + if (!effect.travels) { + expect(p.fadeOpacity, fade, reason: 'ambient never rests $at'); } - for (final v in pulse.bh) { - expect(v, inInclusiveRange(1 - sizeSpan, 1 + sizeSpan)); + + expect(p.travelProgress, inInclusiveRange(0, 1), reason: at); + expect(p.travellers, hasLength(config.beamCount), reason: at); + expect(p.travellers.first, p.travelProgress, reason: at); + for (final traveller in p.travellers) { + expect(traveller.isFinite, isTrue, reason: at); + expect(traveller, inInclusiveRange(0, 1), reason: at); } - for (final v in [...pulse.bx, ...pulse.by]) { - expect(v, inInclusiveRange(-params.dr, params.dr)); + if (!effect.travels) { + expect(p.travelProgress, 0, reason: at); } - expect(pulse.bgh, inInclusiveRange(1 - params.gh, 1 + params.gh)); - for (final v in [ - pulse.bopTl, - pulse.bopTr, - pulse.bopBl, - pulse.bopBr, - ]) { - expect(v, inInclusiveRange(1 - params.op, 1)); + + expect(p.hueDegrees.isFinite, isTrue, reason: at); + switch (config.hueMode) { + case BeamHueMode.none: + expect(p.hueDegrees, 0, reason: at); + case BeamHueMode.continuous: + expect(p.hueDegrees, greaterThanOrEqualTo(0), reason: at); + expect(p.hueDegrees, lessThan(360), reason: at); + case BeamHueMode.pingPong: + expect( + p.hueDegrees, + inInclusiveRange( + -config.hueShift - 1e-9, + config.hueShift + 1e-9, + ), + reason: at, + ); } + + expect(p.cycles.isFinite, isTrue, reason: at); + expect(p.cycles, greaterThanOrEqualTo(0), reason: at); + expect(p.driven, isFalse, reason: at); } - }); - } - } - }); - - group('staticFrame', () { - for (final variant in BeamVariant.values) { - test('$variant: is deterministic', () { - final resolver = BeamPhaseResolver(configFor(variant)); - expectPhasesEqual( - resolver.staticFrame(), - resolver.staticFrame(), - at: 'in staticFrame', - ); - expect(resolver.staticFrame().fadeOpacity, 1); + } }); - test('$variant: is hue-neutral', () { - // Reduced motion paints one frame forever, so it must show the - // palette's own colors rather than an arbitrary point of the hue - // ping-pong frozen in place. - final resolver = BeamPhaseResolver(configFor(variant)); - expect(resolver.staticFrame().hueDegrees, 0); - expect(resolver.staticFrame().bloomHueDegrees, 0); + test('cycles: advances by exactly 1 per cycle', () { + final random = math.Random(0xC1C1E); + for (final config in configs) { + final resolver = BeamPhaseResolver(config); + for (var i = 0; i < samplesPerConfig; i++) { + final t = random.nextDouble() * 1000; + final k = 1 + random.nextInt(20); + expect( + resolver.sample(t + k * config.cycleSeconds, 1).cycles - + resolver.sample(t, 1).cycles, + closeTo(k, 1e-9), + reason: '${describe(config)} t=$t k=$k', + ); + } + } }); - } - }); + + if (effect.travels) { + test('periodicity: the travel repeats every cycle + gap', () { + final random = math.Random(0xC0FFEE); + for (final config in configs) { + final resolver = BeamPhaseResolver(config); + final cycle = config.cycleSeconds + config.gapSeconds; + // Bounce only repeats after a forward and a reverse cycle. + final period = config.direction == BeamDirection.bounce + ? 2 * cycle + : cycle; + final shift = config.phaseOffset * config.cycleSeconds; + for (var i = 0; i < samplesPerConfig; i++) { + // A position within the period, clear of the boundaries + // between cycles, so float rounding of the modulo cannot land + // the two reads on opposite sides of a wrap. + final whichCycle = config.direction == BeamDirection.bounce + ? random.nextInt(2) + : 0; + final local = + (whichCycle + 0.02 + random.nextDouble() * 0.96) * cycle; + final t = period + local - shift; + final later = t + (1 + random.nextInt(20)) * period; + final a = resolver.sample(t, 1); + final b = resolver.sample(later, 1); + final at = '${describe(config)} t=$t vs $later'; + + expect( + b.travelProgress, + closeTo(a.travelProgress, 1e-6), + reason: 'travelProgress $at', + ); + expect( + b.fadeOpacity, + closeTo(a.fadeOpacity, 1e-6), + reason: 'fadeOpacity $at', + ); + expect(b.reversedNow, a.reversedNow, reason: 'reversed $at'); + expect(b.travellers, hasLength(a.travellers.length)); + for (var j = 0; j < a.travellers.length; j++) { + expect( + ringDistance(a.travellers[j], b.travellers[j]), + lessThan(1e-6), + reason: 'traveller $j $at', + ); + } + } + } + }); + } + }); + } } diff --git a/test/animation/pulse_breath_test.dart b/test/animation/pulse_breath_test.dart new file mode 100644 index 0000000..7378b10 --- /dev/null +++ b/test/animation/pulse_breath_test.dart @@ -0,0 +1,227 @@ +import 'package:flutter_border_beam/src/look/pulse_look.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// The pulse's breathing: the per-frame oscillator bank its emitter samples, +/// and the breath its corners swing on — a quicker swell and a slower fade. +/// +/// These pin the shape of the motion (where it rests and peaks, which way it +/// moves, how it scales with the cycle), not its tuning, so retuning the look +/// in `lib/src/look/` leaves them standing. +void main() { + group('breath', () { + test('rests at the start of each cycle and peaks where the swell ends', () { + expect(breath(0), 0); + expect(breath(breathRise), closeTo(1, 1e-12)); + expect(breath(1), closeTo(0, 1e-12)); + }); + + test('swells quicker than it fades back', () { + expect(breathRise, greaterThan(0)); + expect(breathRise, lessThan(0.5)); + }); + + test('rises steadily to the peak, then falls steadily back', () { + const n = 2000; + var previous = breath(0); + for (var i = 1; i <= n; i++) { + final phase = i / n; + final value = breath(phase); + expect(value, inInclusiveRange(0.0, 1.0), reason: '$phase'); + if (phase <= breathRise) { + expect(value, greaterThanOrEqualTo(previous), reason: '$phase'); + } else { + expect(value, lessThanOrEqualTo(previous), reason: '$phase'); + } + previous = value; + } + }); + + test('repeats every cycle, before zero too', () { + // Shifting by whole cycles moves the phase's last bits, and the eased + // curve is solved numerically, so equal means equal to well below a + // visible step rather than bit for bit. + for (final phase in [0.1, breathRise, 0.55, 0.93]) { + for (final cycles in [-2, 1, 7]) { + expect( + breath(phase + cycles), + closeTo(breath(phase), 1e-6), + reason: '$phase + $cycles', + ); + } + } + }); + + test('eases into and out of rest and the peak, with no jump', () { + // An even swing covers h / span of its travel in a step of h; an eased + // one covers a small fraction of that next to each turning point. + const h = 1e-3; + const rise = h / breathRise; + const fall = h / (1 - breathRise); + expect(breath(h), lessThan(rise * 0.1), reason: 'leaving rest'); + expect(1 - breath(breathRise - h), lessThan(rise * 0.1), reason: 'peak'); + expect(1 - breath(breathRise + h), lessThan(fall * 0.1), reason: 'peak'); + expect(breath(1 - h), lessThan(fall * 0.1), reason: 'back to rest'); + }); + }); + + group('PulseOscillator', () { + test('an even swing reaches its far end half a period in', () { + const swing = PulseOscillator(a: 0.25, b: 1, period: 2); + expect(swing.sample(0), closeTo(0.25, 1e-12)); + expect(swing.sample(1), closeTo(1, 1e-12)); + expect(swing.sample(2), closeTo(0.25, 1e-12)); + }); + + test('a breathing swing reaches it after the swell instead', () { + const swing = PulseOscillator(a: 0.25, b: 1, period: 2, breathes: true); + expect(swing.sample(0), closeTo(0.25, 1e-12)); + expect(swing.sample(2 * breathRise), closeTo(1, 1e-12)); + expect(swing.sample(2), closeTo(0.25, 1e-12)); + // Half a period in, the even swing is at its far end; the breath is + // already on its way back. + expect(swing.sample(1), lessThan(1)); + expect(swing.sample(1), greaterThan(0.25)); + }); + + test('a delay plays the same swing later', () { + const onTime = PulseOscillator(a: 0, b: 1, period: 3, breathes: true); + const late = PulseOscillator( + a: 0, + b: 1, + period: 3, + delay: 0.5, + breathes: true, + ); + for (final t in [0.0, 0.7, 1.9, 4.2]) { + expect(late.sample(t + 0.5), closeTo(onTime.sample(t), 1e-6)); + } + }); + + test('never leaves the span between its two ends', () { + for (final breathes in [false, true]) { + // b below a: the swing runs downward. + final swing = PulseOscillator( + a: 1, + b: 0.4, + period: 1.7, + delay: 0.3, + breathes: breathes, + ); + for (var i = 0; i <= 1000; i++) { + expect( + swing.sample(i * 0.0137), + inInclusiveRange(0.4 - 1e-12, 1 + 1e-12), + reason: 'breathes: $breathes at ${i * 0.0137}', + ); + } + } + }); + }); + + group('PulseOscillatorBank', () { + const cycle = 2.3; + + PulseFrame sampleAt(PulseOscillatorBank bank, double t) { + final frame = PulseFrame(); + bank.sample(t, frame); + return frame; + } + + List flatten(PulseFrame f) => [ + ...f.bw, + ...f.bh, + ...f.bx, + ...f.by, + f.bgh, + ...f.bop, + ]; + + for (final dark in [true, false]) { + final surface = dark ? 'dark' : 'light'; + final params = PulseParams.pulse(dark: dark, cycleSeconds: cycle); + final bank = PulseOscillatorBank(params); + + test('$surface: every corner breathes between 1 − depth and full', () { + final low = List.filled(4, double.infinity); + final high = List.filled(4, double.negativeInfinity); + for (var i = 0; i <= 20000; i++) { + final frame = sampleAt(bank, i * 0.005); + for (var c = 0; c < 4; c++) { + final o = frame.bop[c]; + expect(o, inInclusiveRange(1 - params.op - 1e-9, 1 + 1e-9)); + if (o < low[c]) low[c] = o; + if (o > high[c]) high[c] = o; + } + } + for (var c = 0; c < 4; c++) { + expect(low[c], closeTo(1 - params.op, 0.01), reason: 'corner $c'); + expect(high[c], closeTo(1, 0.01), reason: 'corner $c'); + } + }); + + test('$surface: the corners breathe out of step', () { + var widest = 0.0; + for (var i = 0; i <= 2000; i++) { + final bop = sampleAt(bank, i * 0.01).bop; + final spread = + bop.reduce((a, b) => a > b ? a : b) - + bop.reduce((a, b) => a < b ? a : b); + if (spread > widest) widest = spread; + } + expect(widest, greaterThan(params.op / 2)); + }); + + test('$surface: the frozen bloom holds the corners\' average', () { + // The static bloom stands in for the breathing corners when the beam + // cannot move; it must sit at their time average, so a frozen frame + // is neither brighter nor dimmer than a moving one on the whole. + const window = 1000.0; + const step = 0.005; + final sums = List.filled(4, 0); + var n = 0; + for (var t = 0.0; t < window; t += step) { + final bop = sampleAt(bank, t).bop; + for (var c = 0; c < 4; c++) { + sums[c] += bop[c]; + } + n++; + } + for (var c = 0; c < 4; c++) { + expect( + sums[c] / n, + closeTo(params.frozenBloomAlpha, 0.005), + reason: 'corner $c', + ); + } + }); + + test('$surface: a longer cycle plays the same breathing slower', () { + final slow = PulseOscillatorBank( + PulseParams.pulse(dark: dark, cycleSeconds: cycle * 2), + ); + for (final t in [0.0, 0.37, 1.2, 3.9, 11.5]) { + final fast = flatten(sampleAt(bank, t)); + final slowed = flatten(sampleAt(slow, t * 2)); + for (var i = 0; i < fast.length; i++) { + expect(slowed[i], closeTo(fast[i], 1e-6), reason: 't=$t [$i]'); + } + } + }); + } + + test('sampling is pure: a time always gives the same frame', () { + final bank = PulseOscillatorBank( + PulseParams.pulse(dark: true, cycleSeconds: cycle), + ); + final reused = PulseFrame(); + bank.sample(5.25, reused); + final first = flatten(reused); + bank + ..sample(1, reused) + ..sample(0, reused) + ..sample(5.25, reused); + expect(flatten(reused), first); + expect(flatten(sampleAt(bank, 5.25)), first); + }); + }); +} diff --git a/test/animation/spring_curve_test.dart b/test/animation/spring_curve_test.dart index 97d3a26..6a5ef6a 100644 --- a/test/animation/spring_curve_test.dart +++ b/test/animation/spring_curve_test.dart @@ -1,94 +1,137 @@ +import 'dart:math' as math; + +import 'package:flutter_border_beam/src/animation/beam_clock.dart'; import 'package:flutter_border_beam/src/animation/spring_curve.dart'; import 'package:flutter_test/flutter_test.dart'; -/// `FadeSpringCurve.transform(i * 0.05)` for i = 0..20, at full double -/// precision. The fade envelope's shape is visual API — goldens and the -/// documented ~3% overshoot both depend on these exact values. -const List _oracle = [ - 0.0, - 0.15986030326692727, - 0.44896452311296503, - 0.7063666247249973, - 0.8815479259123428, - 0.9784616720631045, - 1.020016563364826, - 1.029814982804687, - 1.0252447161959004, - 1.016641057993826, - 1.0089117673752073, - 1.003622629972982, - 1.0006807812985246, - 0.999408629217683, - 0.9990992111048517, - 0.9992285492416089, - 0.9994836129267871, - 0.9997147812271953, - 0.9998735617828104, - 0.9999619578842425, - 1.0, -]; +/// A critically damped unit spring released from rest, at time [t] seconds +/// for a [response]: `1 − (1 + ω₀t)·e^(−ω₀t)`, ω₀ = 2π / response. +double _critical(double response, double t) { + final u = 2 * math.pi / response * t; + return 1 - (1 + u) * math.exp(-u); +} + +List _samples(BeamSpringCurve curve, [int n = 1000]) => + List.generate(n + 1, (i) => curve.transform(i / n)); void main() { - const curve = FadeSpringCurve.instance; + for (final (name, curve) in [ + ('fadeIn', BeamSpringCurve.fadeIn), + ('fadeOut', BeamSpringCurve.fadeOut), + ('pop', BeamSpringCurve.pop), + ]) { + test('$name pins both endpoints exactly', () { + expect(curve.transform(0), 0.0); + expect(curve.transform(1), 1.0); + }); - test('matches the reference samples at 0.05 increments', () { - for (var i = 0; i < _oracle.length; i++) { - final t = i * 0.05; - expect( - curve.transform(t), - closeTo(_oracle[i], 1e-9), - reason: 'sample $i (t = $t)', - ); - } - }); + test('$name starts from rest', () { + // A spring released from rest eases in quadratically: its first + // thousandth is a tiny fraction of an even pace's. + expect(curve.transform(0.001), lessThan(0.001 * 0.1)); + }); + } - test('pins both endpoints exactly', () { - expect(curve.transform(0), 0.0); - expect(curve.transform(1), 1.0); - }); + group('the fades', () { + for (final (name, curve) in [ + ('fadeIn', BeamSpringCurve.fadeIn), + ('fadeOut', BeamSpringCurve.fadeOut), + ]) { + test('$name is critically damped: monotone, never past 1', () { + final values = _samples(curve, 10000); + for (var i = 1; i < values.length; i++) { + expect(values[i], greaterThanOrEqualTo(values[i - 1]), reason: '$i'); + expect(values[i], lessThanOrEqualTo(1.0), reason: '$i'); + } + }); - test('rises monotonically to its peak, then settles', () { - const samples = 1000; - var peakIndex = 0; - var peak = 0.0; - final values = List.generate( - samples + 1, - (i) => curve.transform(i / samples), - ); - for (var i = 0; i <= samples; i++) { - if (values[i] > peak) { - peak = values[i]; - peakIndex = i; - } + test('$name plays the spring in real time over its settling time', () { + final seconds = curve.settlingSeconds; + for (final f in [0.1, 0.25, 0.5, 0.75]) { + final t = seconds * f; + // Normalised by the 1% left at the settle phase. + final expected = + _critical(curve.response, t) / _critical(curve.response, seconds); + expect(curve.transform(f), closeTo(expected, 1e-9), reason: '$f'); + } + }); } - // Under-damped: it overshoots once, near t = 0.35, by ~3%. - expect(peak, closeTo(1.0298, 1e-3)); - expect(peakIndex / samples, closeTo(0.35, 0.02)); + test('the clock runs each fade over its spring settling time', () { + expect( + BeamClock.fadeInSeconds, + closeTo(BeamSpringCurve.fadeIn.settlingSeconds, 1e-3), + ); + expect( + BeamClock.fadeOutSeconds, + closeTo(BeamSpringCurve.fadeOut.settlingSeconds, 1e-3), + ); + }); - for (var i = 1; i <= peakIndex; i++) { + test('light leaves more gently than it arrives', () { expect( - values[i], - greaterThanOrEqualTo(values[i - 1]), - reason: 'dip before the peak at sample $i', + BeamSpringCurve.fadeOut.response, + greaterThan(BeamSpringCurve.fadeIn.response), ); + expect(BeamClock.fadeOutSeconds, greaterThan(BeamClock.fadeInSeconds)); + }); + + test('a fade-out eases away instead of snapping to nothing', () { + // Opacity at each tenth of the fade-out: falling throughout, a gentle + // first step, and still above zero until the very end. + final opacity = [ + for (var i = 0; i <= 10; i++) + 1 - BeamSpringCurve.fadeOut.transform(i / 10), + ]; + expect(opacity[1], greaterThan(0.75)); + for (var i = 1; i < 10; i++) { + expect(opacity[i], lessThan(opacity[i - 1]), reason: '$i'); + expect(opacity[i], greaterThan(0), reason: '$i'); + } + expect(opacity[10], 0); + }); + }); + + test('pop overshoots a little, once, and settles', () { + final values = _samples(BeamSpringCurve.pop, 10000); + final peak = values.reduce(math.max); + final peakIndex = values.indexOf(peak); + expect(peak, greaterThan(1.01)); + expect(peak, lessThan(1.05)); + expect(peakIndex / 10000, lessThan(0.6)); + // One rise, straight up to the peak. + for (var i = 1; i <= peakIndex; i++) { + expect(values[i], greaterThanOrEqualTo(values[i - 1]), reason: '$i'); + } + // Then back down through 1... + final back = values.indexWhere((v) => v <= 1, peakIndex); + expect(back, greaterThan(peakIndex), reason: 'never came back to 1'); + for (var i = peakIndex + 1; i < back; i++) { + expect(values[i], lessThan(values[i - 1]), reason: '$i'); } - // Past the peak the spring rings down and never climbs back to it. - for (var i = peakIndex + 1; i <= samples; i++) { - expect(values[i], lessThan(peak), reason: 'second peak at sample $i'); + // ...and settled: never over 1 again, and any undershoot within the 1% + // a settled spring leaves. + for (var i = back; i < values.length; i++) { + expect(values[i], inInclusiveRange(0.99, 1 + 1e-9), reason: '$i'); } + expect(values.last, 1.0); }); - test('overshoot stays within the documented bound', () { - const samples = 100000; - var max = 0.0; - var min = 0.0; - for (var i = 0; i <= samples; i++) { - final v = curve.transform(i / samples); - if (v > max) max = v; - if (v < min) min = v; - } - expect(max, lessThan(1.03)); - expect(min, greaterThanOrEqualTo(0.0)); + test('value-equal and described', () { + final same = BeamSpringCurve( + dampingRatio: double.parse('1'), + response: double.parse('0.45'), + ); + expect(identical(same, BeamSpringCurve.fadeIn), isFalse); + expect(same, BeamSpringCurve.fadeIn); + expect(same.hashCode, BeamSpringCurve.fadeIn.hashCode); + expect( + BeamSpringCurve(dampingRatio: double.parse('1'), response: 0.55), + isNot(BeamSpringCurve.fadeIn), + ); + expect( + BeamSpringCurve.fadeIn.toString(), + 'BeamSpringCurve(dampingRatio: 1.0, response: 0.45s)', + ); }); } diff --git a/test/constants/palette_data_test.dart b/test/constants/palette_data_test.dart deleted file mode 100644 index a39ab6d..0000000 --- a/test/constants/palette_data_test.dart +++ /dev/null @@ -1,195 +0,0 @@ -import 'package:flutter/widgets.dart'; -import 'package:flutter_border_beam/src/constants/extra_palettes.dart'; -import 'package:flutter_border_beam/src/constants/palettes.dart'; -import 'package:flutter_border_beam/src/constants/pulse_tables.dart'; -import 'package:flutter_border_beam/src/constants/theme_presets.dart'; -import 'package:flutter_border_beam/src/models/beam_colors.dart'; -import 'package:flutter_border_beam/src/models/beam_variant.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - const presets = { - 'colorful': colorfulPreset, - 'mono': monoPreset, - 'ocean': oceanPreset, - 'sunset': sunsetPreset, - }; - - group('palette table shapes', () { - for (final MapEntry(key: name, value: p) in presets.entries) { - test('$name has the source table cardinalities', () { - expect(p.border, hasLength(9)); - expect(p.smallBorder, hasLength(8)); - expect(p.smallInner, hasLength(8)); - expect(p.lineDark, hasLength(9)); - expect(p.lineLight, hasLength(9)); - expect(p.lineInner, hasLength(9)); - expect(p.lineBloomDark, hasLength(5)); - expect(p.lineBloomLight, hasLength(5)); - }); - - test('$name shares the border geometry of the source', () { - // Geometry (positions/sizes) is identical across presets — only - // colors differ. Spot-check against colorful. - for (final (i, blob) in p.border.indexed) { - expect(blob.position, colorfulPreset.border[i].position); - expect(blob.size, colorfulPreset.border[i].size); - } - }); - } - - test('spot-check verbatim values from styles.ts', () { - // colorful border[0]: rgb(255,50,100) at 33% -7.4%, 70x40 - final b0 = colorfulPreset.border[0]; - expect(b0.color, const Color.fromRGBO(255, 50, 100, 1)); - expect(b0.position, const Offset(0.33, -0.074)); - expect(b0.size, const Size(70, 40)); - // ocean lineLight[8]: rgb(120,90,245) 30x30 at -110,-1 - final o8 = oceanPreset.lineLight[8]; - expect(o8.color, const Color.fromRGBO(120, 90, 245, 1)); - expect(o8.offsetX, -110); - expect(o8.offsetY, -1); - // sunset lineBloomDark[3]: rgba(255,120,50,0.91) / 0.45 - final s3 = sunsetPreset.lineBloomDark[3]; - expect(s3.color1.a, closeTo(0.91, 0.005)); - expect(s3.color2.a, closeTo(0.45, 0.005)); - }); - }); - - group('Flutter-only palette additions', () { - // These are not transcriptions: each is a short source-color list that - // `BeamColors.custom` distributes over the colorful geometry. - const sources = { - 'aurora': (BeamColors.aurora, auroraColors), - 'neon': (BeamColors.neon, neonColors), - 'candy': (BeamColors.candy, candyColors), - 'ember': (BeamColors.ember, emberColors), - 'ice': (BeamColors.ice, iceColors), - 'gold': (BeamColors.gold, goldColors), - 'holographic': (BeamColors.holographic, holographicColors), - }; - - for (final MapEntry(key: name, value: (colors, source)) - in sources.entries) { - test('$name resolves to the source table cardinalities', () { - final p = colors.resolve().data; - expect(p.border, hasLength(9)); - expect(p.smallBorder, hasLength(8)); - expect(p.smallInner, hasLength(8)); - expect(p.lineDark, hasLength(9)); - expect(p.lineLight, hasLength(9)); - expect(p.lineInner, hasLength(9)); - expect(p.lineBloomDark, hasLength(5)); - expect(p.lineBloomLight, hasLength(5)); - }); - - test('$name keeps the colorful geometry and alpha structure', () { - final p = colors.resolve().data; - for (final (i, blob) in p.border.indexed) { - expect(blob.position, colorfulPreset.border[i].position); - expect(blob.size, colorfulPreset.border[i].size); - expect(blob.color.a, closeTo(colorfulPreset.border[i].color.a, 1e-6)); - } - for (final (i, blob) in p.smallInner.indexed) { - expect( - blob.color.a, - closeTo(colorfulPreset.smallInner[i].color.a, 1e-6), - ); - } - for (final (i, pair) in p.lineBloomDark.indexed) { - expect( - pair.color1.a, - closeTo(colorfulPreset.lineBloomDark[i].color1.a, 1e-6), - ); - } - }); - - test('$name uses 3-5 source colors, cycled over the border table', () { - expect(source.length, inInclusiveRange(3, 5)); - expect(source.toSet(), hasLength(source.length), reason: 'duplicates'); - final p = colors.resolve().data; - for (final (i, blob) in p.border.indexed) { - final expected = source[i % source.length]; - expect(blob.color.r, closeTo(expected.r, 1e-6), reason: 'border $i'); - expect(blob.color.g, closeTo(expected.g, 1e-6), reason: 'border $i'); - expect(blob.color.b, closeTo(expected.b, 1e-6), reason: 'border $i'); - } - }); - } - - test('the source lists carry opaque colors', () { - for (final MapEntry(key: name, value: (_, source)) in sources.entries) { - for (final c in source) { - expect(c.a, 1.0, reason: '$name has a translucent source color'); - } - } - }); - }); - - group('pulse tables', () { - test('cardinalities and index bounds', () { - expect(pulseRingMap, hasLength(9)); - expect(pulseInnerSizes, hasLength(9)); - expect(pulseInnerBloom, hasLength(7)); - expect(pulseOuterCore, hasLength(8)); - expect(pulseOuterBloom, hasLength(7)); - for (final spec in [ - ...pulseInnerBloom, - ...pulseOuterCore, - ...pulseOuterBloom, - ]) { - expect(spec.ci, inInclusiveRange(0, 8)); - } - // Outer tables always carry explicit positions. - for (final spec in [...pulseOuterCore, ...pulseOuterBloom]) { - expect(spec.x, isNotNull); - expect(spec.y, isNotNull); - } - }); - }); - - group('theme presets', () { - test('every variant has dark and light entries', () { - for (final v in BeamVariant.values) { - expect(beamThemePresets[v], isNotNull, reason: '$v missing'); - } - }); - - test('verbatim spot checks', () { - final lineDark = themePresetFor(BeamVariant.line, Brightness.dark); - expect(lineDark.strokeOpacity, 1.14); - final poLight = themePresetFor( - BeamVariant.pulseOutside, - Brightness.light, - ); - expect(poLight.strokeOpacity, 1.96); - expect(poLight.brightness, 1.7); - expect(poLight.hairlineOpacity, 0); - }); - }); - - group('BeamColors', () { - test('presets resolve with mono flags', () { - final mono = BeamColors.mono.resolve(); - expect(mono.forcesStaticColors, isTrue); - expect(mono.opacityMultiplier, 0.5); - final colorful = BeamColors.colorful.resolve(); - expect(colorful.forcesStaticColors, isFalse); - expect(colorful.opacityMultiplier, 1.0); - }); - - test('custom cycles colors and preserves preset alpha', () { - const pink = Color(0xFFFF0080); - const cyan = Color(0xFF00FFEE); - final palette = const BeamColors.custom([pink, cyan]).resolve(); - expect(palette.data.border, hasLength(9)); - // Cycled: index 0 pink, 1 cyan, 2 pink... - expect(palette.data.border[0].color.r, closeTo(pink.r, 1e-6)); - expect(palette.data.border[1].color.b, closeTo(cyan.b, 1e-6)); - // Geometry preserved from colorful preset. - expect(palette.data.border[4].size, colorfulPreset.border[4].size); - // Inner alpha pattern preserved (smallInner[0] alpha 0.5). - expect(palette.data.smallInner[0].color.a, closeTo(0.5, 0.005)); - }); - }); -} diff --git a/test/constants/spec_parity_test.dart b/test/constants/spec_parity_test.dart deleted file mode 100644 index be6d608..0000000 --- a/test/constants/spec_parity_test.dart +++ /dev/null @@ -1,1375 +0,0 @@ -// Asserts every table in `lib/src/constants/` against the upstream React -// library's machine-readable spec, vendored at `test/fixtures/beam-spec.json`. -// -// Our constants are hand transcriptions of `src/styles.ts`; this test is the -// only thing that can prove the transcription is still faithful. A failure -// here means the SPEC and OUR CONSTANTS disagree — re-audit against -// `src/styles.ts` and report the divergence. Never "fix" a constant to make -// this test pass (CLAUDE.md hard rule 1). -// -// Spec conventions the parsers below handle: -// colors CSS `rgb(r, g, b)` / `rgba(r, g, b, a)` / `transparent` -// positions `"33% -7.4%"` → fractional Offset(0.33, -0.074) -// sizes `"70px 40px"` → Size(70, 40), and CSS ellipse sizes are RADII -// stops percent (0–100) where our tables carry fractions (0–1) - -import 'dart:convert'; -import 'dart:io'; -import 'dart:ui'; - -import 'package:flutter_border_beam/src/animation/beam_clock.dart'; -import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/animation/oscillator.dart'; -import 'package:flutter_border_beam/src/constants/line_geometry.dart'; -import 'package:flutter_border_beam/src/constants/line_keyframes.dart'; -import 'package:flutter_border_beam/src/constants/palettes.dart'; -import 'package:flutter_border_beam/src/constants/pulse_constants.dart'; -import 'package:flutter_border_beam/src/constants/pulse_params.dart'; -import 'package:flutter_border_beam/src/constants/pulse_tables.dart'; -import 'package:flutter_border_beam/src/constants/rotate_stops.dart'; -import 'package:flutter_border_beam/src/constants/theme_presets.dart'; -import 'package:flutter_border_beam/src/constants/upstream.dart'; -import 'package:flutter_border_beam/src/models/beam_blob.dart'; -import 'package:flutter_border_beam/src/models/beam_colors.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/models/beam_palette.dart'; -import 'package:flutter_border_beam/src/models/beam_style.dart'; -import 'package:flutter_border_beam/src/models/beam_variant.dart'; -import 'package:flutter_test/flutter_test.dart'; - -// ─── Fixture ──────────────────────────────────────────────────────────────── - -const String _fixturePath = 'test/fixtures/beam-spec.json'; -const String _upstreamPath = 'test/fixtures/UPSTREAM'; - -Map _loadSpec() => - jsonDecode(File(_fixturePath).readAsStringSync()) as Map; - -Map _loadUpstream() { - final out = {}; - for (final line in File(_upstreamPath).readAsLinesSync()) { - if (line.trim().isEmpty) continue; - final i = line.indexOf('='); - out[line.substring(0, i)] = line.substring(i + 1); - } - return out; -} - -// ─── CSS value parsers ────────────────────────────────────────────────────── - -/// Parses a spec color string: `rgb(r, g, b)`, `rgba(r, g, b, a)`, or the -/// keyword `transparent`. -Color cssColor(Object? raw) { - final s = (raw! as String).trim(); - if (s == 'transparent') return const Color(0x00000000); - final m = RegExp(r'^rgba?\(([^)]*)\)$').firstMatch(s); - if (m == null) throw FormatException('not a CSS rgb/rgba color: "$s"'); - final parts = m.group(1)!.split(',').map((p) => p.trim()).toList(); - if (parts.length != 3 && parts.length != 4) { - throw FormatException('CSS color needs 3 or 4 components: "$s"'); - } - return Color.fromRGBO( - int.parse(parts[0]), - int.parse(parts[1]), - int.parse(parts[2]), - parts.length == 4 ? double.parse(parts[3]) : 1.0, - ); -} - -/// Parses a spec position string — `"33% -7.4%"` → `Offset(0.33, -0.074)`. -Offset cssPosition(Object? raw) { - final parts = (raw! as String).trim().split(RegExp(r'\s+')); - if (parts.length != 2) { - throw FormatException('CSS position needs two components: "$raw"'); - } - double pct(String p) { - if (!p.endsWith('%')) throw FormatException('not a percentage: "$p"'); - return double.parse(p.substring(0, p.length - 1)) / 100; - } - - return Offset(pct(parts[0]), pct(parts[1])); -} - -/// Parses a spec size string — `"70px 40px"` → `Size(70, 40)`. CSS -/// `radial-gradient(ellipse W H …)` sizes are radii, and so is [Size] here. -Size cssSize(Object? raw) { - final parts = (raw! as String).trim().split(RegExp(r'\s+')); - if (parts.length != 2) { - throw FormatException('CSS size needs two components: "$raw"'); - } - double px(String p) { - if (!p.endsWith('px')) throw FormatException('not a px length: "$p"'); - return double.parse(p.substring(0, p.length - 2)); - } - - return Size(px(parts[0]), px(parts[1])); -} - -/// Parses a single spec percentage — `"27%"` → `0.27`. -double cssPercent(Object? raw) { - final s = (raw! as String).trim(); - if (!s.endsWith('%')) throw FormatException('not a percentage: "$s"'); - return double.parse(s.substring(0, s.length - 1)) / 100; -} - -// ─── Matchers ─────────────────────────────────────────────────────────────── - -/// One 8-bit step: CSS integer channels round-trip through Flutter's doubles. -const double _channelTolerance = 1 / 255; - -/// Half an ulp of the spec's 4-decimal rounding. Flutter stores alpha as an -/// exact double, so the only slack needed is the spec generator's rounding of -/// the mono-attenuated alphas (0.82 × 0.098 = 0.08036, recorded as 0.0804). -const double _alphaTolerance = 1e-4; - -const double _epsilon = 1e-9; - -void expectColor(Color actual, Object? specColor, String reason) { - final want = cssColor(specColor); - expect(actual.r, closeTo(want.r, _channelTolerance), reason: '$reason (r)'); - expect(actual.g, closeTo(want.g, _channelTolerance), reason: '$reason (g)'); - expect(actual.b, closeTo(want.b, _channelTolerance), reason: '$reason (b)'); - expect(actual.a, closeTo(want.a, _channelTolerance), reason: '$reason (a)'); -} - -/// Compares component-wise: `"-7.4%" / 100` and `-0.074` are the same -/// position but not the same double, so `Offset ==` is too strict here. -void expectOffset(Offset actual, Object? specPos, String reason) { - final want = cssPosition(specPos); - expect(actual.dx, closeTo(want.dx, _epsilon), reason: '$reason (dx)'); - expect(actual.dy, closeTo(want.dy, _epsilon), reason: '$reason (dy)'); -} - -void expectSize(Size actual, Object? specSize, String reason) { - final want = cssSize(specSize); - expect(actual.width, closeTo(want.width, _epsilon), reason: '$reason (w)'); - expect(actual.height, closeTo(want.height, _epsilon), reason: '$reason (h)'); -} - -/// Compares a color against loose spec channels (the expanded -/// `line.bloomGradients` stops carry r/g/b as ints and a as a double). -void expectChannels( - Color actual, { - required Map stop, - required String reason, - double alphaScale = 1, -}) { - expect( - actual.r, - closeTo((stop['r'] as num) / 255, _channelTolerance), - reason: '$reason (r)', - ); - expect( - actual.g, - closeTo((stop['g'] as num) / 255, _channelTolerance), - reason: '$reason (g)', - ); - expect( - actual.b, - closeTo((stop['b'] as num) / 255, _channelTolerance), - reason: '$reason (b)', - ); - expect( - actual.a * alphaScale, - closeTo((stop['a'] as num).toDouble(), _alphaTolerance), - reason: '$reason (a)', - ); -} - -void expectNum(num actual, Object? spec, String reason) => expect( - actual.toDouble(), - closeTo((spec! as num).toDouble(), _epsilon), - reason: reason, -); - -/// Asserts a `[[posPercent, value], …]` spec table against parallel -/// fraction/value lists. -/// [terminatedAt1] covers the tables whose CSS gradient stops short of 100% -/// and lets the last stop's (already transparent) color extend to the end. -/// Flutter's `SweepGradient` needs that extension written out, so our list -/// carries one extra `(1.0, 0.0)` entry the spec has no row for. -void expectStopTable( - Object? spec, - List stops, - List values, - String reason, { - bool terminatedAt1 = false, -}) { - final rows = (spec! as List).cast>(); - final extra = terminatedAt1 ? 1 : 0; - expect(stops, hasLength(rows.length + extra), reason: '$reason (stop count)'); - expect( - values, - hasLength(rows.length + extra), - reason: '$reason (value count)', - ); - for (var i = 0; i < rows.length; i++) { - expectNum(stops[i] * 100, rows[i][0], '$reason stop $i'); - expectNum(values[i], rows[i][1], '$reason value $i'); - } - if (terminatedAt1) { - expect(stops.last, 1.0, reason: '$reason terminal stop'); - expect(values.last, 0.0, reason: '$reason terminal value'); - expect( - values[values.length - 2], - 0.0, - reason: '$reason is already transparent before its terminator', - ); - } -} - -/// Asserts a `[[tPercent, value], …]` spec table against a keyframe list. -void expectKeyframes(Object? spec, List track, String reason) { - final rows = (spec! as List).cast>(); - expect(rows, hasLength(track.length), reason: '$reason (length)'); - for (var i = 0; i < rows.length; i++) { - expectNum(track[i].t * 100, rows[i][0], '$reason t$i'); - expectNum(track[i].value, rows[i][1], '$reason value$i'); - } -} - -// ─── Spec key ↔ Dart enum mapping ─────────────────────────────────────────── - -const Map _presets = { - 'colorful': colorfulPreset, - 'mono': monoPreset, - 'ocean': oceanPreset, - 'sunset': sunsetPreset, -}; - -const Map _sizes = { - 'sm': BeamVariant.small, - 'md': BeamVariant.rotate, - 'line': BeamVariant.line, - 'pulse-outside': BeamVariant.pulseOutside, - 'pulse-inner': BeamVariant.pulseInside, -}; - -const Map _regions = { - 1: PulseRegion.r1, - 2: PulseRegion.r2, - 3: PulseRegion.r3, -}; - -const Map _quads = { - 'tl': PulseQuad.tl, - 'tr': PulseQuad.tr, - 'bl': PulseQuad.bl, - 'br': PulseQuad.br, -}; - -void main() { - final spec = _loadSpec(); - final upstream = _loadUpstream(); - - Map obj(Map from, String key) => - from[key] as Map; - List arr(Map from, String key) => - from[key] as List; - - final palettes = obj(spec, 'palettes'); - final rotate = obj(spec, 'rotate'); - final line = obj(spec, 'line'); - final pulse = obj(spec, 'pulse'); - final defaults = obj(spec, 'defaults'); - - // ─── Provenance ─────────────────────────────────────────────────────────── - - group('provenance', () { - test( - 'the fixture is the spec version our constants were audited against', - () { - expect(spec['specVersion'], upstreamSpecVersion); - expect(obj(spec, 'sourceLibrary')['version'], upstreamLibraryVersion); - expect(obj(spec, 'sourceLibrary')['name'], 'border-beam'); - }, - ); - - test('UPSTREAM records the fetched commit and versions', () { - expect(upstream['commit'], matches(RegExp(r'^[0-9a-f]{40}$'))); - expect(upstream['styles_sha256'], matches(RegExp(r'^[0-9a-f]{64}$'))); - expect(upstream['version'], upstreamLibraryVersion); - expect(upstream['spec_version'], upstreamSpecVersion); - expect(upstreamRepository, contains('Jakubantalik/Libraries')); - }); - }); - - // ─── palettes.border ────────────────────────────────────────────────────── - - group('palettes.border', () { - final border = obj(palettes, 'border'); - for (final MapEntry(key: name, value: preset) in _presets.entries) { - final specPreset = obj(border, name); - - test('$name border blobs', () { - final blobs = specPreset['border'] as List; - expect( - preset.border, - hasLength(blobs.length), - reason: '$name border length', - ); - for (var i = 0; i < blobs.length; i++) { - final b = blobs[i] as Map; - final ours = preset.border[i]; - expectColor(ours.color, b['color'], '$name border[$i].color'); - expectOffset(ours.position, b['pos'], '$name border[$i].pos'); - expectSize(ours.size, b['size'], '$name border[$i].size'); - } - }); - - test('$name spike colors', () { - final s = obj(specPreset, 'spike'); - expectColor(preset.spike.primary, s['primary'], '$name spike.primary'); - expectColor( - preset.spike.secondary, - s['secondary'], - '$name spike.secondary', - ); - final lt = obj(specPreset, 'spikeLt'); - expectColor( - preset.spikeLt.primary, - lt['primary'], - '$name spikeLt.primary', - ); - expectColor( - preset.spikeLt.secondary, - lt['secondary'], - '$name spikeLt.secondary', - ); - }); - } - }); - - // ─── palettes.small ─────────────────────────────────────────────────────── - - group('palettes.small', () { - final small = obj(palettes, 'small'); - for (final MapEntry(key: name, value: preset) in _presets.entries) { - final specPreset = obj(small, name); - - void checkTable(String key, List ours) { - final blobs = specPreset[key] as List; - expect( - ours, - hasLength(blobs.length), - reason: '$name small.$key length', - ); - for (var i = 0; i < blobs.length; i++) { - final b = blobs[i] as Map; - expectColor(ours[i].color, b['color'], '$name small.$key[$i].color'); - expectOffset(ours[i].position, b['pos'], '$name small.$key[$i].pos'); - expectSize(ours[i].size, b['size'], '$name small.$key[$i].size'); - } - } - - test('$name smallBorder', () => checkTable('border', preset.smallBorder)); - test('$name smallInner', () => checkTable('inner', preset.smallInner)); - } - }); - - // ─── palettes.line / palettes.lineInner ─────────────────────────────────── - - group('palettes.line', () { - final specLine = obj(palettes, 'line'); - final specInner = obj(palettes, 'lineInner'); - - void checkLineBlobs( - String reason, - List blobs, - List ours, - ) { - expect(ours, hasLength(blobs.length), reason: '$reason length'); - for (var i = 0; i < blobs.length; i++) { - final b = blobs[i] as Map; - expectColor(ours[i].color, b['color'], '$reason[$i].color'); - expectNum(ours[i].sizeW, b['sizeW'], '$reason[$i].sizeW'); - expectNum(ours[i].sizeH, b['sizeH'], '$reason[$i].sizeH'); - expectNum(ours[i].offsetX, b['offsetX'], '$reason[$i].offsetX'); - expectNum(ours[i].offsetY, b['offsetY'], '$reason[$i].offsetY'); - } - } - - for (final MapEntry(key: name, value: preset) in _presets.entries) { - test('$name lineDark', () { - checkLineBlobs( - '$name line.dark', - arr(obj(specLine, name), 'dark'), - preset.lineDark, - ); - }); - test('$name lineLight', () { - checkLineBlobs( - '$name line.light', - arr(obj(specLine, name), 'light'), - preset.lineLight, - ); - }); - test('$name lineInner', () { - checkLineBlobs( - '$name lineInner', - specInner[name] as List, - preset.lineInner, - ); - }); - } - }); - - // ─── palettes.lineBloom ─────────────────────────────────────────────────── - - group('palettes.lineBloom', () { - final bloom = obj(palettes, 'lineBloom'); - for (final MapEntry(key: name, value: preset) in _presets.entries) { - for (final theme in const ['dark', 'light']) { - test('$name lineBloom.$theme', () { - final spikes = arr(obj(obj(bloom, name), theme), 'spikes'); - final ours = theme == 'dark' - ? preset.lineBloomDark - : preset.lineBloomLight; - expect( - ours, - hasLength(spikes.length), - reason: '$name lineBloom.$theme length', - ); - for (var i = 0; i < spikes.length; i++) { - final s = spikes[i] as Map; - expectColor( - ours[i].color1, - s['color1'], - '$name lineBloom.$theme[$i].c1', - ); - expectColor( - ours[i].color2, - s['color2'], - '$name lineBloom.$theme[$i].c2', - ); - } - }); - } - } - }); - - // ─── sizeThemePresets ───────────────────────────────────────────────────── - - group('sizeThemePresets', () { - final presets = obj(spec, 'sizeThemePresets'); - for (final MapEntry(key: size, value: variant) in _sizes.entries) { - for (final theme in const ['dark', 'light']) { - test('$size/$theme', () { - final s = obj(obj(presets, size), theme); - final ours = themePresetFor( - variant, - theme == 'dark' ? Brightness.dark : Brightness.light, - ); - expectNum( - ours.strokeOpacity, - s['strokeOpacity'], - '$size/$theme strokeOpacity', - ); - expectNum( - ours.innerOpacity, - s['innerOpacity'], - '$size/$theme innerOpacity', - ); - expectNum( - ours.bloomOpacity, - s['bloomOpacity'], - '$size/$theme bloomOpacity', - ); - expectColor( - ours.innerShadow, - s['innerShadow'], - '$size/$theme innerShadow', - ); - expectNum( - ours.saturation, - s['saturation'], - '$size/$theme saturation', - ); - - // `brightness` and `hairlineOpacity` are optional in the spec; a - // missing key must mean a null field on our side, not a default. - if (s.containsKey('brightness')) { - expect( - ours.brightness, - isNotNull, - reason: '$size/$theme brightness present in spec', - ); - expectNum( - ours.brightness!, - s['brightness'], - '$size/$theme brightness', - ); - } else { - expect( - ours.brightness, - isNull, - reason: '$size/$theme brightness absent from spec', - ); - } - if (s.containsKey('hairlineOpacity')) { - expect( - ours.hairlineOpacity, - isNotNull, - reason: '$size/$theme hairlineOpacity present in spec', - ); - expectNum( - ours.hairlineOpacity!, - s['hairlineOpacity'], - '$size/$theme hairlineOpacity', - ); - } else { - expect( - ours.hairlineOpacity, - isNull, - reason: '$size/$theme hairlineOpacity absent from spec', - ); - } - }); - } - } - }); - - // ─── sizePresets ────────────────────────────────────────────────────────── - - group('sizePresets', () { - final presets = obj(spec, 'sizePresets'); - for (final MapEntry(key: size, value: variant) in _sizes.entries) { - test('$size radius and border width', () { - final s = obj(presets, size); - expectNum( - variant.defaultBorderRadius, - s['borderRadius'], - '$size borderRadius', - ); - expectNum( - variant.defaultBorderWidth, - s['borderWidth'], - '$size borderWidth', - ); - }); - } - // GAP: sizePresets.sm.width/height (70×36) has no counterpart — the - // Flutter widget wraps and measures its child instead of forcing a size. - }); - - // ─── rotate.* ───────────────────────────────────────────────────────────── - - group('rotate stops', () { - test('beamMaskStops ↔ rotateWindow*', () { - expectStopTable( - rotate['beamMaskStops'], - rotateWindowStops, - rotateWindowAlphas, - 'beamMaskStops', - ); - }); - - test('smallMaskStops ↔ smallWindow*', () { - expectStopTable( - rotate['smallMaskStops'], - smallWindowStops, - smallWindowAlphas, - 'smallMaskStops', - ); - }); - - test('whiteGradientStops.dark ↔ rotateHighlight*Dark', () { - expectStopTable( - obj(rotate, 'whiteGradientStops')['dark'], - rotateHighlightStops, - rotateHighlightAlphasDark, - 'whiteGradient.dark', - ); - }); - - test('whiteGradientStops.light ↔ rotateHighlight*Light', () { - expectStopTable( - obj(rotate, 'whiteGradientStops')['light'], - rotateHighlightStops, - rotateHighlightAlphasLight, - 'whiteGradient.light', - ); - }); - - test('bloomGradientStops.dark ↔ rotateBloom*Dark', () { - expectStopTable( - obj(rotate, 'bloomGradientStops')['dark'], - rotateBloomStops, - rotateBloomAlphasDark, - 'bloomGradient.dark', - terminatedAt1: true, - ); - }); - - test('bloomGradientStops.light ↔ rotateBloom*Light', () { - expectStopTable( - obj(rotate, 'bloomGradientStops')['light'], - rotateBloomStops, - rotateBloomAlphasLight, - 'bloomGradient.light', - terminatedAt1: true, - ); - }); - }); - - group('rotate constants', () { - test('innerGradientDerivation ↔ rotateInnerBlob*', () { - final d = obj(rotate, 'innerGradientDerivation'); - expectNum(rotateInnerBlobScale, d['sizeScale'], 'inner sizeScale'); - expectNum(rotateInnerBlobAlpha, d['alpha'], 'inner alpha'); - expectNum(rotateInnerBlobAlphaMono, d['monoAlpha'], 'inner monoAlpha'); - }); - - test('innerShadowBlur ↔ rotate/small inner shadow blur', () { - final b = obj(rotate, 'innerShadowBlur'); - expectNum(rotateInnerShadowBlur, b['md'], 'innerShadowBlur.md'); - expectNum(smallInnerShadowBlur, b['sm'], 'innerShadowBlur.sm'); - }); - - test('bloomBlurPx ↔ rotateBloomBlurSigma', () { - // CSS `filter: blur(Npx)` maps to sigma = N. - expectNum(rotateBloomBlurSigma, rotate['bloomBlurPx'], 'bloomBlurPx'); - }); - - // GAP: rotate.innerEdgeMaskPx (28) and rotate.spin (0→360, linear) have no - // constant of their own — the feather is a default argument on - // `BeamGradients.vertical/horizontalEdgeFeather` and the spin is the - // rotate variant's angle = travelProgress × 2π. - }); - - // ─── line geometry ──────────────────────────────────────────────────────── - - group('line geometry', () { - test('beamMaskEllipse ↔ lineWindow*', () { - final e = obj(line, 'beamMaskEllipse'); - expectNum(lineWindowRadiusX, e['w'], 'beamMask w'); - expectNum(lineWindowRadiusY, e['h'], 'beamMask h'); - final soft = (e['softStop']! as List).cast(); - expectNum(lineWindowMidStop * 100, soft[0], 'beamMask soft stop'); - expectNum(lineWindowMidAlpha, soft[1], 'beamMask soft alpha'); - }); - - test('bloomMaskEllipse ↔ lineBloomWindow*', () { - final e = obj(line, 'bloomMaskEllipse'); - expectNum(lineBloomWindowRadiusX, e['w'], 'bloomMask w'); - expectNum(lineBloomWindowRadiusY, e['h'], 'bloomMask h'); - final soft = (e['softStop']! as List).cast(); - expectNum(lineBloomWindowMidStop * 100, soft[0], 'bloomMask soft stop'); - expectNum(lineBloomWindowMidAlpha, soft[1], 'bloomMask soft alpha'); - }); - - test('whiteHighlight.dark ↔ lineHighlight*Dark', () { - final h = obj(obj(line, 'whiteHighlight'), 'dark'); - expectNum(lineHighlightRadiusXDark, h['w'], 'highlight.dark w'); - expectNum(lineHighlightRadiusYDark, h['h'], 'highlight.dark h'); - expectNum(lineHighlightOffsetY, h['yOffset'], 'highlight.dark yOffset'); - expectStopTable( - h['stops'], - lineHighlightStopsDark, - lineHighlightAlphasDark, - 'highlight.dark stops', - ); - }); - - test('whiteHighlight.light ↔ lineHighlight*Light', () { - final h = obj(obj(line, 'whiteHighlight'), 'light'); - expectNum(lineHighlightRadiusXLight, h['w'], 'highlight.light w'); - expectNum(lineHighlightRadiusYLight, h['h'], 'highlight.light h'); - expectNum(lineHighlightOffsetY, h['yOffset'], 'highlight.light yOffset'); - expectStopTable( - h['stops'], - lineHighlightStopsLight, - lineHighlightAlphasLight, - 'highlight.light stops', - ); - // The light-theme highlight paints black, not white. - expect(h['onBlack'], isTrue); - }); - - test('bloom blur sigmas', () { - expectNum(lineBloomBlurSigma, line['bloomBlurPx'], 'line bloomBlurPx'); - // The spec calls this key `monoBloomExtraBlurPx`, but in `styles.ts` the - // mono branch REPLACES the animated bloom filter (`blur(8px) hue-rotate…`) - // with a bare `filter: blur(6px)` — it does not add to it. The value is - // the mono sigma, which is what we store. - expectNum( - lineBloomBlurSigmaMono, - line['monoBloomExtraBlurPx'], - 'line monoBloomExtraBlurPx', - ); - }); - - // GAP: no `line.innerShadowBlur` in the spec; `lineInnerShadowBlur` (9) - // is transcribed from `box-shadow: inset 0 0 9px 1px` in styles.ts. - }); - - // ─── line keyframes ─────────────────────────────────────────────────────── - - group('line keyframes', () { - final kf = obj(line, 'keyframes'); - - test('travel.x ↔ lineTravelX', () { - expectKeyframes(obj(kf, 'travel')['x'], lineTravelX, 'travel.x'); - }); - test('travel.w ↔ lineTravelW', () { - expectKeyframes(obj(kf, 'travel')['w'], lineTravelW, 'travel.w'); - }); - test('edgeFade ↔ lineEdgeFade', () { - expectKeyframes(kf['edgeFade'], lineEdgeFade, 'edgeFade'); - }); - test('breathe ↔ lineBreatheH', () { - expectKeyframes(kf['breathe'], lineBreatheH, 'breathe'); - }); - test('spike ↔ lineSpike', () { - expectKeyframes(kf['spike'], lineSpike, 'spike'); - }); - test('spike2 ↔ lineSpike2', () { - expectKeyframes(kf['spike2'], lineSpike2, 'spike2'); - }); - - test('durationScale ↔ BeamConfig breathe/spike factors', () { - final s = obj(kf, 'durationScale'); - final config = _configFor(BeamVariant.line); - expectNum(1, s['travel'], 'durationScale.travel'); - expectNum(1, s['edgeFade'], 'durationScale.edgeFade'); - expectNum(config.breatheFactor, s['breathe'], 'durationScale.breathe'); - expectNum(config.spikeFactor, s['spike'], 'durationScale.spike'); - expectNum(config.spike2Factor, s['spike2'], 'durationScale.spike2'); - }); - - test('easing per track', () { - final e = obj(kf, 'easing'); - // The travel/edge tracks sample linearly; breathe/spike ease per - // segment (`sampleKeyframes(..., easedSegments: true)`). - expect(e['travel'], 'linear'); - expect(e['edgeFade'], 'linear'); - expect(e['breathe'], 'easeInOut'); - expect(e['spike'], 'easeInOut'); - expect(e['spike2'], 'easeInOut'); - }); - }); - - // ─── line.bloomGradients — the expanded spike table ─────────────────────── - // - // The spec expands each palette × theme into 7 fixed spikes plus (dark) the - // traveling dot and ambient glow, or (light) the traveling shadow. Our port - // keeps the geometry in `line_geometry.dart` and the colors in the palette - // tables, with the mono attenuation applied at paint time — so the mono rows - // are compared against `ourAlpha × attenuation`. - - group('line.bloomGradients', () { - final grads = obj(line, 'bloomGradients'); - - /// Indices of the four thin (color-palette) spikes within the 7. - const thin = [0, 2, 4, 6]; - - for (final MapEntry(key: name, value: preset) in _presets.entries) { - final isMono = name == 'mono'; - for (final theme in const ['dark', 'light']) { - final isDark = theme == 'dark'; - - test('$name/$theme spike geometry', () { - final rows = arr( - obj(grads, name), - theme, - ).cast>(); - expect(lineSpikes, hasLength(7)); - for (var i = 0; i < 7; i++) { - final r = rows[i]; - final s = lineSpikes[i]; - expectNum(s.fx * 100, r['xPct'], '$name/$theme spike$i xPct'); - expectNum(-s.yInset, r['yOffPx'], '$name/$theme spike$i yOffPx'); - final stops = (r['stops']! as List).cast>(); - expect( - stops, - hasLength(3), - reason: '$name/$theme spike$i stop count', - ); - expectNum(0, stops[0]['pos'], '$name/$theme spike$i pos0'); - expectNum(s.midStop, stops[1]['pos'], '$name/$theme spike$i mid'); - expectNum(s.endStop, stops[2]['pos'], '$name/$theme spike$i end'); - expectNum(0, stops[2]['a'], '$name/$theme spike$i end alpha'); - - // Radii. - final w = obj(r, 'w')['base']! as num; - final h = obj(r, 'h')['base']! as num; - final t = thin.indexOf(i); - if (t >= 0) { - final wantW = isMono - ? (i == 6 && !isDark - ? lineMonoThinSpikeWidthLight92 - : lineMonoThinSpikeWidths[t]) - : (i == 6 && !isDark - ? lineThinSpikeWidthLight92 - : lineThinSpikeWidths[t]); - final wantH = isMono - ? lineMonoThinSpikeHeights[t] - : lineThinSpikeHeights[t]; - expectNum(wantW, w, '$name/$theme spike$i width'); - expectNum(wantH, h, '$name/$theme spike$i height'); - } else { - final wantW = switch (i) { - 1 => lineSpikeWideRadiusX22, - 3 => lineSpikeWideRadiusX50, - _ => lineSpikeRadiusX78, - }; - final wantH = switch (i) { - 1 => lineSpikeRadiusY22, - 3 => lineSpikeRadiusY50, - _ => lineSpikeRadiusY78, - }; - expectNum(wantW, w, '$name/$theme spike$i width'); - expectNum(wantH, h, '$name/$theme spike$i height'); - } - } - }); - - test('$name/$theme spike colors', () { - final rows = arr( - obj(grads, name), - theme, - ).cast>(); - final spikes = isDark ? preset.spike : preset.spikeLt; - final table = isDark ? preset.lineBloomDark : preset.lineBloomLight; - - List> stopsOf(int i) => - (rows[i]['stops']! as List).cast>(); - - // Spike 0 — the primary accent. - final s0 = stopsOf(0); - expectChannels( - spikes.primary, - stop: s0[0], - reason: '$name/$theme spike0 core', - alphaScale: isMono ? lineMonoSpike1 : 1, - ); - expectChannels( - spikes.primary, - stop: s0[1], - reason: '$name/$theme spike0 mid', - alphaScale: isMono - ? (isDark ? lineMonoSpike1MidDark : lineMonoSpike1MidLight) - : (isDark ? 1 : lineSpike1MidLightAlpha), - ); - - // Spike 1 — the secondary accent. - final s1 = stopsOf(1); - expectChannels( - spikes.secondary, - stop: s1[0], - reason: '$name/$theme spike1 core', - alphaScale: isMono ? lineMonoSpike2 : 1, - ); - expectChannels( - spikes.secondary, - stop: s1[1], - reason: '$name/$theme spike1 mid', - alphaScale: isMono - ? (isDark ? lineMonoSpike2MidDark : lineMonoSpike2MidLight) - : (isDark ? lineSpike2MidDarkAlpha : lineSpike2MidLightAlpha) / - spikes.secondary.a, - ); - - // Spikes 2–6 — the five palette bloom pairs. - for (var i = 2; i < 7; i++) { - final st = stopsOf(i); - final pair = table[i - 2]; - expectChannels( - pair.color1, - stop: st[0], - reason: '$name/$theme spike$i core', - alphaScale: isMono ? lineMonoTableSpike1 : 1, - ); - expectChannels( - pair.color2, - stop: st[1], - reason: '$name/$theme spike$i mid', - alphaScale: isMono ? lineMonoTableSpike2 : 1, - ); - } - }); - - test('$name/$theme traveling dot, ambient glow and shadow', () { - final rows = arr( - obj(grads, name), - theme, - ).cast>(); - if (isDark) { - expect( - rows, - hasLength(9), - reason: 'dark carries dot + ambient after the 7 spikes', - ); - final dot = rows[7]; - expectNum(lineDotOffsetY, dot['yOffPx'], '$name dot yOffPx'); - expectNum(lineDotRadiusX, obj(dot, 'w')['base'], '$name dot w'); - expectNum(lineDotRadiusY, obj(dot, 'h')['base'], '$name dot h'); - final dotStops = (dot['stops']! as List) - .cast>(); - final dotAlphas = isMono ? lineDotAlphasMono : lineDotAlphas; - for (var i = 0; i < lineDotStops.length; i++) { - expectNum(lineDotStops[i], dotStops[i]['pos'], '$name dot pos$i'); - expectNum( - i < dotAlphas.length ? dotAlphas[i] : 0, - dotStops[i]['a'], - '$name dot alpha$i', - ); - expectNum(255, dotStops[i]['r'], '$name dot is white'); - } - - final amb = rows[8]; - expectNum(0, amb['yOffPx'], '$name ambient yOffPx'); - expectNum(lineAmbientRadiusX, obj(amb, 'w')['base'], '$name amb w'); - expectNum(lineAmbientRadiusY, obj(amb, 'h')['base'], '$name amb h'); - final ambStops = (amb['stops']! as List) - .cast>(); - final ambAlphas = isMono - ? lineAmbientAlphasMono - : lineAmbientAlphas; - for (var i = 0; i < lineAmbientStops.length; i++) { - expectNum( - lineAmbientStops[i], - ambStops[i]['pos'], - '$name amb pos$i', - ); - expectNum( - i < ambAlphas.length ? ambAlphas[i] : 0, - ambStops[i]['a'], - '$name amb alpha$i', - ); - } - } else { - expect( - rows, - hasLength(8), - reason: 'light carries one shadow blob after the 7 spikes', - ); - final sh = rows[7]; - expectNum(0, sh['yOffPx'], '$name shadow yOffPx'); - expectNum( - lineShadowRadiusX, - obj(sh, 'w')['base'], - '$name shadow w', - ); - expectNum( - lineShadowRadiusY, - obj(sh, 'h')['base'], - '$name shadow h', - ); - final shStops = (sh['stops']! as List).cast>(); - for (var i = 0; i < lineShadowStops.length; i++) { - expectNum( - lineShadowStops[i], - shStops[i]['pos'], - '$name shadow pos$i', - ); - expectNum( - lineShadowAlphas[i], - shStops[i]['a'], - '$name shadow alpha$i', - ); - expectNum(0, shStops[i]['r'], '$name shadow is black'); - } - } - }); - } - } - }); - - // ─── pulse tables ───────────────────────────────────────────────────────── - - group('pulse tables', () { - test('ringMap ↔ pulseRingMap', () { - final rows = arr(pulse, 'ringMap').cast>(); - expect(pulseRingMap, hasLength(rows.length)); - for (var i = 0; i < rows.length; i++) { - expect( - pulseRingMap[i].region, - _regions[rows[i]['region']], - reason: 'ringMap[$i].region', - ); - expect( - pulseRingMap[i].quad, - _quads[rows[i]['quad']], - reason: 'ringMap[$i].quad', - ); - } - }); - - test('innerSizes ↔ pulseInnerSizes', () { - final rows = arr(pulse, 'innerSizes').cast>(); - expect(pulseInnerSizes, hasLength(rows.length)); - for (var i = 0; i < rows.length; i++) { - expectNum(pulseInnerSizes[i].width, rows[i][0], 'innerSizes[$i].w'); - expectNum(pulseInnerSizes[i].height, rows[i][1], 'innerSizes[$i].h'); - } - }); - - void checkSpecs( - String key, - List ours, { - required bool positioned, - }) { - final rows = arr(pulse, key).cast>(); - expect(ours, hasLength(rows.length), reason: '$key length'); - for (var i = 0; i < rows.length; i++) { - final r = rows[i]; - expect(ours[i].ci, r['ci'], reason: '$key[$i].ci'); - expect( - ours[i].region, - _regions[r['region']], - reason: '$key[$i].region', - ); - expect(ours[i].quad, _quads[r['quad']], reason: '$key[$i].quad'); - expectNum(ours[i].w, r['w'], '$key[$i].w'); - expectNum(ours[i].h, r['h'], '$key[$i].h'); - if (positioned) { - expect(ours[i].x, isNotNull, reason: '$key[$i].x'); - expect(ours[i].y, isNotNull, reason: '$key[$i].y'); - expect( - ours[i].x!, - closeTo(cssPercent(r['x']), _epsilon), - reason: '$key[$i].x', - ); - expect( - ours[i].y!, - closeTo(cssPercent(r['y']), _epsilon), - reason: '$key[$i].y', - ); - } else { - expect(r.containsKey('x'), isFalse, reason: '$key[$i] has no x'); - expect(ours[i].x, isNull, reason: '$key[$i].x inherits'); - expect(ours[i].y, isNull, reason: '$key[$i].y inherits'); - } - } - } - - test('innerBloom ↔ pulseInnerBloom', () { - checkSpecs('innerBloom', pulseInnerBloom, positioned: false); - }); - test('outerCore ↔ pulseOuterCore', () { - checkSpecs('outerCore', pulseOuterCore, positioned: true); - }); - test('outerBloom ↔ pulseOuterBloom', () { - checkSpecs('outerBloom', pulseOuterBloom, positioned: true); - }); - - test('innerCornerAccent ↔ pulseInnerCorner*', () { - final a = obj(pulse, 'innerCornerAccent'); - expectNum(pulseInnerCornerRadius, a['sizePx'], 'cornerAccent sizePx'); - expectNum( - pulseInnerCornerAlphaDark, - obj(a, 'alpha')['dark'], - 'cornerAccent alpha.dark', - ); - expectNum( - pulseInnerCornerAlphaLight, - obj(a, 'alpha')['light'], - 'cornerAccent alpha.light', - ); - expectNum( - pulseInnerCornerEndStop * 100, - a['fadeStop'], - 'cornerAccent fadeStop', - ); - }); - - test('innerBloomBlurPx ↔ pulseInnerBloomBlurSigma', () { - expectNum( - pulseInnerBloomBlurSigma, - pulse['innerBloomBlurPx'], - 'innerBloomBlurPx', - ); - }); - - test('oscillatorCurve is the cosine ping-pong we implement', () { - expect(pulse['oscillatorCurve'], 'cosinePingPong'); - expect(pingPong(0), closeTo(0, _epsilon)); - expect(pingPong(0.5), closeTo(1, _epsilon)); - expect(pingPong(1), closeTo(0, _epsilon)); - // Cosine is even, so negative phases (positive delays) are valid. - expect(pingPong(-0.25), closeTo(pingPong(0.25), _epsilon)); - }); - }); - - // ─── pulse params, oscillators and hue periods ──────────────────────────── - - group('pulse params', () { - const variants = { - 'inner': BeamVariant.pulseInside, - 'outside': BeamVariant.pulseOutside, - }; - - for (final MapEntry(key: key, value: variant) in variants.entries) { - for (final theme in const ['dark', 'light']) { - final brightness = theme == 'dark' ? Brightness.dark : Brightness.light; - - test('$key/$theme params ↔ PulseParams.resolve', () { - final s = obj(obj(obj(pulse, key), theme), 'params'); - // 2.3 is the source's pulse cycle duration, at which durScale == 1. - final p = PulseParams.resolve(variant, brightness, 2.3); - expectNum(p.sp, s['sp'], '$key/$theme sp'); - expectNum(p.dr, s['dr'], '$key/$theme dr'); - expectNum(p.op, s['op'], '$key/$theme op'); - expectNum(p.gh, s['gh'], '$key/$theme gh'); - expectNum(p.bs, s['bs'], '$key/$theme bs'); - expectNum(p.ss, s['ss'], '$key/$theme ss'); - expectNum(p.ghs, s['ghs'], '$key/$theme ghs'); - expectNum(p.huePeriod, s['huePeriod'], '$key/$theme huePeriod'); - }); - - test('$key/$theme oscillators ↔ PulseOscillatorBank', () { - final rows = arr( - obj(obj(pulse, key), theme), - 'oscillators', - ).cast>(); - final bank = PulseOscillatorBank( - PulseParams.resolve(variant, brightness, 2.3), - ); - expect( - bank.oscillators, - hasLength(rows.length), - reason: '$key/$theme oscillator count', - ); - expect( - bank.oscillators.keys.toList(), - rows.map((r) => r['prop']).toList(), - reason: '$key/$theme oscillator order', - ); - for (final r in rows) { - final prop = r['prop']! as String; - final o = bank.oscillators[prop]!; - expectNum(o.a, r['a'], '$key/$theme $prop.a'); - expectNum(o.b, r['b'], '$key/$theme $prop.b'); - expectNum(o.period, r['period'], '$key/$theme $prop.period'); - expectNum(o.delay, r['delay'], '$key/$theme $prop.delay'); - expect( - r['unit'], - prop.startsWith('bx') || prop.startsWith('by') ? 'px' : '', - reason: '$key/$theme $prop.unit', - ); - } - }); - - test('$key/$theme frozenBloomAlpha ↔ 1 − op/2', () { - final s = obj(obj(pulse, key), theme); - final p = PulseParams.resolve(variant, brightness, 2.3); - expectNum( - 1 - p.op * 0.5, - s['frozenBloomAlpha'], - '$key/$theme frozenBloomAlpha', - ); - }); - } - } - - test('huePeriod ↔ BeamVariant.defaultHuePeriod', () { - final h = obj(pulse, 'huePeriod'); - expectNum( - BeamVariant.pulseInside.defaultHuePeriod.inMilliseconds / 1000, - h['pulse-inner'], - 'pulse-inner huePeriod', - ); - expectNum( - BeamVariant.pulseOutside.defaultHuePeriod.inMilliseconds / 1000, - h['pulse-outside'], - 'pulse-outside huePeriod', - ); - }); - }); - - // ─── pulse.outsideConstants ─────────────────────────────────────────────── - - group('pulse.outsideConstants', () { - // Only the VERBATIM half of `pulse_constants.dart` maps here. The blur and - // inset values below them in that file are the source demo page's tuned - // `.beam-host--pulse-outside-tuned` recipe, which this port bakes in — the - // spec records the library's untuned defaults instead, so they are - // deliberately not compared. See the file header. - final c = obj(pulse, 'outsideConstants'); - - test('glowScale ↔ pulseOuterScaleX/Y', () { - expectNum(pulseOuterScaleX, obj(c, 'glowScale')['x'], 'glowScale.x'); - expectNum(pulseOuterScaleY, obj(c, 'glowScale')['y'], 'glowScale.y'); - }); - - test('referenceSize ↔ pulseOuterReference*', () { - expectNum( - pulseOuterReferenceWidth, - obj(c, 'referenceSize')['w'], - 'referenceSize.w', - ); - expectNum( - pulseOuterReferenceHeight, - obj(c, 'referenceSize')['h'], - 'referenceSize.h', - ); - }); - - test('scaleClamp ↔ pulseOuterMin/MaxScale', () { - expectNum(pulseOuterMinScale, obj(c, 'scaleClamp')['min'], 'clamp.min'); - expectNum(pulseOuterMaxScale, obj(c, 'scaleClamp')['max'], 'clamp.max'); - }); - - // GAPS in pulse_constants.dart, all deliberate: - // * glowBlurPx (3/6), bloomBlurPx (22.5/15), coreInsetPx (10), - // bloomInsetPx (30) — the library's untuned defaults; the port ships - // the demo recipe (6/14 insets, 10/19 unit-scaled blurs) instead, all - // overridable through coreBlur/bloomBlur. - // * hairline.rgb (dark 70,70,70 / light 0,0,0) — lives inline in - // `PulseOuterStrategy.paintAbove`, not in a constant. - // * pulseOuterGlowUnitDamping (0.7) has no spec counterpart. - }); - - // ─── defaults ───────────────────────────────────────────────────────────── - - group('defaults', () { - test('cycle durations ↔ BeamVariant.defaultCycleDuration', () { - final d = obj(defaults, 'duration'); - double secs(BeamVariant v) => - v.defaultCycleDuration.inMicroseconds / 1000000; - expectNum(secs(BeamVariant.rotate), d['rotate'], 'rotate duration'); - expectNum(secs(BeamVariant.small), d['rotate'], 'small duration'); - expectNum(secs(BeamVariant.line), d['line'], 'line duration'); - expectNum(secs(BeamVariant.pulseInside), d['pulse'], 'pulseInside'); - expectNum(secs(BeamVariant.pulseOutside), d['pulse'], 'pulseOutside'); - }); - - test('hueRange and the line cap ↔ BeamConfig.resolve', () { - expectNum( - _configFor(BeamVariant.rotate).hueRange, - defaults['hueRange'], - 'default hueRange', - ); - // The line variant caps the range; a range under the cap passes through. - expectNum( - _configFor(BeamVariant.line).hueRange, - defaults['lineHueRangeCap'], - 'line hueRange cap', - ); - expect(_configFor(BeamVariant.line, hueRange: 5).hueRange, 5.0); - }); - - test('fade seconds ↔ BeamClock', () { - expectNum(BeamClock.fadeInSeconds, defaults['fadeInSeconds'], 'fadeIn'); - expectNum( - BeamClock.fadeOutSeconds, - defaults['fadeOutSeconds'], - 'fadeOut', - ); - }); - - test('strength and brightness fallback ↔ BeamConfig.resolve', () { - expectNum( - _configFor(BeamVariant.rotate).strength, - defaults['strength'], - 'default strength', - ); - // `md` has no `brightness` in its theme preset, so the fallback shows. - expect( - themePresetFor(BeamVariant.rotate, Brightness.dark).brightness, - isNull, - ); - expectNum( - _configFor(BeamVariant.rotate).brightnessFactor, - defaults['brightnessFallback'], - 'brightness fallback', - ); - }); - - test('mono treatment ↔ BeamColors.mono', () { - final mono = BeamColors.mono.resolve(); - expectNum( - mono.opacityMultiplier, - defaults['monoOpacityMultiplier'], - 'monoOpacityMultiplier', - ); - expect(mono.forcesStaticColors, defaults['monoForcesStaticColors']); - expect(mono.monoTreatment, isTrue); - }); - - test('hue-shift periods ↔ BeamVariant defaults', () { - double secs(Duration d) => d.inMicroseconds / 1000000; - for (final v in [ - BeamVariant.rotate, - BeamVariant.small, - BeamVariant.line, - ]) { - expectNum( - secs(v.defaultHuePeriod), - defaults['rotateHueShiftPeriod'], - '$v huePeriod', - ); - } - expectNum( - secs(BeamVariant.line.defaultBloomHuePeriod), - defaults['lineBloomHueShiftPeriod'], - 'line bloom huePeriod', - ); - }); - - test('line bloom hue range carries the +10° bonus', () { - final config = _configFor(BeamVariant.line); - final resolver = BeamPhaseResolver(config); - // `_pingPongHue` reaches −range at t=0 and +range at half a period. - final low = resolver.sample(0, 1).bloomHueDegrees; - final high = resolver - .sample(config.bloomHuePeriodSeconds / 2, 1) - .bloomHueDegrees; - expectNum( - (high - low) / 2 - config.hueRange, - defaults['lineBloomHueRangeBonus'], - 'lineBloomHueRangeBonus', - ); - }); - - test('the spec\'s declared defaults name our built-ins', () { - expect(defaults['size'], 'md'); - expect(defaults['colorVariant'], 'colorful'); - expect(defaults['theme'], 'dark'); - expect(defaults['fadeEasing'], 'ease'); - }); - - // GAP: `defaults.pulseDriverFps` (30) is the source's pulse-driver tick - // rate; ours is BeamClock's optional fps cap, not a constant. - // GAP: `filters.order` / `filters.hueRotateModel` describe the CSS filter - // pipeline our `BeamColorMatrix` implements; no constant mirrors them. - }); - - // ─── enums ──────────────────────────────────────────────────────────────── - - group('enums', () { - test('sizes ↔ BeamVariant', () { - expect( - arr(obj(spec, 'enums'), 'sizes').cast().toSet(), - _sizes.keys.toSet(), - ); - expect(_sizes.values.toSet(), BeamVariant.values.toSet()); - }); - - test('colorVariants ↔ the four transcribed presets', () { - expect( - arr(obj(spec, 'enums'), 'colorVariants').cast().toSet(), - _presets.keys.toSet(), - ); - }); - - test('themes ↔ Brightness', () { - expect(arr(obj(spec, 'enums'), 'themes').cast(), [ - 'dark', - 'light', - ]); - }); - }); -} - -/// A resolved config for [variant] at the source's defaults. -BeamConfig _configFor(BeamVariant variant, {double? hueRange}) => - BeamConfig.resolve( - variant: variant, - palette: const BeamPalette(data: colorfulPreset), - brightness: Brightness.dark, - style: hueRange == null - ? const BeamStyle() - : BeamStyle(hueRange: hueRange), - ); diff --git a/test/fixtures/UPSTREAM b/test/fixtures/UPSTREAM deleted file mode 100644 index e752dc6..0000000 --- a/test/fixtures/UPSTREAM +++ /dev/null @@ -1,5 +0,0 @@ -commit=3862ffa345217443b63696a8c331a0664eea4b04 -version=1.3.0 -package_version=1.4.0 -spec_version=1.0.0 -styles_sha256=547f7c91c4a33eade75dd00869a2bd49d5dac4ddc95be841b03e35f64a0fd344 diff --git a/test/fixtures/beam-spec.json b/test/fixtures/beam-spec.json deleted file mode 100644 index 85865ba..0000000 --- a/test/fixtures/beam-spec.json +++ /dev/null @@ -1,5731 +0,0 @@ -{ - "specVersion": "1.0.0", - "sourceLibrary": { - "name": "border-beam", - "version": "1.3.0" - }, - "generated": "2026-07-27", - "reference": "Web demo at https://beam.jakubantalik.com is the visual ground truth.", - "enums": { - "sizes": [ - "sm", - "md", - "line", - "pulse-outside", - "pulse-inner" - ], - "colorVariants": [ - "colorful", - "mono", - "ocean", - "sunset" - ], - "themes": [ - "dark", - "light" - ] - }, - "defaults": { - "size": "md", - "colorVariant": "colorful", - "theme": "dark", - "duration": { - "line": 3.1, - "pulse": 2.3, - "rotate": 1.96 - }, - "hueRange": 30, - "lineHueRangeCap": 13, - "strength": 1, - "brightnessFallback": 1.3, - "fadeInSeconds": 0.6, - "fadeOutSeconds": 0.5, - "fadeEasing": "ease", - "rotateHueShiftPeriod": 12, - "lineBloomHueShiftPeriod": 8, - "lineBloomHueRangeBonus": 10, - "monoOpacityMultiplier": 0.5, - "monoForcesStaticColors": true, - "pulseDriverFps": 30 - }, - "sizePresets": { - "sm": { - "borderRadius": 32, - "borderWidth": 1, - "width": 70, - "height": 36 - }, - "md": { - "borderRadius": 16, - "borderWidth": 1 - }, - "line": { - "borderRadius": 16, - "borderWidth": 1 - }, - "pulse-outside": { - "borderRadius": 16, - "borderWidth": 1 - }, - "pulse-inner": { - "borderRadius": 16, - "borderWidth": 1 - } - }, - "sizeThemePresets": { - "sm": { - "dark": { - "strokeOpacity": 0.46, - "innerOpacity": 0.24, - "bloomOpacity": 0.38, - "innerShadow": "rgba(255, 255, 255, 0.3)", - "saturation": 1.2 - }, - "light": { - "strokeOpacity": 0.12, - "innerOpacity": 0.3, - "bloomOpacity": 0.16, - "innerShadow": "rgba(0, 0, 0, 0.14)", - "saturation": 1.8 - } - }, - "md": { - "dark": { - "strokeOpacity": 0.26, - "innerOpacity": 0.42, - "bloomOpacity": 0.24, - "innerShadow": "rgba(255, 255, 255, 0.27)", - "saturation": 1.2 - }, - "light": { - "strokeOpacity": 0.12, - "innerOpacity": 0.26, - "bloomOpacity": 0.34, - "innerShadow": "rgba(0, 0, 0, 0.14)", - "saturation": 1.5 - } - }, - "line": { - "dark": { - "strokeOpacity": 1.14, - "innerOpacity": 0.7, - "bloomOpacity": 0.8, - "innerShadow": "rgba(255, 255, 255, 0.1)", - "saturation": 1.2 - }, - "light": { - "strokeOpacity": 0.16, - "innerOpacity": 0.32, - "bloomOpacity": 0.3, - "innerShadow": "rgba(0, 0, 0, 0.14)", - "saturation": 1.95 - } - }, - "pulse-outside": { - "dark": { - "strokeOpacity": 0.94, - "innerOpacity": 0.34, - "bloomOpacity": 0.3, - "innerShadow": "transparent", - "saturation": 1.2, - "brightness": 1.9, - "hairlineOpacity": 0 - }, - "light": { - "strokeOpacity": 1.96, - "innerOpacity": 1.04, - "bloomOpacity": 0.42, - "innerShadow": "transparent", - "saturation": 0.6, - "brightness": 1.7, - "hairlineOpacity": 0 - } - }, - "pulse-inner": { - "dark": { - "strokeOpacity": 1.54, - "innerOpacity": 0.44, - "bloomOpacity": 0.66, - "innerShadow": "transparent", - "saturation": 1.2, - "brightness": 0.75 - }, - "light": { - "strokeOpacity": 0.32, - "innerOpacity": 0.4, - "bloomOpacity": 0.8, - "innerShadow": "transparent", - "saturation": 0.75, - "brightness": 1.3 - } - } - }, - "palettes": { - "border": { - "colorful": { - "border": [ - { - "color": "rgb(255, 50, 100)", - "pos": "33% -7.4%", - "size": "70px 40px" - }, - { - "color": "rgb(40, 140, 255)", - "pos": "12% -5%", - "size": "60px 35px" - }, - { - "color": "rgb(50, 200, 80)", - "pos": "2.1% 68.3%", - "size": "40px 70px" - }, - { - "color": "rgb(30, 185, 170)", - "pos": "2.1% 68.3%", - "size": "20px 35px" - }, - { - "color": "rgb(100, 70, 255)", - "pos": "74.4% 100%", - "size": "180px 32px" - }, - { - "color": "rgb(40, 140, 255)", - "pos": "55% 100%", - "size": "85px 26px" - }, - { - "color": "rgb(255, 120, 40)", - "pos": "93.9% 0%", - "size": "74px 32px" - }, - { - "color": "rgb(240, 50, 180)", - "pos": "100% 27.1%", - "size": "26px 42px" - }, - { - "color": "rgb(180, 40, 240)", - "pos": "100% 27.1%", - "size": "52px 48px" - } - ], - "spike": { - "primary": "rgb(255, 60, 80)", - "secondary": "rgba(40, 190, 180, 0.98)" - }, - "spikeLt": { - "primary": "rgb(200, 30, 60)", - "secondary": "rgb(20, 150, 140)" - } - }, - "mono": { - "border": [ - { - "color": "rgb(180, 180, 180)", - "pos": "33% -7.4%", - "size": "70px 40px" - }, - { - "color": "rgb(140, 140, 140)", - "pos": "12% -5%", - "size": "60px 35px" - }, - { - "color": "rgb(160, 160, 160)", - "pos": "2.1% 68.3%", - "size": "40px 70px" - }, - { - "color": "rgb(130, 130, 130)", - "pos": "2.1% 68.3%", - "size": "20px 35px" - }, - { - "color": "rgb(170, 170, 170)", - "pos": "74.4% 100%", - "size": "180px 32px" - }, - { - "color": "rgb(150, 150, 150)", - "pos": "55% 100%", - "size": "85px 26px" - }, - { - "color": "rgb(190, 190, 190)", - "pos": "93.9% 0%", - "size": "74px 32px" - }, - { - "color": "rgb(145, 145, 145)", - "pos": "100% 27.1%", - "size": "26px 42px" - }, - { - "color": "rgb(165, 165, 165)", - "pos": "100% 27.1%", - "size": "52px 48px" - } - ], - "spike": { - "primary": "rgb(200, 200, 200)", - "secondary": "rgb(170, 170, 170)" - }, - "spikeLt": { - "primary": "rgb(80, 80, 80)", - "secondary": "rgb(120, 120, 120)" - } - }, - "ocean": { - "border": [ - { - "color": "rgb(100, 80, 220)", - "pos": "33% -7.4%", - "size": "70px 40px" - }, - { - "color": "rgb(60, 120, 255)", - "pos": "12% -5%", - "size": "60px 35px" - }, - { - "color": "rgb(80, 100, 200)", - "pos": "2.1% 68.3%", - "size": "40px 70px" - }, - { - "color": "rgb(50, 140, 220)", - "pos": "2.1% 68.3%", - "size": "20px 35px" - }, - { - "color": "rgb(120, 80, 255)", - "pos": "74.4% 100%", - "size": "180px 32px" - }, - { - "color": "rgb(70, 130, 255)", - "pos": "55% 100%", - "size": "85px 26px" - }, - { - "color": "rgb(140, 100, 240)", - "pos": "93.9% 0%", - "size": "74px 32px" - }, - { - "color": "rgb(90, 110, 230)", - "pos": "100% 27.1%", - "size": "26px 42px" - }, - { - "color": "rgb(130, 70, 255)", - "pos": "100% 27.1%", - "size": "52px 48px" - } - ], - "spike": { - "primary": "rgb(100, 120, 255)", - "secondary": "rgba(130, 100, 220, 0.98)" - }, - "spikeLt": { - "primary": "rgb(60, 60, 180)", - "secondary": "rgb(80, 100, 200)" - } - }, - "sunset": { - "border": [ - { - "color": "rgb(255, 80, 50)", - "pos": "33% -7.4%", - "size": "70px 40px" - }, - { - "color": "rgb(255, 160, 40)", - "pos": "12% -5%", - "size": "60px 35px" - }, - { - "color": "rgb(255, 120, 60)", - "pos": "2.1% 68.3%", - "size": "40px 70px" - }, - { - "color": "rgb(255, 200, 50)", - "pos": "2.1% 68.3%", - "size": "20px 35px" - }, - { - "color": "rgb(255, 100, 80)", - "pos": "74.4% 100%", - "size": "180px 32px" - }, - { - "color": "rgb(255, 180, 60)", - "pos": "55% 100%", - "size": "85px 26px" - }, - { - "color": "rgb(255, 60, 60)", - "pos": "93.9% 0%", - "size": "74px 32px" - }, - { - "color": "rgb(255, 140, 50)", - "pos": "100% 27.1%", - "size": "26px 42px" - }, - { - "color": "rgb(255, 90, 70)", - "pos": "100% 27.1%", - "size": "52px 48px" - } - ], - "spike": { - "primary": "rgb(255, 140, 80)", - "secondary": "rgba(255, 100, 60, 0.98)" - }, - "spikeLt": { - "primary": "rgb(200, 80, 40)", - "secondary": "rgb(220, 120, 30)" - } - } - }, - "small": { - "colorful": { - "border": [ - { - "color": "rgb(50, 200, 80)", - "pos": "2% 68%", - "size": "9px 18px" - }, - { - "color": "rgb(30, 185, 170)", - "pos": "2% 68%", - "size": "4px 8px" - }, - { - "color": "rgb(255, 120, 40)", - "pos": "72% -3%", - "size": "59px 9px" - }, - { - "color": "rgb(100, 70, 255)", - "pos": "74% 100%", - "size": "42px 7px" - }, - { - "color": "rgb(240, 50, 180)", - "pos": "100% 27%", - "size": "10px 17px" - }, - { - "color": "rgb(180, 40, 240)", - "pos": "100% 27%", - "size": "10px 18px" - }, - { - "color": "rgb(40, 140, 255)", - "pos": "100% 27%", - "size": "5px 10px" - }, - { - "color": "rgb(255, 50, 100)", - "pos": "100% 27%", - "size": "11px 12px" - } - ], - "inner": [ - { - "color": "rgba(50, 200, 80, 0.5)", - "pos": "2% 68%", - "size": "9px 18px" - }, - { - "color": "rgba(30, 185, 170, 0.45)", - "pos": "2% 68%", - "size": "4px 8px" - }, - { - "color": "rgba(255, 120, 40, 0.35)", - "pos": "72% -3%", - "size": "59px 9px" - }, - { - "color": "rgba(100, 70, 255, 0.35)", - "pos": "74% 100%", - "size": "42px 7px" - }, - { - "color": "rgba(240, 50, 180, 0.3)", - "pos": "100% 27%", - "size": "10px 17px" - }, - { - "color": "rgba(180, 40, 240, 0.4)", - "pos": "100% 27%", - "size": "10px 18px" - }, - { - "color": "rgba(40, 140, 255, 0.3)", - "pos": "100% 27%", - "size": "5px 10px" - }, - { - "color": "rgba(255, 50, 100, 0.3)", - "pos": "100% 27%", - "size": "11px 12px" - } - ] - }, - "mono": { - "border": [ - { - "color": "rgb(160, 160, 160)", - "pos": "2% 68%", - "size": "9px 18px" - }, - { - "color": "rgb(140, 140, 140)", - "pos": "2% 68%", - "size": "4px 8px" - }, - { - "color": "rgb(180, 180, 180)", - "pos": "72% -3%", - "size": "59px 9px" - }, - { - "color": "rgb(150, 150, 150)", - "pos": "74% 100%", - "size": "42px 7px" - }, - { - "color": "rgb(170, 170, 170)", - "pos": "100% 27%", - "size": "10px 17px" - }, - { - "color": "rgb(155, 155, 155)", - "pos": "100% 27%", - "size": "10px 18px" - }, - { - "color": "rgb(145, 145, 145)", - "pos": "100% 27%", - "size": "5px 10px" - }, - { - "color": "rgb(165, 165, 165)", - "pos": "100% 27%", - "size": "11px 12px" - } - ], - "inner": [ - { - "color": "rgba(160, 160, 160, 0.25)", - "pos": "2% 68%", - "size": "9px 18px" - }, - { - "color": "rgba(140, 140, 140, 0.22)", - "pos": "2% 68%", - "size": "4px 8px" - }, - { - "color": "rgba(180, 180, 180, 0.17)", - "pos": "72% -3%", - "size": "59px 9px" - }, - { - "color": "rgba(150, 150, 150, 0.17)", - "pos": "74% 100%", - "size": "42px 7px" - }, - { - "color": "rgba(170, 170, 170, 0.15)", - "pos": "100% 27%", - "size": "10px 17px" - }, - { - "color": "rgba(155, 155, 155, 0.20)", - "pos": "100% 27%", - "size": "10px 18px" - }, - { - "color": "rgba(145, 145, 145, 0.15)", - "pos": "100% 27%", - "size": "5px 10px" - }, - { - "color": "rgba(165, 165, 165, 0.15)", - "pos": "100% 27%", - "size": "11px 12px" - } - ] - }, - "ocean": { - "border": [ - { - "color": "rgb(60, 140, 200)", - "pos": "2% 68%", - "size": "9px 18px" - }, - { - "color": "rgb(50, 120, 180)", - "pos": "2% 68%", - "size": "4px 8px" - }, - { - "color": "rgb(100, 80, 220)", - "pos": "72% -3%", - "size": "59px 9px" - }, - { - "color": "rgb(80, 100, 255)", - "pos": "74% 100%", - "size": "42px 7px" - }, - { - "color": "rgb(120, 70, 240)", - "pos": "100% 27%", - "size": "10px 17px" - }, - { - "color": "rgb(90, 80, 220)", - "pos": "100% 27%", - "size": "10px 18px" - }, - { - "color": "rgb(70, 110, 255)", - "pos": "100% 27%", - "size": "5px 10px" - }, - { - "color": "rgb(110, 90, 230)", - "pos": "100% 27%", - "size": "11px 12px" - } - ], - "inner": [ - { - "color": "rgba(60, 140, 200, 0.5)", - "pos": "2% 68%", - "size": "9px 18px" - }, - { - "color": "rgba(50, 120, 180, 0.45)", - "pos": "2% 68%", - "size": "4px 8px" - }, - { - "color": "rgba(100, 80, 220, 0.35)", - "pos": "72% -3%", - "size": "59px 9px" - }, - { - "color": "rgba(80, 100, 255, 0.35)", - "pos": "74% 100%", - "size": "42px 7px" - }, - { - "color": "rgba(120, 70, 240, 0.3)", - "pos": "100% 27%", - "size": "10px 17px" - }, - { - "color": "rgba(90, 80, 220, 0.4)", - "pos": "100% 27%", - "size": "10px 18px" - }, - { - "color": "rgba(70, 110, 255, 0.3)", - "pos": "100% 27%", - "size": "5px 10px" - }, - { - "color": "rgba(110, 90, 230, 0.3)", - "pos": "100% 27%", - "size": "11px 12px" - } - ] - }, - "sunset": { - "border": [ - { - "color": "rgb(255, 180, 50)", - "pos": "2% 68%", - "size": "9px 18px" - }, - { - "color": "rgb(255, 150, 40)", - "pos": "2% 68%", - "size": "4px 8px" - }, - { - "color": "rgb(255, 80, 60)", - "pos": "72% -3%", - "size": "59px 9px" - }, - { - "color": "rgb(255, 100, 80)", - "pos": "74% 100%", - "size": "42px 7px" - }, - { - "color": "rgb(255, 60, 80)", - "pos": "100% 27%", - "size": "10px 17px" - }, - { - "color": "rgb(255, 120, 60)", - "pos": "100% 27%", - "size": "10px 18px" - }, - { - "color": "rgb(255, 200, 50)", - "pos": "100% 27%", - "size": "5px 10px" - }, - { - "color": "rgb(255, 90, 70)", - "pos": "100% 27%", - "size": "11px 12px" - } - ], - "inner": [ - { - "color": "rgba(255, 180, 50, 0.5)", - "pos": "2% 68%", - "size": "9px 18px" - }, - { - "color": "rgba(255, 150, 40, 0.45)", - "pos": "2% 68%", - "size": "4px 8px" - }, - { - "color": "rgba(255, 80, 60, 0.35)", - "pos": "72% -3%", - "size": "59px 9px" - }, - { - "color": "rgba(255, 100, 80, 0.35)", - "pos": "74% 100%", - "size": "42px 7px" - }, - { - "color": "rgba(255, 60, 80, 0.3)", - "pos": "100% 27%", - "size": "10px 17px" - }, - { - "color": "rgba(255, 120, 60, 0.4)", - "pos": "100% 27%", - "size": "10px 18px" - }, - { - "color": "rgba(255, 200, 50, 0.3)", - "pos": "100% 27%", - "size": "5px 10px" - }, - { - "color": "rgba(255, 90, 70, 0.3)", - "pos": "100% 27%", - "size": "11px 12px" - } - ] - } - }, - "line": { - "colorful": { - "dark": [ - { - "color": "rgb(255, 50, 100)", - "sizeW": 36, - "sizeH": 36, - "offsetX": 0, - "offsetY": 2 - }, - { - "color": "rgb(40, 180, 220)", - "sizeW": 30, - "sizeH": 32, - "offsetX": 39, - "offsetY": 0 - }, - { - "color": "rgb(50, 200, 80)", - "sizeW": 33, - "sizeH": 28, - "offsetX": -36, - "offsetY": 2 - }, - { - "color": "rgb(180, 40, 240)", - "sizeW": 29, - "sizeH": 34, - "offsetX": -54, - "offsetY": 0 - }, - { - "color": "rgb(255, 160, 30)", - "sizeW": 27, - "sizeH": 30, - "offsetX": 51, - "offsetY": -1 - }, - { - "color": "rgb(100, 70, 255)", - "sizeW": 36, - "sizeH": 24, - "offsetX": 21, - "offsetY": 1 - }, - { - "color": "rgb(40, 140, 255)", - "sizeW": 30, - "sizeH": 22, - "offsetX": -21, - "offsetY": 0 - }, - { - "color": "rgb(240, 50, 180)", - "sizeW": 25, - "sizeH": 28, - "offsetX": 66, - "offsetY": 1 - }, - { - "color": "rgb(30, 185, 170)", - "sizeW": 23, - "sizeH": 30, - "offsetX": -66, - "offsetY": -1 - } - ], - "light": [ - { - "color": "rgb(255, 50, 100)", - "sizeW": 45, - "sizeH": 36, - "offsetX": 0, - "offsetY": 2 - }, - { - "color": "rgb(40, 140, 255)", - "sizeW": 35, - "sizeH": 32, - "offsetX": 65, - "offsetY": 0 - }, - { - "color": "rgb(50, 200, 80)", - "sizeW": 40, - "sizeH": 28, - "offsetX": -60, - "offsetY": 2 - }, - { - "color": "rgb(180, 40, 240)", - "sizeW": 35, - "sizeH": 34, - "offsetX": -90, - "offsetY": 0 - }, - { - "color": "rgb(30, 185, 170)", - "sizeW": 38, - "sizeH": 30, - "offsetX": 85, - "offsetY": -1 - }, - { - "color": "rgb(100, 70, 255)", - "sizeW": 50, - "sizeH": 24, - "offsetX": 35, - "offsetY": 1 - }, - { - "color": "rgb(40, 140, 255)", - "sizeW": 40, - "sizeH": 22, - "offsetX": -35, - "offsetY": 0 - }, - { - "color": "rgb(255, 120, 40)", - "sizeW": 35, - "sizeH": 28, - "offsetX": 110, - "offsetY": 1 - }, - { - "color": "rgb(240, 50, 180)", - "sizeW": 30, - "sizeH": 30, - "offsetX": -110, - "offsetY": -1 - } - ] - }, - "mono": { - "dark": [ - { - "color": "rgb(200, 200, 200)", - "sizeW": 36, - "sizeH": 36, - "offsetX": 0, - "offsetY": 2 - }, - { - "color": "rgb(170, 170, 170)", - "sizeW": 30, - "sizeH": 32, - "offsetX": 39, - "offsetY": 0 - }, - { - "color": "rgb(155, 155, 155)", - "sizeW": 33, - "sizeH": 28, - "offsetX": -36, - "offsetY": 2 - }, - { - "color": "rgb(185, 185, 185)", - "sizeW": 29, - "sizeH": 34, - "offsetX": -54, - "offsetY": 0 - }, - { - "color": "rgb(165, 165, 165)", - "sizeW": 27, - "sizeH": 30, - "offsetX": 51, - "offsetY": -1 - }, - { - "color": "rgb(180, 180, 180)", - "sizeW": 36, - "sizeH": 24, - "offsetX": 21, - "offsetY": 1 - }, - { - "color": "rgb(160, 160, 160)", - "sizeW": 30, - "sizeH": 22, - "offsetX": -21, - "offsetY": 0 - }, - { - "color": "rgb(175, 175, 175)", - "sizeW": 25, - "sizeH": 28, - "offsetX": 66, - "offsetY": 1 - }, - { - "color": "rgb(190, 190, 190)", - "sizeW": 23, - "sizeH": 30, - "offsetX": -66, - "offsetY": -1 - } - ], - "light": [ - { - "color": "rgb(100, 100, 100)", - "sizeW": 45, - "sizeH": 36, - "offsetX": 0, - "offsetY": 2 - }, - { - "color": "rgb(80, 80, 80)", - "sizeW": 35, - "sizeH": 32, - "offsetX": 65, - "offsetY": 0 - }, - { - "color": "rgb(90, 90, 90)", - "sizeW": 40, - "sizeH": 28, - "offsetX": -60, - "offsetY": 2 - }, - { - "color": "rgb(70, 70, 70)", - "sizeW": 35, - "sizeH": 34, - "offsetX": -90, - "offsetY": 0 - }, - { - "color": "rgb(85, 85, 85)", - "sizeW": 38, - "sizeH": 30, - "offsetX": 85, - "offsetY": -1 - }, - { - "color": "rgb(95, 95, 95)", - "sizeW": 50, - "sizeH": 24, - "offsetX": 35, - "offsetY": 1 - }, - { - "color": "rgb(75, 75, 75)", - "sizeW": 40, - "sizeH": 22, - "offsetX": -35, - "offsetY": 0 - }, - { - "color": "rgb(105, 105, 105)", - "sizeW": 35, - "sizeH": 28, - "offsetX": 110, - "offsetY": 1 - }, - { - "color": "rgb(65, 65, 65)", - "sizeW": 30, - "sizeH": 30, - "offsetX": -110, - "offsetY": -1 - } - ] - }, - "ocean": { - "dark": [ - { - "color": "rgb(100, 80, 220)", - "sizeW": 36, - "sizeH": 36, - "offsetX": 0, - "offsetY": 2 - }, - { - "color": "rgb(60, 120, 255)", - "sizeW": 30, - "sizeH": 32, - "offsetX": 39, - "offsetY": 0 - }, - { - "color": "rgb(80, 100, 200)", - "sizeW": 33, - "sizeH": 28, - "offsetX": -36, - "offsetY": 2 - }, - { - "color": "rgb(130, 70, 255)", - "sizeW": 29, - "sizeH": 34, - "offsetX": -54, - "offsetY": 0 - }, - { - "color": "rgb(70, 130, 255)", - "sizeW": 27, - "sizeH": 30, - "offsetX": 51, - "offsetY": -1 - }, - { - "color": "rgb(120, 80, 255)", - "sizeW": 36, - "sizeH": 24, - "offsetX": 21, - "offsetY": 1 - }, - { - "color": "rgb(90, 110, 230)", - "sizeW": 30, - "sizeH": 22, - "offsetX": -21, - "offsetY": 0 - }, - { - "color": "rgb(110, 90, 240)", - "sizeW": 25, - "sizeH": 28, - "offsetX": 66, - "offsetY": 1 - }, - { - "color": "rgb(140, 100, 255)", - "sizeW": 23, - "sizeH": 30, - "offsetX": -66, - "offsetY": -1 - } - ], - "light": [ - { - "color": "rgb(80, 60, 200)", - "sizeW": 45, - "sizeH": 36, - "offsetX": 0, - "offsetY": 2 - }, - { - "color": "rgb(50, 100, 220)", - "sizeW": 35, - "sizeH": 32, - "offsetX": 65, - "offsetY": 0 - }, - { - "color": "rgb(70, 90, 190)", - "sizeW": 40, - "sizeH": 28, - "offsetX": -60, - "offsetY": 2 - }, - { - "color": "rgb(110, 60, 220)", - "sizeW": 35, - "sizeH": 34, - "offsetX": -90, - "offsetY": 0 - }, - { - "color": "rgb(60, 110, 230)", - "sizeW": 38, - "sizeH": 30, - "offsetX": 85, - "offsetY": -1 - }, - { - "color": "rgb(100, 70, 240)", - "sizeW": 50, - "sizeH": 24, - "offsetX": 35, - "offsetY": 1 - }, - { - "color": "rgb(80, 100, 210)", - "sizeW": 40, - "sizeH": 22, - "offsetX": -35, - "offsetY": 0 - }, - { - "color": "rgb(90, 80, 225)", - "sizeW": 35, - "sizeH": 28, - "offsetX": 110, - "offsetY": 1 - }, - { - "color": "rgb(120, 90, 245)", - "sizeW": 30, - "sizeH": 30, - "offsetX": -110, - "offsetY": -1 - } - ] - }, - "sunset": { - "dark": [ - { - "color": "rgb(255, 100, 60)", - "sizeW": 36, - "sizeH": 36, - "offsetX": 0, - "offsetY": 2 - }, - { - "color": "rgb(255, 180, 50)", - "sizeW": 30, - "sizeH": 32, - "offsetX": 39, - "offsetY": 0 - }, - { - "color": "rgb(255, 140, 70)", - "sizeW": 33, - "sizeH": 28, - "offsetX": -36, - "offsetY": 2 - }, - { - "color": "rgb(255, 80, 80)", - "sizeW": 29, - "sizeH": 34, - "offsetX": -54, - "offsetY": 0 - }, - { - "color": "rgb(255, 200, 60)", - "sizeW": 27, - "sizeH": 30, - "offsetX": 51, - "offsetY": -1 - }, - { - "color": "rgb(255, 120, 50)", - "sizeW": 36, - "sizeH": 24, - "offsetX": 21, - "offsetY": 1 - }, - { - "color": "rgb(255, 160, 80)", - "sizeW": 30, - "sizeH": 22, - "offsetX": -21, - "offsetY": 0 - }, - { - "color": "rgb(255, 90, 60)", - "sizeW": 25, - "sizeH": 28, - "offsetX": 66, - "offsetY": 1 - }, - { - "color": "rgb(255, 70, 70)", - "sizeW": 23, - "sizeH": 30, - "offsetX": -66, - "offsetY": -1 - } - ], - "light": [ - { - "color": "rgb(220, 80, 40)", - "sizeW": 45, - "sizeH": 36, - "offsetX": 0, - "offsetY": 2 - }, - { - "color": "rgb(230, 150, 30)", - "sizeW": 35, - "sizeH": 32, - "offsetX": 65, - "offsetY": 0 - }, - { - "color": "rgb(210, 110, 50)", - "sizeW": 40, - "sizeH": 28, - "offsetX": -60, - "offsetY": 2 - }, - { - "color": "rgb(200, 60, 60)", - "sizeW": 35, - "sizeH": 34, - "offsetX": -90, - "offsetY": 0 - }, - { - "color": "rgb(220, 170, 40)", - "sizeW": 38, - "sizeH": 30, - "offsetX": 85, - "offsetY": -1 - }, - { - "color": "rgb(210, 100, 30)", - "sizeW": 50, - "sizeH": 24, - "offsetX": 35, - "offsetY": 1 - }, - { - "color": "rgb(230, 130, 60)", - "sizeW": 40, - "sizeH": 22, - "offsetX": -35, - "offsetY": 0 - }, - { - "color": "rgb(190, 70, 50)", - "sizeW": 35, - "sizeH": 28, - "offsetX": 110, - "offsetY": 1 - }, - { - "color": "rgb(180, 50, 50)", - "sizeW": 30, - "sizeH": 30, - "offsetX": -110, - "offsetY": -1 - } - ] - } - }, - "lineInner": { - "colorful": [ - { - "color": "rgba(255, 50, 100, 0.48)", - "sizeW": 33, - "sizeH": 30, - "offsetX": 0, - "offsetY": 0 - }, - { - "color": "rgba(40, 180, 220, 0.42)", - "sizeW": 24, - "sizeH": 26, - "offsetX": 39, - "offsetY": -3 - }, - { - "color": "rgba(50, 200, 80, 0.48)", - "sizeW": 27, - "sizeH": 24, - "offsetX": -36, - "offsetY": 0 - }, - { - "color": "rgba(180, 40, 240, 0.42)", - "sizeW": 23, - "sizeH": 28, - "offsetX": -54, - "offsetY": -2 - }, - { - "color": "rgba(255, 160, 30, 0.50)", - "sizeW": 24, - "sizeH": 24, - "offsetX": 51, - "offsetY": -1 - }, - { - "color": "rgba(100, 70, 255, 0.45)", - "sizeW": 30, - "sizeH": 20, - "offsetX": 21, - "offsetY": 0 - }, - { - "color": "rgba(40, 140, 255, 0.40)", - "sizeW": 25, - "sizeH": 18, - "offsetX": -21, - "offsetY": -2 - }, - { - "color": "rgba(240, 50, 180, 0.45)", - "sizeW": 21, - "sizeH": 24, - "offsetX": 66, - "offsetY": 0 - }, - { - "color": "rgba(30, 185, 170, 0.52)", - "sizeW": 18, - "sizeH": 26, - "offsetX": -66, - "offsetY": -1 - } - ], - "mono": [ - { - "color": "rgba(200, 200, 200, 0.48)", - "sizeW": 33, - "sizeH": 30, - "offsetX": 0, - "offsetY": 0 - }, - { - "color": "rgba(170, 170, 170, 0.42)", - "sizeW": 24, - "sizeH": 26, - "offsetX": 39, - "offsetY": -3 - }, - { - "color": "rgba(155, 155, 155, 0.48)", - "sizeW": 27, - "sizeH": 24, - "offsetX": -36, - "offsetY": 0 - }, - { - "color": "rgba(185, 185, 185, 0.42)", - "sizeW": 23, - "sizeH": 28, - "offsetX": -54, - "offsetY": -2 - }, - { - "color": "rgba(165, 165, 165, 0.50)", - "sizeW": 24, - "sizeH": 24, - "offsetX": 51, - "offsetY": -1 - }, - { - "color": "rgba(180, 180, 180, 0.45)", - "sizeW": 30, - "sizeH": 20, - "offsetX": 21, - "offsetY": 0 - }, - { - "color": "rgba(160, 160, 160, 0.40)", - "sizeW": 25, - "sizeH": 18, - "offsetX": -21, - "offsetY": -2 - }, - { - "color": "rgba(175, 175, 175, 0.45)", - "sizeW": 21, - "sizeH": 24, - "offsetX": 66, - "offsetY": 0 - }, - { - "color": "rgba(190, 190, 190, 0.52)", - "sizeW": 18, - "sizeH": 26, - "offsetX": -66, - "offsetY": -1 - } - ], - "ocean": [ - { - "color": "rgba(100, 80, 220, 0.48)", - "sizeW": 33, - "sizeH": 30, - "offsetX": 0, - "offsetY": 0 - }, - { - "color": "rgba(60, 120, 255, 0.42)", - "sizeW": 24, - "sizeH": 26, - "offsetX": 39, - "offsetY": -3 - }, - { - "color": "rgba(80, 100, 200, 0.48)", - "sizeW": 27, - "sizeH": 24, - "offsetX": -36, - "offsetY": 0 - }, - { - "color": "rgba(130, 70, 255, 0.42)", - "sizeW": 23, - "sizeH": 28, - "offsetX": -54, - "offsetY": -2 - }, - { - "color": "rgba(70, 130, 255, 0.50)", - "sizeW": 24, - "sizeH": 24, - "offsetX": 51, - "offsetY": -1 - }, - { - "color": "rgba(120, 80, 255, 0.45)", - "sizeW": 30, - "sizeH": 20, - "offsetX": 21, - "offsetY": 0 - }, - { - "color": "rgba(90, 110, 230, 0.40)", - "sizeW": 25, - "sizeH": 18, - "offsetX": -21, - "offsetY": -2 - }, - { - "color": "rgba(110, 90, 240, 0.45)", - "sizeW": 21, - "sizeH": 24, - "offsetX": 66, - "offsetY": 0 - }, - { - "color": "rgba(140, 100, 255, 0.52)", - "sizeW": 18, - "sizeH": 26, - "offsetX": -66, - "offsetY": -1 - } - ], - "sunset": [ - { - "color": "rgba(255, 100, 60, 0.48)", - "sizeW": 33, - "sizeH": 30, - "offsetX": 0, - "offsetY": 0 - }, - { - "color": "rgba(255, 180, 50, 0.42)", - "sizeW": 24, - "sizeH": 26, - "offsetX": 39, - "offsetY": -3 - }, - { - "color": "rgba(255, 140, 70, 0.48)", - "sizeW": 27, - "sizeH": 24, - "offsetX": -36, - "offsetY": 0 - }, - { - "color": "rgba(255, 80, 80, 0.42)", - "sizeW": 23, - "sizeH": 28, - "offsetX": -54, - "offsetY": -2 - }, - { - "color": "rgba(255, 200, 60, 0.50)", - "sizeW": 24, - "sizeH": 24, - "offsetX": 51, - "offsetY": -1 - }, - { - "color": "rgba(255, 120, 50, 0.45)", - "sizeW": 30, - "sizeH": 20, - "offsetX": 21, - "offsetY": 0 - }, - { - "color": "rgba(255, 160, 80, 0.40)", - "sizeW": 25, - "sizeH": 18, - "offsetX": -21, - "offsetY": -2 - }, - { - "color": "rgba(255, 90, 60, 0.45)", - "sizeW": 21, - "sizeH": 24, - "offsetX": 66, - "offsetY": 0 - }, - { - "color": "rgba(255, 70, 70, 0.52)", - "sizeW": 18, - "sizeH": 26, - "offsetX": -66, - "offsetY": -1 - } - ] - }, - "lineBloom": { - "colorful": { - "dark": { - "spikes": [ - { - "color1": "rgb(100, 70, 255)", - "color2": "rgba(100, 70, 255, 1)" - }, - { - "color1": "rgba(255, 170, 40, 0.59)", - "color2": "rgba(255, 170, 40, 0.29)" - }, - { - "color1": "rgb(50, 200, 100)", - "color2": "rgba(50, 200, 100, 1)" - }, - { - "color1": "rgba(200, 50, 240, 0.91)", - "color2": "rgba(200, 50, 240, 0.45)" - }, - { - "color1": "rgb(40, 140, 255)", - "color2": "rgba(40, 140, 255, 1)" - } - ] - }, - "light": { - "spikes": [ - { - "color1": "rgb(80, 50, 200)", - "color2": "rgba(80, 50, 200, 0.8)" - }, - { - "color1": "rgba(210, 130, 0, 0.7)", - "color2": "rgba(210, 130, 0, 0.46)" - }, - { - "color1": "rgb(30, 160, 70)", - "color2": "rgba(30, 160, 70, 0.82)" - }, - { - "color1": "rgb(160, 30, 190)", - "color2": "rgba(160, 30, 190, 0.7)" - }, - { - "color1": "rgb(30, 100, 200)", - "color2": "rgba(30, 100, 200, 0.78)" - } - ] - } - }, - "mono": { - "dark": { - "spikes": [ - { - "color1": "rgb(200, 200, 200)", - "color2": "rgba(200, 200, 200, 1)" - }, - { - "color1": "rgba(180, 180, 180, 0.59)", - "color2": "rgba(180, 180, 180, 0.29)" - }, - { - "color1": "rgb(190, 190, 190)", - "color2": "rgba(190, 190, 190, 1)" - }, - { - "color1": "rgba(170, 170, 170, 0.91)", - "color2": "rgba(170, 170, 170, 0.45)" - }, - { - "color1": "rgb(185, 185, 185)", - "color2": "rgba(185, 185, 185, 1)" - } - ] - }, - "light": { - "spikes": [ - { - "color1": "rgb(80, 80, 80)", - "color2": "rgba(80, 80, 80, 0.8)" - }, - { - "color1": "rgba(100, 100, 100, 0.7)", - "color2": "rgba(100, 100, 100, 0.46)" - }, - { - "color1": "rgb(70, 70, 70)", - "color2": "rgba(70, 70, 70, 0.82)" - }, - { - "color1": "rgb(90, 90, 90)", - "color2": "rgba(90, 90, 90, 0.7)" - }, - { - "color1": "rgb(85, 85, 85)", - "color2": "rgba(85, 85, 85, 0.78)" - } - ] - } - }, - "ocean": { - "dark": { - "spikes": [ - { - "color1": "rgb(100, 80, 255)", - "color2": "rgb(100, 80, 255)" - }, - { - "color1": "rgba(80, 130, 220, 0.59)", - "color2": "rgba(80, 130, 220, 0.29)" - }, - { - "color1": "rgb(60, 100, 255)", - "color2": "rgb(60, 100, 255)" - }, - { - "color1": "rgba(90, 120, 200, 0.91)", - "color2": "rgba(90, 120, 200, 0.45)" - }, - { - "color1": "rgb(120, 90, 255)", - "color2": "rgb(120, 90, 255)" - } - ] - }, - "light": { - "spikes": [ - { - "color1": "rgb(50, 40, 180)", - "color2": "rgba(50, 40, 180, 0.8)" - }, - { - "color1": "rgba(40, 80, 200, 0.7)", - "color2": "rgba(40, 80, 200, 0.46)" - }, - { - "color1": "rgb(30, 50, 190)", - "color2": "rgba(30, 50, 190, 0.82)" - }, - { - "color1": "rgb(60, 90, 180)", - "color2": "rgba(60, 90, 180, 0.7)" - }, - { - "color1": "rgb(70, 60, 200)", - "color2": "rgba(70, 60, 200, 0.78)" - } - ] - } - }, - "sunset": { - "dark": { - "spikes": [ - { - "color1": "rgb(255, 100, 80)", - "color2": "rgb(255, 100, 80)" - }, - { - "color1": "rgba(255, 150, 80, 0.59)", - "color2": "rgba(255, 150, 80, 0.29)" - }, - { - "color1": "rgb(255, 80, 60)", - "color2": "rgb(255, 80, 60)" - }, - { - "color1": "rgba(255, 120, 50, 0.91)", - "color2": "rgba(255, 120, 50, 0.45)" - }, - { - "color1": "rgb(255, 140, 70)", - "color2": "rgb(255, 140, 70)" - } - ] - }, - "light": { - "spikes": [ - { - "color1": "rgb(200, 60, 30)", - "color2": "rgba(200, 60, 30, 0.8)" - }, - { - "color1": "rgba(220, 100, 20, 0.7)", - "color2": "rgba(220, 100, 20, 0.46)" - }, - { - "color1": "rgb(180, 40, 20)", - "color2": "rgba(180, 40, 20, 0.82)" - }, - { - "color1": "rgb(210, 80, 10)", - "color2": "rgba(210, 80, 10, 0.7)" - }, - { - "color1": "rgb(190, 70, 30)", - "color2": "rgba(190, 70, 30, 0.78)" - } - ] - } - } - } - }, - "rotate": { - "whiteGradientStops": { - "dark": [ - [ - 0, - 0 - ], - [ - 54, - 0 - ], - [ - 57, - 0.1 - ], - [ - 60, - 0.3 - ], - [ - 63, - 0.6 - ], - [ - 66, - 0.75 - ], - [ - 69, - 0.6 - ], - [ - 72, - 0.3 - ], - [ - 75, - 0.1 - ], - [ - 78, - 0 - ], - [ - 100, - 0 - ] - ], - "light": [ - [ - 0, - 0 - ], - [ - 54, - 0 - ], - [ - 57, - 0.08 - ], - [ - 60, - 0.2 - ], - [ - 63, - 0.4 - ], - [ - 66, - 0.55 - ], - [ - 69, - 0.4 - ], - [ - 72, - 0.2 - ], - [ - 75, - 0.08 - ], - [ - 78, - 0 - ], - [ - 100, - 0 - ] - ] - }, - "bloomGradientStops": { - "dark": [ - [ - 0, - 0 - ], - [ - 58, - 0 - ], - [ - 62, - 0.03 - ], - [ - 65, - 0.08 - ], - [ - 67, - 0.2 - ], - [ - 69, - 0.45 - ], - [ - 70, - 0.85 - ], - [ - 70.5, - 0.85 - ], - [ - 71.5, - 0.45 - ], - [ - 73, - 0.2 - ], - [ - 75, - 0.08 - ], - [ - 78, - 0.03 - ], - [ - 82, - 0 - ] - ], - "light": [ - [ - 0, - 0 - ], - [ - 58, - 0 - ], - [ - 62, - 0.02 - ], - [ - 65, - 0.08 - ], - [ - 67, - 0.2 - ], - [ - 69, - 0.4 - ], - [ - 70, - 0.6 - ], - [ - 70.5, - 0.6 - ], - [ - 71.5, - 0.4 - ], - [ - 73, - 0.2 - ], - [ - 75, - 0.08 - ], - [ - 78, - 0.02 - ], - [ - 82, - 0 - ] - ] - }, - "beamMaskStops": [ - [ - 0, - 0 - ], - [ - 30, - 0 - ], - [ - 36, - 0.1 - ], - [ - 44, - 0.35 - ], - [ - 52, - 1 - ], - [ - 80, - 1 - ], - [ - 86, - 0.35 - ], - [ - 92, - 0.1 - ], - [ - 95, - 0 - ], - [ - 100, - 0 - ] - ], - "smallMaskStops": [ - [ - 0, - 0 - ], - [ - 22, - 0 - ], - [ - 28, - 0.12 - ], - [ - 36, - 0.4 - ], - [ - 46, - 1 - ], - [ - 82, - 1 - ], - [ - 88, - 0.4 - ], - [ - 94, - 0.12 - ], - [ - 97, - 0 - ], - [ - 100, - 0 - ] - ], - "innerGradientDerivation": { - "sizeScale": 0.9, - "alpha": 0.45, - "monoAlpha": 0.225 - }, - "innerEdgeMaskPx": 28, - "innerShadowBlur": { - "md": 9, - "sm": 5 - }, - "bloomBlurPx": 8, - "spin": { - "from": 0, - "to": 360, - "easing": "linear" - } - }, - "line": { - "keyframes": { - "travel": { - "x": [ - [ - 0, - 0.06 - ], - [ - 10, - 0.15 - ], - [ - 20, - 0.25 - ], - [ - 30, - 0.35 - ], - [ - 40, - 0.44 - ], - [ - 50, - 0.5 - ], - [ - 60, - 0.56 - ], - [ - 70, - 0.65 - ], - [ - 80, - 0.75 - ], - [ - 90, - 0.85 - ], - [ - 100, - 0.94 - ] - ], - "w": [ - [ - 0, - 0.5 - ], - [ - 10, - 0.8 - ], - [ - 20, - 1.1 - ], - [ - 30, - 1.3 - ], - [ - 40, - 1.45 - ], - [ - 50, - 1.5 - ], - [ - 60, - 1.45 - ], - [ - 70, - 1.3 - ], - [ - 80, - 1.1 - ], - [ - 90, - 0.8 - ], - [ - 100, - 0.5 - ] - ] - }, - "edgeFade": [ - [ - 0, - 0 - ], - [ - 12.5, - 0 - ], - [ - 32.5, - 1 - ], - [ - 67.5, - 1 - ], - [ - 87.5, - 0 - ], - [ - 100, - 0 - ] - ], - "breathe": [ - [ - 0, - 0.8 - ], - [ - 25, - 1.25 - ], - [ - 55, - 0.85 - ], - [ - 80, - 1.3 - ], - [ - 100, - 0.8 - ] - ], - "spike": [ - [ - 0, - 0.8 - ], - [ - 25, - 1.3 - ], - [ - 50, - 0.9 - ], - [ - 75, - 1.4 - ], - [ - 100, - 0.8 - ] - ], - "spike2": [ - [ - 0, - 1.2 - ], - [ - 25, - 0.7 - ], - [ - 50, - 1.4 - ], - [ - 75, - 0.8 - ], - [ - 100, - 1.2 - ] - ], - "durationScale": { - "travel": 1, - "edgeFade": 1, - "breathe": 1.3, - "spike": 1.33, - "spike2": 1.7 - }, - "easing": { - "travel": "linear", - "edgeFade": "linear", - "breathe": "easeInOut", - "spike": "easeInOut", - "spike2": "easeInOut" - } - }, - "beamMaskEllipse": { - "w": 78, - "h": 60, - "softStop": [ - 45, - 0.5 - ] - }, - "bloomMaskEllipse": { - "w": 84, - "h": 110, - "softStop": [ - 35, - 0.5 - ] - }, - "whiteHighlight": { - "dark": { - "w": 24, - "h": 28, - "yOffset": 2, - "stops": [ - [ - 0, - 0.38 - ], - [ - 30, - 0.12 - ], - [ - 65, - 0 - ] - ] - }, - "light": { - "w": 35, - "h": 28, - "yOffset": 2, - "stops": [ - [ - 0, - 0.6 - ], - [ - 35, - 0.25 - ], - [ - 70, - 0 - ] - ], - "onBlack": true - } - }, - "bloomGradients": { - "colorful": { - "dark": [ - { - "xPct": 8, - "yOffPx": -2, - "w": { - "base": 0.8, - "mult": "spike" - }, - "h": { - "base": 92, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 60, - "b": 80, - "a": 1, - "pos": 0 - }, - { - "r": 255, - "g": 60, - "b": 80, - "a": 1, - "pos": 0.3 - }, - { - "r": 255, - "g": 60, - "b": 80, - "a": 0, - "pos": 0.88 - } - ] - }, - { - "xPct": 22, - "yOffPx": -4, - "w": { - "base": 10, - "mult": "spike2" - }, - "h": { - "base": 35, - "mult": "h" - }, - "stops": [ - { - "r": 40, - "g": 190, - "b": 180, - "a": 0.98, - "pos": 0 - }, - { - "r": 40, - "g": 190, - "b": 180, - "a": 0.49, - "pos": 0.5 - }, - { - "r": 40, - "g": 190, - "b": 180, - "a": 0, - "pos": 0.95 - } - ] - }, - { - "xPct": 36, - "yOffPx": -3, - "w": { - "base": 2, - "mult": "inv-spike" - }, - "h": { - "base": 72, - "mult": "h" - }, - "stops": [ - { - "r": 100, - "g": 70, - "b": 255, - "a": 1, - "pos": 0 - }, - { - "r": 100, - "g": 70, - "b": 255, - "a": 1, - "pos": 0.4 - }, - { - "r": 100, - "g": 70, - "b": 255, - "a": 0, - "pos": 0.9 - } - ] - }, - { - "xPct": 50, - "yOffPx": -2, - "w": { - "base": 14, - "mult": "spike2" - }, - "h": { - "base": 28, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 170, - "b": 40, - "a": 0.59, - "pos": 0 - }, - { - "r": 255, - "g": 170, - "b": 40, - "a": 0.29, - "pos": 0.55 - }, - { - "r": 255, - "g": 170, - "b": 40, - "a": 0, - "pos": 0.96 - } - ] - }, - { - "xPct": 64, - "yOffPx": -4, - "w": { - "base": 1.2, - "mult": "inv-spike2" - }, - "h": { - "base": 85, - "mult": "h" - }, - "stops": [ - { - "r": 50, - "g": 200, - "b": 100, - "a": 1, - "pos": 0 - }, - { - "r": 50, - "g": 200, - "b": 100, - "a": 1, - "pos": 0.35 - }, - { - "r": 50, - "g": 200, - "b": 100, - "a": 0, - "pos": 0.89 - } - ] - }, - { - "xPct": 78, - "yOffPx": -2, - "w": { - "base": 7, - "mult": "spike" - }, - "h": { - "base": 45, - "mult": "h" - }, - "stops": [ - { - "r": 200, - "g": 50, - "b": 240, - "a": 0.91, - "pos": 0 - }, - { - "r": 200, - "g": 50, - "b": 240, - "a": 0.45, - "pos": 0.48 - }, - { - "r": 200, - "g": 50, - "b": 240, - "a": 0, - "pos": 0.94 - } - ] - }, - { - "xPct": 92, - "yOffPx": -3, - "w": { - "base": 0.6, - "mult": "inv-spike" - }, - "h": { - "base": 60, - "mult": "h" - }, - "stops": [ - { - "r": 40, - "g": 140, - "b": 255, - "a": 1, - "pos": 0 - }, - { - "r": 40, - "g": 140, - "b": 255, - "a": 1, - "pos": 0.42 - }, - { - "r": 40, - "g": 140, - "b": 255, - "a": 0, - "pos": 0.91 - } - ] - }, - { - "xPct": null, - "yOffPx": 1, - "w": { - "base": 21, - "mult": "spike" - }, - "h": { - "base": 15, - "mult": "spike2" - }, - "stops": [ - { - "r": 255, - "g": 255, - "b": 255, - "a": 1, - "pos": 0 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.9, - "pos": 0.2 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.5, - "pos": 0.5 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0, - "pos": 1 - } - ] - }, - { - "xPct": null, - "yOffPx": 0, - "w": { - "base": 42, - "mult": "w" - }, - "h": { - "base": 40, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.3, - "pos": 0 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.12, - "pos": 0.25 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.03, - "pos": 0.55 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0, - "pos": 0.8 - } - ] - } - ], - "light": [ - { - "xPct": 8, - "yOffPx": -2, - "w": { - "base": 0.8, - "mult": "spike" - }, - "h": { - "base": 92, - "mult": "h" - }, - "stops": [ - { - "r": 200, - "g": 30, - "b": 60, - "a": 1, - "pos": 0 - }, - { - "r": 200, - "g": 30, - "b": 60, - "a": 0.85, - "pos": 0.3 - }, - { - "r": 200, - "g": 30, - "b": 60, - "a": 0, - "pos": 0.88 - } - ] - }, - { - "xPct": 22, - "yOffPx": -4, - "w": { - "base": 10, - "mult": "spike2" - }, - "h": { - "base": 35, - "mult": "h" - }, - "stops": [ - { - "r": 20, - "g": 150, - "b": 140, - "a": 1, - "pos": 0 - }, - { - "r": 20, - "g": 150, - "b": 140, - "a": 0.7, - "pos": 0.5 - }, - { - "r": 20, - "g": 150, - "b": 140, - "a": 0, - "pos": 0.95 - } - ] - }, - { - "xPct": 36, - "yOffPx": -3, - "w": { - "base": 2, - "mult": "inv-spike" - }, - "h": { - "base": 72, - "mult": "h" - }, - "stops": [ - { - "r": 80, - "g": 50, - "b": 200, - "a": 1, - "pos": 0 - }, - { - "r": 80, - "g": 50, - "b": 200, - "a": 0.8, - "pos": 0.4 - }, - { - "r": 80, - "g": 50, - "b": 200, - "a": 0, - "pos": 0.9 - } - ] - }, - { - "xPct": 50, - "yOffPx": -2, - "w": { - "base": 14, - "mult": "spike2" - }, - "h": { - "base": 28, - "mult": "h" - }, - "stops": [ - { - "r": 210, - "g": 130, - "b": 0, - "a": 0.7, - "pos": 0 - }, - { - "r": 210, - "g": 130, - "b": 0, - "a": 0.46, - "pos": 0.55 - }, - { - "r": 210, - "g": 130, - "b": 0, - "a": 0, - "pos": 0.96 - } - ] - }, - { - "xPct": 64, - "yOffPx": -4, - "w": { - "base": 1.2, - "mult": "inv-spike2" - }, - "h": { - "base": 85, - "mult": "h" - }, - "stops": [ - { - "r": 30, - "g": 160, - "b": 70, - "a": 1, - "pos": 0 - }, - { - "r": 30, - "g": 160, - "b": 70, - "a": 0.82, - "pos": 0.35 - }, - { - "r": 30, - "g": 160, - "b": 70, - "a": 0, - "pos": 0.89 - } - ] - }, - { - "xPct": 78, - "yOffPx": -2, - "w": { - "base": 7, - "mult": "spike" - }, - "h": { - "base": 45, - "mult": "h" - }, - "stops": [ - { - "r": 160, - "g": 30, - "b": 190, - "a": 1, - "pos": 0 - }, - { - "r": 160, - "g": 30, - "b": 190, - "a": 0.7, - "pos": 0.48 - }, - { - "r": 160, - "g": 30, - "b": 190, - "a": 0, - "pos": 0.94 - } - ] - }, - { - "xPct": 92, - "yOffPx": -3, - "w": { - "base": 1, - "mult": "inv-spike" - }, - "h": { - "base": 60, - "mult": "h" - }, - "stops": [ - { - "r": 30, - "g": 100, - "b": 200, - "a": 1, - "pos": 0 - }, - { - "r": 30, - "g": 100, - "b": 200, - "a": 0.78, - "pos": 0.42 - }, - { - "r": 30, - "g": 100, - "b": 200, - "a": 0, - "pos": 0.91 - } - ] - }, - { - "xPct": null, - "yOffPx": 0, - "w": { - "base": 50, - "mult": "w" - }, - "h": { - "base": 32, - "mult": "h" - }, - "stops": [ - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.5, - "pos": 0 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.18, - "pos": 0.3 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.03, - "pos": 0.6 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0, - "pos": 0.85 - } - ] - } - ] - }, - "mono": { - "dark": [ - { - "xPct": 8, - "yOffPx": -2, - "w": { - "base": 12, - "mult": "spike" - }, - "h": { - "base": 42, - "mult": "h" - }, - "stops": [ - { - "r": 200, - "g": 200, - "b": 200, - "a": 0.14, - "pos": 0 - }, - { - "r": 200, - "g": 200, - "b": 200, - "a": 0.09, - "pos": 0.3 - }, - { - "r": 200, - "g": 200, - "b": 200, - "a": 0, - "pos": 0.88 - } - ] - }, - { - "xPct": 22, - "yOffPx": -4, - "w": { - "base": 10, - "mult": "spike2" - }, - "h": { - "base": 35, - "mult": "h" - }, - "stops": [ - { - "r": 170, - "g": 170, - "b": 170, - "a": 0.12, - "pos": 0 - }, - { - "r": 170, - "g": 170, - "b": 170, - "a": 0.06, - "pos": 0.5 - }, - { - "r": 170, - "g": 170, - "b": 170, - "a": 0, - "pos": 0.95 - } - ] - }, - { - "xPct": 36, - "yOffPx": -3, - "w": { - "base": 14, - "mult": "inv-spike" - }, - "h": { - "base": 38, - "mult": "h" - }, - "stops": [ - { - "r": 200, - "g": 200, - "b": 200, - "a": 0.14, - "pos": 0 - }, - { - "r": 200, - "g": 200, - "b": 200, - "a": 0.098, - "pos": 0.4 - }, - { - "r": 200, - "g": 200, - "b": 200, - "a": 0, - "pos": 0.9 - } - ] - }, - { - "xPct": 50, - "yOffPx": -2, - "w": { - "base": 14, - "mult": "spike2" - }, - "h": { - "base": 28, - "mult": "h" - }, - "stops": [ - { - "r": 180, - "g": 180, - "b": 180, - "a": 0.0826, - "pos": 0 - }, - { - "r": 180, - "g": 180, - "b": 180, - "a": 0.0284, - "pos": 0.55 - }, - { - "r": 180, - "g": 180, - "b": 180, - "a": 0, - "pos": 0.96 - } - ] - }, - { - "xPct": 64, - "yOffPx": -4, - "w": { - "base": 12, - "mult": "inv-spike2" - }, - "h": { - "base": 40, - "mult": "h" - }, - "stops": [ - { - "r": 190, - "g": 190, - "b": 190, - "a": 0.14, - "pos": 0 - }, - { - "r": 190, - "g": 190, - "b": 190, - "a": 0.098, - "pos": 0.35 - }, - { - "r": 190, - "g": 190, - "b": 190, - "a": 0, - "pos": 0.89 - } - ] - }, - { - "xPct": 78, - "yOffPx": -2, - "w": { - "base": 7, - "mult": "spike" - }, - "h": { - "base": 45, - "mult": "h" - }, - "stops": [ - { - "r": 170, - "g": 170, - "b": 170, - "a": 0.1274, - "pos": 0 - }, - { - "r": 170, - "g": 170, - "b": 170, - "a": 0.0441, - "pos": 0.48 - }, - { - "r": 170, - "g": 170, - "b": 170, - "a": 0, - "pos": 0.94 - } - ] - }, - { - "xPct": 92, - "yOffPx": -3, - "w": { - "base": 10, - "mult": "inv-spike" - }, - "h": { - "base": 32, - "mult": "h" - }, - "stops": [ - { - "r": 185, - "g": 185, - "b": 185, - "a": 0.14, - "pos": 0 - }, - { - "r": 185, - "g": 185, - "b": 185, - "a": 0.098, - "pos": 0.42 - }, - { - "r": 185, - "g": 185, - "b": 185, - "a": 0, - "pos": 0.91 - } - ] - }, - { - "xPct": null, - "yOffPx": 1, - "w": { - "base": 21, - "mult": "spike" - }, - "h": { - "base": 15, - "mult": "spike2" - }, - "stops": [ - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.5, - "pos": 0 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.45, - "pos": 0.2 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.25, - "pos": 0.5 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0, - "pos": 1 - } - ] - }, - { - "xPct": null, - "yOffPx": 0, - "w": { - "base": 42, - "mult": "w" - }, - "h": { - "base": 40, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.15, - "pos": 0 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.06, - "pos": 0.25 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.015, - "pos": 0.55 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0, - "pos": 0.8 - } - ] - } - ], - "light": [ - { - "xPct": 8, - "yOffPx": -2, - "w": { - "base": 12, - "mult": "spike" - }, - "h": { - "base": 42, - "mult": "h" - }, - "stops": [ - { - "r": 80, - "g": 80, - "b": 80, - "a": 0.14, - "pos": 0 - }, - { - "r": 80, - "g": 80, - "b": 80, - "a": 0.11, - "pos": 0.3 - }, - { - "r": 80, - "g": 80, - "b": 80, - "a": 0, - "pos": 0.88 - } - ] - }, - { - "xPct": 22, - "yOffPx": -4, - "w": { - "base": 10, - "mult": "spike2" - }, - "h": { - "base": 35, - "mult": "h" - }, - "stops": [ - { - "r": 120, - "g": 120, - "b": 120, - "a": 0.12, - "pos": 0 - }, - { - "r": 120, - "g": 120, - "b": 120, - "a": 0.09, - "pos": 0.5 - }, - { - "r": 120, - "g": 120, - "b": 120, - "a": 0, - "pos": 0.95 - } - ] - }, - { - "xPct": 36, - "yOffPx": -3, - "w": { - "base": 14, - "mult": "inv-spike" - }, - "h": { - "base": 38, - "mult": "h" - }, - "stops": [ - { - "r": 80, - "g": 80, - "b": 80, - "a": 0.14, - "pos": 0 - }, - { - "r": 80, - "g": 80, - "b": 80, - "a": 0.0784, - "pos": 0.4 - }, - { - "r": 80, - "g": 80, - "b": 80, - "a": 0, - "pos": 0.9 - } - ] - }, - { - "xPct": 50, - "yOffPx": -2, - "w": { - "base": 14, - "mult": "spike2" - }, - "h": { - "base": 28, - "mult": "h" - }, - "stops": [ - { - "r": 100, - "g": 100, - "b": 100, - "a": 0.098, - "pos": 0 - }, - { - "r": 100, - "g": 100, - "b": 100, - "a": 0.0451, - "pos": 0.55 - }, - { - "r": 100, - "g": 100, - "b": 100, - "a": 0, - "pos": 0.96 - } - ] - }, - { - "xPct": 64, - "yOffPx": -4, - "w": { - "base": 12, - "mult": "inv-spike2" - }, - "h": { - "base": 40, - "mult": "h" - }, - "stops": [ - { - "r": 70, - "g": 70, - "b": 70, - "a": 0.14, - "pos": 0 - }, - { - "r": 70, - "g": 70, - "b": 70, - "a": 0.0804, - "pos": 0.35 - }, - { - "r": 70, - "g": 70, - "b": 70, - "a": 0, - "pos": 0.89 - } - ] - }, - { - "xPct": 78, - "yOffPx": -2, - "w": { - "base": 7, - "mult": "spike" - }, - "h": { - "base": 45, - "mult": "h" - }, - "stops": [ - { - "r": 90, - "g": 90, - "b": 90, - "a": 0.14, - "pos": 0 - }, - { - "r": 90, - "g": 90, - "b": 90, - "a": 0.0686, - "pos": 0.48 - }, - { - "r": 90, - "g": 90, - "b": 90, - "a": 0, - "pos": 0.94 - } - ] - }, - { - "xPct": 92, - "yOffPx": -3, - "w": { - "base": 12, - "mult": "inv-spike" - }, - "h": { - "base": 32, - "mult": "h" - }, - "stops": [ - { - "r": 85, - "g": 85, - "b": 85, - "a": 0.14, - "pos": 0 - }, - { - "r": 85, - "g": 85, - "b": 85, - "a": 0.0764, - "pos": 0.42 - }, - { - "r": 85, - "g": 85, - "b": 85, - "a": 0, - "pos": 0.91 - } - ] - }, - { - "xPct": null, - "yOffPx": 0, - "w": { - "base": 50, - "mult": "w" - }, - "h": { - "base": 32, - "mult": "h" - }, - "stops": [ - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.5, - "pos": 0 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.18, - "pos": 0.3 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.03, - "pos": 0.6 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0, - "pos": 0.85 - } - ] - } - ] - }, - "ocean": { - "dark": [ - { - "xPct": 8, - "yOffPx": -2, - "w": { - "base": 0.8, - "mult": "spike" - }, - "h": { - "base": 92, - "mult": "h" - }, - "stops": [ - { - "r": 100, - "g": 120, - "b": 255, - "a": 1, - "pos": 0 - }, - { - "r": 100, - "g": 120, - "b": 255, - "a": 1, - "pos": 0.3 - }, - { - "r": 100, - "g": 120, - "b": 255, - "a": 0, - "pos": 0.88 - } - ] - }, - { - "xPct": 22, - "yOffPx": -4, - "w": { - "base": 10, - "mult": "spike2" - }, - "h": { - "base": 35, - "mult": "h" - }, - "stops": [ - { - "r": 130, - "g": 100, - "b": 220, - "a": 0.98, - "pos": 0 - }, - { - "r": 130, - "g": 100, - "b": 220, - "a": 0.49, - "pos": 0.5 - }, - { - "r": 130, - "g": 100, - "b": 220, - "a": 0, - "pos": 0.95 - } - ] - }, - { - "xPct": 36, - "yOffPx": -3, - "w": { - "base": 2, - "mult": "inv-spike" - }, - "h": { - "base": 72, - "mult": "h" - }, - "stops": [ - { - "r": 100, - "g": 80, - "b": 255, - "a": 1, - "pos": 0 - }, - { - "r": 100, - "g": 80, - "b": 255, - "a": 1, - "pos": 0.4 - }, - { - "r": 100, - "g": 80, - "b": 255, - "a": 0, - "pos": 0.9 - } - ] - }, - { - "xPct": 50, - "yOffPx": -2, - "w": { - "base": 14, - "mult": "spike2" - }, - "h": { - "base": 28, - "mult": "h" - }, - "stops": [ - { - "r": 80, - "g": 130, - "b": 220, - "a": 0.59, - "pos": 0 - }, - { - "r": 80, - "g": 130, - "b": 220, - "a": 0.29, - "pos": 0.55 - }, - { - "r": 80, - "g": 130, - "b": 220, - "a": 0, - "pos": 0.96 - } - ] - }, - { - "xPct": 64, - "yOffPx": -4, - "w": { - "base": 1.2, - "mult": "inv-spike2" - }, - "h": { - "base": 85, - "mult": "h" - }, - "stops": [ - { - "r": 60, - "g": 100, - "b": 255, - "a": 1, - "pos": 0 - }, - { - "r": 60, - "g": 100, - "b": 255, - "a": 1, - "pos": 0.35 - }, - { - "r": 60, - "g": 100, - "b": 255, - "a": 0, - "pos": 0.89 - } - ] - }, - { - "xPct": 78, - "yOffPx": -2, - "w": { - "base": 7, - "mult": "spike" - }, - "h": { - "base": 45, - "mult": "h" - }, - "stops": [ - { - "r": 90, - "g": 120, - "b": 200, - "a": 0.91, - "pos": 0 - }, - { - "r": 90, - "g": 120, - "b": 200, - "a": 0.45, - "pos": 0.48 - }, - { - "r": 90, - "g": 120, - "b": 200, - "a": 0, - "pos": 0.94 - } - ] - }, - { - "xPct": 92, - "yOffPx": -3, - "w": { - "base": 0.6, - "mult": "inv-spike" - }, - "h": { - "base": 60, - "mult": "h" - }, - "stops": [ - { - "r": 120, - "g": 90, - "b": 255, - "a": 1, - "pos": 0 - }, - { - "r": 120, - "g": 90, - "b": 255, - "a": 1, - "pos": 0.42 - }, - { - "r": 120, - "g": 90, - "b": 255, - "a": 0, - "pos": 0.91 - } - ] - }, - { - "xPct": null, - "yOffPx": 1, - "w": { - "base": 21, - "mult": "spike" - }, - "h": { - "base": 15, - "mult": "spike2" - }, - "stops": [ - { - "r": 255, - "g": 255, - "b": 255, - "a": 1, - "pos": 0 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.9, - "pos": 0.2 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.5, - "pos": 0.5 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0, - "pos": 1 - } - ] - }, - { - "xPct": null, - "yOffPx": 0, - "w": { - "base": 42, - "mult": "w" - }, - "h": { - "base": 40, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.3, - "pos": 0 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.12, - "pos": 0.25 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.03, - "pos": 0.55 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0, - "pos": 0.8 - } - ] - } - ], - "light": [ - { - "xPct": 8, - "yOffPx": -2, - "w": { - "base": 0.8, - "mult": "spike" - }, - "h": { - "base": 92, - "mult": "h" - }, - "stops": [ - { - "r": 60, - "g": 60, - "b": 180, - "a": 1, - "pos": 0 - }, - { - "r": 60, - "g": 60, - "b": 180, - "a": 0.85, - "pos": 0.3 - }, - { - "r": 60, - "g": 60, - "b": 180, - "a": 0, - "pos": 0.88 - } - ] - }, - { - "xPct": 22, - "yOffPx": -4, - "w": { - "base": 10, - "mult": "spike2" - }, - "h": { - "base": 35, - "mult": "h" - }, - "stops": [ - { - "r": 80, - "g": 100, - "b": 200, - "a": 1, - "pos": 0 - }, - { - "r": 80, - "g": 100, - "b": 200, - "a": 0.7, - "pos": 0.5 - }, - { - "r": 80, - "g": 100, - "b": 200, - "a": 0, - "pos": 0.95 - } - ] - }, - { - "xPct": 36, - "yOffPx": -3, - "w": { - "base": 2, - "mult": "inv-spike" - }, - "h": { - "base": 72, - "mult": "h" - }, - "stops": [ - { - "r": 50, - "g": 40, - "b": 180, - "a": 1, - "pos": 0 - }, - { - "r": 50, - "g": 40, - "b": 180, - "a": 0.8, - "pos": 0.4 - }, - { - "r": 50, - "g": 40, - "b": 180, - "a": 0, - "pos": 0.9 - } - ] - }, - { - "xPct": 50, - "yOffPx": -2, - "w": { - "base": 14, - "mult": "spike2" - }, - "h": { - "base": 28, - "mult": "h" - }, - "stops": [ - { - "r": 40, - "g": 80, - "b": 200, - "a": 0.7, - "pos": 0 - }, - { - "r": 40, - "g": 80, - "b": 200, - "a": 0.46, - "pos": 0.55 - }, - { - "r": 40, - "g": 80, - "b": 200, - "a": 0, - "pos": 0.96 - } - ] - }, - { - "xPct": 64, - "yOffPx": -4, - "w": { - "base": 1.2, - "mult": "inv-spike2" - }, - "h": { - "base": 85, - "mult": "h" - }, - "stops": [ - { - "r": 30, - "g": 50, - "b": 190, - "a": 1, - "pos": 0 - }, - { - "r": 30, - "g": 50, - "b": 190, - "a": 0.82, - "pos": 0.35 - }, - { - "r": 30, - "g": 50, - "b": 190, - "a": 0, - "pos": 0.89 - } - ] - }, - { - "xPct": 78, - "yOffPx": -2, - "w": { - "base": 7, - "mult": "spike" - }, - "h": { - "base": 45, - "mult": "h" - }, - "stops": [ - { - "r": 60, - "g": 90, - "b": 180, - "a": 1, - "pos": 0 - }, - { - "r": 60, - "g": 90, - "b": 180, - "a": 0.7, - "pos": 0.48 - }, - { - "r": 60, - "g": 90, - "b": 180, - "a": 0, - "pos": 0.94 - } - ] - }, - { - "xPct": 92, - "yOffPx": -3, - "w": { - "base": 1, - "mult": "inv-spike" - }, - "h": { - "base": 60, - "mult": "h" - }, - "stops": [ - { - "r": 70, - "g": 60, - "b": 200, - "a": 1, - "pos": 0 - }, - { - "r": 70, - "g": 60, - "b": 200, - "a": 0.78, - "pos": 0.42 - }, - { - "r": 70, - "g": 60, - "b": 200, - "a": 0, - "pos": 0.91 - } - ] - }, - { - "xPct": null, - "yOffPx": 0, - "w": { - "base": 50, - "mult": "w" - }, - "h": { - "base": 32, - "mult": "h" - }, - "stops": [ - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.5, - "pos": 0 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.18, - "pos": 0.3 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.03, - "pos": 0.6 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0, - "pos": 0.85 - } - ] - } - ] - }, - "sunset": { - "dark": [ - { - "xPct": 8, - "yOffPx": -2, - "w": { - "base": 0.8, - "mult": "spike" - }, - "h": { - "base": 92, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 140, - "b": 80, - "a": 1, - "pos": 0 - }, - { - "r": 255, - "g": 140, - "b": 80, - "a": 1, - "pos": 0.3 - }, - { - "r": 255, - "g": 140, - "b": 80, - "a": 0, - "pos": 0.88 - } - ] - }, - { - "xPct": 22, - "yOffPx": -4, - "w": { - "base": 10, - "mult": "spike2" - }, - "h": { - "base": 35, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 100, - "b": 60, - "a": 0.98, - "pos": 0 - }, - { - "r": 255, - "g": 100, - "b": 60, - "a": 0.49, - "pos": 0.5 - }, - { - "r": 255, - "g": 100, - "b": 60, - "a": 0, - "pos": 0.95 - } - ] - }, - { - "xPct": 36, - "yOffPx": -3, - "w": { - "base": 2, - "mult": "inv-spike" - }, - "h": { - "base": 72, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 100, - "b": 80, - "a": 1, - "pos": 0 - }, - { - "r": 255, - "g": 100, - "b": 80, - "a": 1, - "pos": 0.4 - }, - { - "r": 255, - "g": 100, - "b": 80, - "a": 0, - "pos": 0.9 - } - ] - }, - { - "xPct": 50, - "yOffPx": -2, - "w": { - "base": 14, - "mult": "spike2" - }, - "h": { - "base": 28, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 150, - "b": 80, - "a": 0.59, - "pos": 0 - }, - { - "r": 255, - "g": 150, - "b": 80, - "a": 0.29, - "pos": 0.55 - }, - { - "r": 255, - "g": 150, - "b": 80, - "a": 0, - "pos": 0.96 - } - ] - }, - { - "xPct": 64, - "yOffPx": -4, - "w": { - "base": 1.2, - "mult": "inv-spike2" - }, - "h": { - "base": 85, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 80, - "b": 60, - "a": 1, - "pos": 0 - }, - { - "r": 255, - "g": 80, - "b": 60, - "a": 1, - "pos": 0.35 - }, - { - "r": 255, - "g": 80, - "b": 60, - "a": 0, - "pos": 0.89 - } - ] - }, - { - "xPct": 78, - "yOffPx": -2, - "w": { - "base": 7, - "mult": "spike" - }, - "h": { - "base": 45, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 120, - "b": 50, - "a": 0.91, - "pos": 0 - }, - { - "r": 255, - "g": 120, - "b": 50, - "a": 0.45, - "pos": 0.48 - }, - { - "r": 255, - "g": 120, - "b": 50, - "a": 0, - "pos": 0.94 - } - ] - }, - { - "xPct": 92, - "yOffPx": -3, - "w": { - "base": 0.6, - "mult": "inv-spike" - }, - "h": { - "base": 60, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 140, - "b": 70, - "a": 1, - "pos": 0 - }, - { - "r": 255, - "g": 140, - "b": 70, - "a": 1, - "pos": 0.42 - }, - { - "r": 255, - "g": 140, - "b": 70, - "a": 0, - "pos": 0.91 - } - ] - }, - { - "xPct": null, - "yOffPx": 1, - "w": { - "base": 21, - "mult": "spike" - }, - "h": { - "base": 15, - "mult": "spike2" - }, - "stops": [ - { - "r": 255, - "g": 255, - "b": 255, - "a": 1, - "pos": 0 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.9, - "pos": 0.2 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.5, - "pos": 0.5 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0, - "pos": 1 - } - ] - }, - { - "xPct": null, - "yOffPx": 0, - "w": { - "base": 42, - "mult": "w" - }, - "h": { - "base": 40, - "mult": "h" - }, - "stops": [ - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.3, - "pos": 0 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.12, - "pos": 0.25 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0.03, - "pos": 0.55 - }, - { - "r": 255, - "g": 255, - "b": 255, - "a": 0, - "pos": 0.8 - } - ] - } - ], - "light": [ - { - "xPct": 8, - "yOffPx": -2, - "w": { - "base": 0.8, - "mult": "spike" - }, - "h": { - "base": 92, - "mult": "h" - }, - "stops": [ - { - "r": 200, - "g": 80, - "b": 40, - "a": 1, - "pos": 0 - }, - { - "r": 200, - "g": 80, - "b": 40, - "a": 0.85, - "pos": 0.3 - }, - { - "r": 200, - "g": 80, - "b": 40, - "a": 0, - "pos": 0.88 - } - ] - }, - { - "xPct": 22, - "yOffPx": -4, - "w": { - "base": 10, - "mult": "spike2" - }, - "h": { - "base": 35, - "mult": "h" - }, - "stops": [ - { - "r": 220, - "g": 120, - "b": 30, - "a": 1, - "pos": 0 - }, - { - "r": 220, - "g": 120, - "b": 30, - "a": 0.7, - "pos": 0.5 - }, - { - "r": 220, - "g": 120, - "b": 30, - "a": 0, - "pos": 0.95 - } - ] - }, - { - "xPct": 36, - "yOffPx": -3, - "w": { - "base": 2, - "mult": "inv-spike" - }, - "h": { - "base": 72, - "mult": "h" - }, - "stops": [ - { - "r": 200, - "g": 60, - "b": 30, - "a": 1, - "pos": 0 - }, - { - "r": 200, - "g": 60, - "b": 30, - "a": 0.8, - "pos": 0.4 - }, - { - "r": 200, - "g": 60, - "b": 30, - "a": 0, - "pos": 0.9 - } - ] - }, - { - "xPct": 50, - "yOffPx": -2, - "w": { - "base": 14, - "mult": "spike2" - }, - "h": { - "base": 28, - "mult": "h" - }, - "stops": [ - { - "r": 220, - "g": 100, - "b": 20, - "a": 0.7, - "pos": 0 - }, - { - "r": 220, - "g": 100, - "b": 20, - "a": 0.46, - "pos": 0.55 - }, - { - "r": 220, - "g": 100, - "b": 20, - "a": 0, - "pos": 0.96 - } - ] - }, - { - "xPct": 64, - "yOffPx": -4, - "w": { - "base": 1.2, - "mult": "inv-spike2" - }, - "h": { - "base": 85, - "mult": "h" - }, - "stops": [ - { - "r": 180, - "g": 40, - "b": 20, - "a": 1, - "pos": 0 - }, - { - "r": 180, - "g": 40, - "b": 20, - "a": 0.82, - "pos": 0.35 - }, - { - "r": 180, - "g": 40, - "b": 20, - "a": 0, - "pos": 0.89 - } - ] - }, - { - "xPct": 78, - "yOffPx": -2, - "w": { - "base": 7, - "mult": "spike" - }, - "h": { - "base": 45, - "mult": "h" - }, - "stops": [ - { - "r": 210, - "g": 80, - "b": 10, - "a": 1, - "pos": 0 - }, - { - "r": 210, - "g": 80, - "b": 10, - "a": 0.7, - "pos": 0.48 - }, - { - "r": 210, - "g": 80, - "b": 10, - "a": 0, - "pos": 0.94 - } - ] - }, - { - "xPct": 92, - "yOffPx": -3, - "w": { - "base": 1, - "mult": "inv-spike" - }, - "h": { - "base": 60, - "mult": "h" - }, - "stops": [ - { - "r": 190, - "g": 70, - "b": 30, - "a": 1, - "pos": 0 - }, - { - "r": 190, - "g": 70, - "b": 30, - "a": 0.78, - "pos": 0.42 - }, - { - "r": 190, - "g": 70, - "b": 30, - "a": 0, - "pos": 0.91 - } - ] - }, - { - "xPct": null, - "yOffPx": 0, - "w": { - "base": 50, - "mult": "w" - }, - "h": { - "base": 32, - "mult": "h" - }, - "stops": [ - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.5, - "pos": 0 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.18, - "pos": 0.3 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0.03, - "pos": 0.6 - }, - { - "r": 0, - "g": 0, - "b": 0, - "a": 0, - "pos": 0.85 - } - ] - } - ] - } - }, - "monoBloomExtraBlurPx": 6, - "bloomBlurPx": 8 - }, - "pulse": { - "ringMap": [ - { - "region": 1, - "quad": "tl" - }, - { - "region": 2, - "quad": "tl" - }, - { - "region": 3, - "quad": "bl" - }, - { - "region": 1, - "quad": "bl" - }, - { - "region": 2, - "quad": "br" - }, - { - "region": 3, - "quad": "br" - }, - { - "region": 1, - "quad": "tr" - }, - { - "region": 2, - "quad": "tr" - }, - { - "region": 3, - "quad": "tr" - } - ], - "innerSizes": [ - [ - 65, - 35 - ], - [ - 55, - 30 - ], - [ - 35, - 65 - ], - [ - 15, - 30 - ], - [ - 173, - 28 - ], - [ - 80, - 22 - ], - [ - 69, - 28 - ], - [ - 22, - 38 - ], - [ - 47, - 44 - ] - ], - "innerBloom": [ - { - "ci": 0, - "region": 1, - "quad": "tl", - "w": 84, - "h": 48 - }, - { - "ci": 1, - "region": 2, - "quad": "tl", - "w": 72, - "h": 42 - }, - { - "ci": 2, - "region": 3, - "quad": "bl", - "w": 48, - "h": 84 - }, - { - "ci": 4, - "region": 2, - "quad": "br", - "w": 216, - "h": 38 - }, - { - "ci": 5, - "region": 3, - "quad": "br", - "w": 102, - "h": 31 - }, - { - "ci": 6, - "region": 1, - "quad": "tr", - "w": 89, - "h": 38 - }, - { - "ci": 8, - "region": 3, - "quad": "tr", - "w": 62, - "h": 58 - } - ], - "outerCore": [ - { - "ci": 0, - "region": 1, - "quad": "tl", - "w": 80, - "h": 19, - "x": "27%", - "y": "0%" - }, - { - "ci": 6, - "region": 2, - "quad": "tr", - "w": 74, - "h": 11, - "x": "73%", - "y": "-1%" - }, - { - "ci": 7, - "region": 3, - "quad": "tr", - "w": 15, - "h": 44, - "x": "100%", - "y": "33%" - }, - { - "ci": 8, - "region": 1, - "quad": "br", - "w": 19, - "h": 38, - "x": "101%", - "y": "72%" - }, - { - "ci": 4, - "region": 2, - "quad": "br", - "w": 84, - "h": 13, - "x": "67%", - "y": "100%" - }, - { - "ci": 1, - "region": 3, - "quad": "bl", - "w": 60, - "h": 21, - "x": "24%", - "y": "101%" - }, - { - "ci": 2, - "region": 1, - "quad": "bl", - "w": 17, - "h": 40, - "x": "0%", - "y": "60%" - }, - { - "ci": 3, - "region": 2, - "quad": "tl", - "w": 13, - "h": 32, - "x": "-1%", - "y": "28%" - } - ], - "outerBloom": [ - { - "ci": 0, - "region": 1, - "quad": "tl", - "w": 110, - "h": 30, - "x": "27%", - "y": "3%" - }, - { - "ci": 6, - "region": 2, - "quad": "tr", - "w": 100, - "h": 20, - "x": "73%", - "y": "1%" - }, - { - "ci": 7, - "region": 3, - "quad": "tr", - "w": 26, - "h": 62, - "x": "100%", - "y": "33%" - }, - { - "ci": 8, - "region": 1, - "quad": "br", - "w": 30, - "h": 56, - "x": "101%", - "y": "72%" - }, - { - "ci": 4, - "region": 2, - "quad": "br", - "w": 120, - "h": 22, - "x": "67%", - "y": "99%" - }, - { - "ci": 1, - "region": 3, - "quad": "bl", - "w": 88, - "h": 32, - "x": "24%", - "y": "99%" - }, - { - "ci": 2, - "region": 1, - "quad": "bl", - "w": 28, - "h": 58, - "x": "0%", - "y": "60%" - } - ], - "innerCornerAccent": { - "sizePx": 60, - "alpha": { - "dark": 0.18, - "light": 0.08 - }, - "fadeStop": 70 - }, - "inner": { - "dark": { - "params": { - "sp": 0.28, - "dr": 33, - "op": 0.48, - "gh": 0.34, - "bs": 1.9, - "ss": 2.6, - "ghs": 2.4, - "huePeriod": 16 - }, - "oscillators": [ - { - "prop": "bw1", - "a": 0.72, - "b": 1.308, - "period": 2.34, - "delay": 0, - "unit": "" - }, - { - "prop": "bh1", - "a": 1.252, - "b": 0.762, - "period": 3.276, - "delay": 0, - "unit": "" - }, - { - "prop": "bx1", - "a": -33, - "b": 29.7, - "period": 3.04, - "delay": 0, - "unit": "px" - }, - { - "prop": "by1", - "a": 18.15, - "b": -23.1, - "period": 3.04, - "delay": 0, - "unit": "px" - }, - { - "prop": "bw2", - "a": 1.28, - "b": 0.762, - "period": 2.86, - "delay": 0, - "unit": "" - }, - { - "prop": "bh2", - "a": 0.776, - "b": 1.294, - "period": 2.106, - "delay": 0, - "unit": "" - }, - { - "prop": "bx2", - "a": 26.4, - "b": -29.7, - "period": 3.572, - "delay": 0, - "unit": "px" - }, - { - "prop": "by2", - "a": -33, - "b": 21.45, - "period": 3.572, - "delay": 0, - "unit": "px" - }, - { - "prop": "bw3", - "a": 0.832, - "b": 1.322, - "period": 2.548, - "delay": 0, - "unit": "" - }, - { - "prop": "bh3", - "a": 1.21, - "b": 0.72, - "period": 3.64, - "delay": 0, - "unit": "" - }, - { - "prop": "bx3", - "a": -19.8, - "b": 33, - "period": 2.755, - "delay": 0, - "unit": "px" - }, - { - "prop": "by3", - "a": -28.05, - "b": 14.85, - "period": 2.755, - "delay": 0, - "unit": "px" - }, - { - "prop": "bgh", - "a": 0.66, - "b": 1.34, - "period": 2.4, - "delay": 0, - "unit": "" - }, - { - "prop": "bop-tl", - "a": 0.52, - "b": 1, - "period": 1.9, - "delay": 0, - "unit": "" - }, - { - "prop": "bop-tr", - "a": 0.52, - "b": 1, - "period": 2.508, - "delay": 0.532, - "unit": "" - }, - { - "prop": "bop-bl", - "a": 0.52, - "b": 1, - "period": 1.596, - "delay": 1.045, - "unit": "" - }, - { - "prop": "bop-br", - "a": 0.52, - "b": 1, - "period": 3.002, - "delay": 1.577, - "unit": "" - } - ], - "frozenBloomAlpha": 0.76 - }, - "light": { - "params": { - "sp": 0.28, - "dr": 40, - "op": 0.45, - "gh": 0.22, - "bs": 2.6, - "ss": 4.6, - "ghs": 5.5, - "huePeriod": 16 - }, - "oscillators": [ - { - "prop": "bw1", - "a": 0.72, - "b": 1.308, - "period": 4.14, - "delay": 0, - "unit": "" - }, - { - "prop": "bh1", - "a": 1.252, - "b": 0.762, - "period": 5.796, - "delay": 0, - "unit": "" - }, - { - "prop": "bx1", - "a": -40, - "b": 36, - "period": 4.16, - "delay": 0, - "unit": "px" - }, - { - "prop": "by1", - "a": 22, - "b": -28, - "period": 4.16, - "delay": 0, - "unit": "px" - }, - { - "prop": "bw2", - "a": 1.28, - "b": 0.762, - "period": 5.06, - "delay": 0, - "unit": "" - }, - { - "prop": "bh2", - "a": 0.776, - "b": 1.294, - "period": 3.726, - "delay": 0, - "unit": "" - }, - { - "prop": "bx2", - "a": 32, - "b": -36, - "period": 4.888, - "delay": 0, - "unit": "px" - }, - { - "prop": "by2", - "a": -40, - "b": 26, - "period": 4.888, - "delay": 0, - "unit": "px" - }, - { - "prop": "bw3", - "a": 0.832, - "b": 1.322, - "period": 4.508, - "delay": 0, - "unit": "" - }, - { - "prop": "bh3", - "a": 1.21, - "b": 0.72, - "period": 6.44, - "delay": 0, - "unit": "" - }, - { - "prop": "bx3", - "a": -24, - "b": 40, - "period": 3.77, - "delay": 0, - "unit": "px" - }, - { - "prop": "by3", - "a": -34, - "b": 18, - "period": 3.77, - "delay": 0, - "unit": "px" - }, - { - "prop": "bgh", - "a": 0.78, - "b": 1.22, - "period": 5.5, - "delay": 0, - "unit": "" - }, - { - "prop": "bop-tl", - "a": 0.55, - "b": 1, - "period": 2.6, - "delay": 0, - "unit": "" - }, - { - "prop": "bop-tr", - "a": 0.55, - "b": 1, - "period": 3.432, - "delay": 0.728, - "unit": "" - }, - { - "prop": "bop-bl", - "a": 0.55, - "b": 1, - "period": 2.184, - "delay": 1.43, - "unit": "" - }, - { - "prop": "bop-br", - "a": 0.55, - "b": 1, - "period": 4.108, - "delay": 2.158, - "unit": "" - } - ], - "frozenBloomAlpha": 0.775 - } - }, - "outside": { - "dark": { - "params": { - "sp": 0.28, - "dr": 14, - "op": 0.46, - "gh": 0.16, - "bs": 2.3, - "ss": 6.4, - "ghs": 2.4, - "huePeriod": 14 - }, - "oscillators": [ - { - "prop": "bw1", - "a": 0.72, - "b": 1.308, - "period": 5.76, - "delay": 0, - "unit": "" - }, - { - "prop": "bh1", - "a": 1.252, - "b": 0.762, - "period": 8.064, - "delay": 0, - "unit": "" - }, - { - "prop": "bx1", - "a": -14, - "b": 12.6, - "period": 3.68, - "delay": 0, - "unit": "px" - }, - { - "prop": "by1", - "a": 7.7, - "b": -9.8, - "period": 3.68, - "delay": 0, - "unit": "px" - }, - { - "prop": "bw2", - "a": 1.28, - "b": 0.762, - "period": 7.04, - "delay": 0, - "unit": "" - }, - { - "prop": "bh2", - "a": 0.776, - "b": 1.294, - "period": 5.184, - "delay": 0, - "unit": "" - }, - { - "prop": "bx2", - "a": 11.2, - "b": -12.6, - "period": 4.324, - "delay": 0, - "unit": "px" - }, - { - "prop": "by2", - "a": -14, - "b": 9.1, - "period": 4.324, - "delay": 0, - "unit": "px" - }, - { - "prop": "bw3", - "a": 0.832, - "b": 1.322, - "period": 6.272, - "delay": 0, - "unit": "" - }, - { - "prop": "bh3", - "a": 1.21, - "b": 0.72, - "period": 8.96, - "delay": 0, - "unit": "" - }, - { - "prop": "bx3", - "a": -8.4, - "b": 14, - "period": 3.335, - "delay": 0, - "unit": "px" - }, - { - "prop": "by3", - "a": -11.9, - "b": 6.3, - "period": 3.335, - "delay": 0, - "unit": "px" - }, - { - "prop": "bgh", - "a": 0.84, - "b": 1.16, - "period": 2.4, - "delay": 0, - "unit": "" - }, - { - "prop": "bop-tl", - "a": 0.54, - "b": 1, - "period": 2.3, - "delay": 0, - "unit": "" - }, - { - "prop": "bop-tr", - "a": 0.54, - "b": 1, - "period": 3.036, - "delay": 0.644, - "unit": "" - }, - { - "prop": "bop-bl", - "a": 0.54, - "b": 1, - "period": 1.932, - "delay": 1.265, - "unit": "" - }, - { - "prop": "bop-br", - "a": 0.54, - "b": 1, - "period": 3.634, - "delay": 1.909, - "unit": "" - } - ], - "frozenBloomAlpha": 0.77 - }, - "light": { - "params": { - "sp": 0.36, - "dr": 19, - "op": 0, - "gh": 0.58, - "bs": 3.7, - "ss": 4.6, - "ghs": 3.8, - "huePeriod": 14 - }, - "oscillators": [ - { - "prop": "bw1", - "a": 0.64, - "b": 1.396, - "period": 4.14, - "delay": 0, - "unit": "" - }, - { - "prop": "bh1", - "a": 1.324, - "b": 0.694, - "period": 5.796, - "delay": 0, - "unit": "" - }, - { - "prop": "bx1", - "a": -19, - "b": 17.1, - "period": 5.92, - "delay": 0, - "unit": "px" - }, - { - "prop": "by1", - "a": 10.45, - "b": -13.3, - "period": 5.92, - "delay": 0, - "unit": "px" - }, - { - "prop": "bw2", - "a": 1.36, - "b": 0.694, - "period": 5.06, - "delay": 0, - "unit": "" - }, - { - "prop": "bh2", - "a": 0.712, - "b": 1.378, - "period": 3.726, - "delay": 0, - "unit": "" - }, - { - "prop": "bx2", - "a": 15.2, - "b": -17.1, - "period": 6.956, - "delay": 0, - "unit": "px" - }, - { - "prop": "by2", - "a": -19, - "b": 12.35, - "period": 6.956, - "delay": 0, - "unit": "px" - }, - { - "prop": "bw3", - "a": 0.784, - "b": 1.414, - "period": 4.508, - "delay": 0, - "unit": "" - }, - { - "prop": "bh3", - "a": 1.27, - "b": 0.64, - "period": 6.44, - "delay": 0, - "unit": "" - }, - { - "prop": "bx3", - "a": -11.4, - "b": 19, - "period": 5.365, - "delay": 0, - "unit": "px" - }, - { - "prop": "by3", - "a": -16.15, - "b": 8.55, - "period": 5.365, - "delay": 0, - "unit": "px" - }, - { - "prop": "bgh", - "a": 0.42, - "b": 1.58, - "period": 3.8, - "delay": 0, - "unit": "" - }, - { - "prop": "bop-tl", - "a": 1, - "b": 1, - "period": 3.7, - "delay": 0, - "unit": "" - }, - { - "prop": "bop-tr", - "a": 1, - "b": 1, - "period": 4.884, - "delay": 1.036, - "unit": "" - }, - { - "prop": "bop-bl", - "a": 1, - "b": 1, - "period": 3.108, - "delay": 2.035, - "unit": "" - }, - { - "prop": "bop-br", - "a": 1, - "b": 1, - "period": 5.846, - "delay": 3.071, - "unit": "" - } - ], - "frozenBloomAlpha": 1 - } - }, - "huePeriod": { - "pulse-inner": 16, - "pulse-outside": 14 - }, - "outsideConstants": { - "glowScale": { - "x": 0.95, - "y": 0.9 - }, - "glowBlurPx": { - "dark": 3, - "light": 6 - }, - "bloomBlurPx": { - "dark": 22.5, - "light": 15 - }, - "coreInsetPx": 10, - "bloomInsetPx": 30, - "referenceSize": { - "w": 350, - "h": 140 - }, - "scaleClamp": { - "min": 0.35, - "max": 4 - }, - "hairline": { - "rgb": { - "dark": [ - 70, - 70, - 70 - ], - "light": [ - 0, - 0, - 0 - ] - } - } - }, - "innerBloomBlurPx": 8, - "oscillatorCurve": "cosinePingPong" - }, - "filters": { - "order": [ - "blur?", - "hue-rotate", - "brightness", - "saturate" - ], - "hueRotateModel": "css-fecolormatrix-huerotate-linearRGB-off" - } -} diff --git a/test/golden/beam_golden_test.dart b/test/golden/beam_golden_test.dart index 50dd5cc..7f83f72 100644 --- a/test/golden/beam_golden_test.dart +++ b/test/golden/beam_golden_test.dart @@ -1,289 +1,130 @@ @Tags(['golden']) library; -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -/// Golden scenes freeze the (fake) test clock at 1.3s after activation — -/// past the 0.6s fade-in, mid-cycle for every variant — so each image -/// captures a representative animated frame deterministically. The two -/// traveling variants are captured a second time at a later instant -/// (`_late`), because one frame of a sweep says nothing about where the -/// sweep is the rest of the time. +import 'golden_scene.dart'; + +/// The effect family: every effect on both themes in the colorful palette +/// and in the other three original palettes, and the effect options. /// -/// Regenerate with: -/// flutter test --update-goldens --tags golden +/// All captured at t = 1.3s. A travelling effect is captured a second time +/// (`_late`) further along: one frame of a sweep says nothing about where it +/// is the rest of the time. void main() { - Widget scene({ - required Widget beam, - required Brightness brightness, - double width = 350, - double height = 140, - }) { - final isDark = brightness == Brightness.dark; - return MaterialApp( - debugShowCheckedModeBanner: false, - theme: ThemeData(brightness: brightness), - home: ColoredBox( - // The demo backdrops of the source library. - color: isDark ? const Color(0xFF070707) : const Color(0xFFFDFDFD), - child: Center( - child: SizedBox(width: width, height: height, child: beam), - ), - ), - ); - } + setUpAll(BorderBeam.precache); + + // Where the second capture of each travelling effect lands: late in a + // rotate's turn and a line's sweep. + const late = { + 'rotate': Duration(milliseconds: 2000), + 'line': Duration(milliseconds: 2000), + }; - // [radii] carries a per-corner radius when a scene needs one; otherwise - // every corner takes [radius]. - Widget mockSurface( + BeamTheme themeFor(Brightness b) => + b == Brightness.dark ? BeamTheme.dark : BeamTheme.light; + + Widget beam( + BeamEffect effect, Brightness brightness, { + BeamColors colors = BeamColors.colorful, + BeamStyle style = const BeamStyle(), double radius = 16, - BorderRadius? radii, - }) => DecoratedBox( - decoration: BoxDecoration( - color: brightness == Brightness.dark - ? const Color(0xFF1D1D1D) - : const Color(0xFFFFFFFF), - borderRadius: radii ?? BorderRadius.circular(radius), - border: Border.all( - color: brightness == Brightness.dark - ? const Color(0x14FFFFFF) - : const Color(0x14000000), - ), - ), + }) => BorderBeam( + effect: effect, + colors: colors, + borderRadius: radius, + style: style.copyWith(theme: themeFor(brightness)), + child: mockSurface(brightness, radius: radius), ); - Future capture( - WidgetTester tester, - String name, - Widget Function(Brightness) beam, { - required Brightness brightness, - double width = 350, - double height = 140, - Duration freeze = const Duration(milliseconds: 1300), - }) async { - await tester.pumpWidget( - scene( - beam: beam(brightness), - brightness: brightness, - width: width, - height: height, - ), - ); - await tester.pump(); - await tester.pump(freeze); - await expectLater( - find.byType(MaterialApp), - matchesGoldenFile('goldens/$name.png'), - ); - } - for (final brightness in Brightness.values) { - final theme = brightness == Brightness.dark ? 'dark' : 'light'; - final beamTheme = brightness == Brightness.dark - ? BeamTheme.dark - : BeamTheme.light; - - for (final MapEntry(key: paletteName, value: colors) in { - 'colorful': BeamColors.colorful, - 'mono': BeamColors.mono, - 'ocean': BeamColors.ocean, - 'sunset': BeamColors.sunset, - }.entries) { - testWidgets('rotate $theme $paletteName', (tester) async { - await capture( - tester, - 'rotate_${theme}_$paletteName', - brightness: brightness, - (b) => BorderBeam.rotate( - colors: colors, - style: BeamStyle(theme: beamTheme), - child: mockSurface(b), - ), - ); - }); + final theme = brightness.name; - testWidgets('small $theme $paletteName', (tester) async { - await capture( + for (final effect in BeamEffect.values) { + testWidgets('${effect.name} $theme colorful', (tester) async { + await captureGolden( tester, - 'small_${theme}_$paletteName', - brightness: brightness, - width: 70, - height: 36, - (b) => BorderBeam.small( - colors: colors, - style: BeamStyle(theme: beamTheme), - child: mockSurface(b, radius: 32), - ), + '${effect.name}_${theme}_colorful', + goldenScene(beam(effect, brightness), brightness: brightness), ); }); - testWidgets('line $theme $paletteName', (tester) async { - await capture( - tester, - 'line_${theme}_$paletteName', - brightness: brightness, - (b) => BorderBeam.line( - colors: colors, - style: BeamStyle(theme: beamTheme), - child: mockSurface(b), - ), - ); - }); - - testWidgets('pulseInside $theme $paletteName', (tester) async { - await capture( - tester, - 'pulse_inside_${theme}_$paletteName', - brightness: brightness, - (b) => BorderBeam.pulseInside( - colors: colors, - style: BeamStyle(theme: beamTheme), - child: mockSurface(b), - ), - ); - }); - - testWidgets('pulseOutside $theme $paletteName', (tester) async { - await capture( - tester, - 'pulse_outside_${theme}_$paletteName', - brightness: brightness, - (b) => BorderBeam.pulseOutside( - colors: colors, - style: BeamStyle(theme: beamTheme), - child: mockSurface(b), - ), - ); - }); + final later = late[effect.name]; + if (later != null) { + testWidgets('${effect.name} $theme colorful late', (tester) async { + await captureGolden( + tester, + '${effect.name}_${theme}_colorful_late', + goldenScene(beam(effect, brightness), brightness: brightness), + freeze: later, + ); + }); + } } - // Second freezes for the traveling variants. rotate's 1.96s cycle puts - // 2.3s at cycle fraction 0.17 (vs 0.66 at 1.3s) — the beam is on the - // opposite side of the border. line's 3.1s cycle puts 2.0s at fraction - // 0.645, still inside the [0.325, 0.675] window where `beam-edge-fade` - // holds at 1, so the beam is at full strength further along its travel - // (x 0.60 vs 0.45 at 1.3s). - testWidgets('rotate $theme colorful late', (tester) async { - await capture( - tester, - 'rotate_${theme}_colorful_late', - brightness: brightness, - freeze: const Duration(milliseconds: 2300), - (b) => BorderBeam.rotate( - style: BeamStyle(theme: beamTheme), - child: mockSurface(b), - ), - ); - }); - - testWidgets('line $theme colorful late', (tester) async { - await capture( - tester, - 'line_${theme}_colorful_late', - brightness: brightness, - freeze: const Duration(milliseconds: 2000), - (b) => BorderBeam.line( - style: BeamStyle(theme: beamTheme), - child: mockSurface(b), - ), - ); - }); + for (final effect in BeamEffect.values) { + for (final MapEntry(key: palette, value: colors) in { + 'mono': BeamColors.mono, + 'ocean': BeamColors.ocean, + 'sunset': BeamColors.sunset, + }.entries) { + testWidgets('${effect.name} $theme $palette', (tester) async { + await captureGolden( + tester, + '${effect.name}_${theme}_$palette', + goldenScene( + beam(effect, brightness, colors: colors), + brightness: brightness, + ), + ); + }); + } + } - testWidgets('rotate $theme ocean superellipse', (tester) async { - await capture( + // The small-chip size the old `small` variant was made for: rotate + // scales its glow down with the box. + testWidgets('rotate $theme chip', (tester) async { + await captureGolden( tester, - 'rotate_${theme}_ocean_squircle', - brightness: brightness, - (b) => BorderBeam.rotate( - colors: BeamColors.ocean, - style: BeamStyle(theme: beamTheme), - shape: const BeamShape(superellipse: true), - borderRadius: 28, - child: mockSurface(b, radius: 28), + 'rotate_${theme}_chip', + goldenScene( + beam(const BeamEffect.rotate(), brightness, radius: 18), + brightness: brightness, + size: const Size(70, 36), ), ); }); } - testWidgets('rotate dark custom palette', (tester) async { - await capture( + testWidgets('rotate dark comet', (tester) async { + await captureGolden( tester, - 'rotate_dark_custom', - brightness: Brightness.dark, - (b) => BorderBeam.rotate( - colors: const BeamColors.custom([ - Color(0xFFFF0080), - Color(0xFF00E5FF), - Color(0xFFFFC400), - ]), - style: const BeamStyle(theme: BeamTheme.dark), - child: mockSurface(b), - ), + 'rotate_dark_comet', + goldenScene(beam(const BeamEffect.rotate(comet: true), Brightness.dark)), ); }); - // Per-corner and stadium geometry, dark/colorful only: the shape is what - // these scenes are about, so one palette is enough. - const cornerRadii = BorderRadius.only( - topLeft: Radius.circular(40), - bottomRight: Radius.circular(40), - ); - - testWidgets('rotate dark colorful per-corner radii', (tester) async { - await capture( - tester, - 'rotate_dark_colorful_corners', - brightness: Brightness.dark, - (b) => BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark), - shape: const BeamShape(radius: cornerRadii), - child: mockSurface(b, radii: cornerRadii), - ), - ); - }); - - testWidgets('rotate dark colorful per-corner superellipse', (tester) async { - await capture( + testWidgets('rotate dark long tail', (tester) async { + await captureGolden( tester, - 'rotate_dark_colorful_corners_squircle', - brightness: Brightness.dark, - (b) => BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark), - shape: const BeamShape(radius: cornerRadii, superellipse: true), - child: mockSurface(b, radii: cornerRadii), - ), + 'rotate_dark_long_tail', + goldenScene(beam(const BeamEffect.rotate(length: 2), Brightness.dark)), ); }); - // A 350x60 box: the stadium radius clamps to 30 on every corner, so the - // beam travels a pill and the surface matches it. - testWidgets('rotate dark colorful stadium', (tester) async { - await capture( + testWidgets('rotate dark glow 2', (tester) async { + await captureGolden( tester, - 'rotate_dark_colorful_stadium', - brightness: Brightness.dark, - height: 60, - (b) => BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark), - shape: const BeamShape.stadium(), - child: mockSurface(b, radius: 30), - ), - ); - }); - - testWidgets('line dark colorful stadium', (tester) async { - await capture( - tester, - 'line_dark_colorful_stadium', - brightness: Brightness.dark, - height: 60, - (b) => BorderBeam.line( - style: const BeamStyle(theme: BeamTheme.dark), - shape: const BeamShape.stadium(), - child: mockSurface(b, radius: 30), + 'rotate_dark_glow_2', + goldenScene( + beam( + const BeamEffect.rotate(), + Brightness.dark, + style: const BeamStyle(glow: 2), + ), ), ); }); diff --git a/test/golden/golden_scene.dart b/test/golden/golden_scene.dart new file mode 100644 index 0000000..2811c7f --- /dev/null +++ b/test/golden/golden_scene.dart @@ -0,0 +1,122 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Shared staging for the golden families. +/// +/// Every scene is a beam over a mock surface, centred on the demo backdrop +/// with [goldenMargin] of clear room on every side — outward light (a comet, +/// a positive ring offset) paints past the box and must land in the +/// image, not off it. Only that keyed region is captured, so the PNGs stay +/// small and an unrelated change to the test surface size moves nothing. +/// +/// Scenes freeze the fake test clock at [goldenFreeze] after activation — +/// past the fade-in (`BeamClock.fadeInSeconds`), mid-cycle — so each image +/// is one representative animated frame, deterministic run to run. +/// +/// Regenerate (macOS, on the SDK `ci.yaml` pins): +/// flutter test --update-goldens --tags golden + +/// The instant every scene is captured at, unless it says otherwise. +const Duration goldenFreeze = Duration(milliseconds: 1300); + +/// Clear room around the beam's box. +const double goldenMargin = 100; + +/// The card every scene lights unless it needs another size. +const Size goldenCard = Size(350, 140); + +const Key _captureKey = ValueKey('golden-capture'); + +/// The demo backdrop for [brightness]. +Color backdropFor(Brightness brightness) => brightness == Brightness.dark + ? const Color(0xFF070707) + : const Color(0xFFFDFDFD); + +/// The card surface a beam is painted around, matching the beam's corners. +/// +/// [radii] gives per-corner radii; [superellipse] clips the card with +/// Flutter's own superellipse so the scene shows whether the beam's stroke +/// sits on the card's edge. +Widget mockSurface( + Brightness brightness, { + double radius = 16, + BorderRadius? radii, + bool superellipse = false, +}) { + final dark = brightness == Brightness.dark; + final fill = dark ? const Color(0xFF1D1D1D) : const Color(0xFFFFFFFF); + final edge = BorderSide( + color: dark ? const Color(0x14FFFFFF) : const Color(0x14000000), + ); + final corners = radii ?? BorderRadius.circular(radius); + return DecoratedBox( + decoration: ShapeDecoration( + color: fill, + shape: superellipse + ? RoundedSuperellipseBorder(borderRadius: corners, side: edge) + : RoundedRectangleBorder(borderRadius: corners, side: edge), + ), + ); +} + +/// Stages [child] at [size] on the backdrop for [brightness]. +Widget goldenScene( + Widget child, { + Brightness brightness = Brightness.dark, + Size size = goldenCard, +}) => MaterialApp( + debugShowCheckedModeBanner: false, + theme: ThemeData(brightness: brightness), + home: Center( + child: RepaintBoundary( + key: _captureKey, + child: ColoredBox( + color: backdropFor(brightness), + child: Padding( + padding: const EdgeInsets.all(goldenMargin), + child: SizedBox.fromSize(size: size, child: child), + ), + ), + ), + ), +); + +/// Pumps [scene], runs the clock to [freeze], and matches the staged region +/// against `goldens/[name].png`. +/// +/// [beforeFreeze] runs after the first frame and before the clock advances — +/// the hook for a hover, a press, or a focus request. +/// +/// The clock normally jumps straight to [freeze]: every animated value is a +/// pure function of elapsed time. [frameByFrame] advances it in 60Hz frames +/// instead, for the one thing that integrates per frame — the eased +/// `BorderBeam.follow`, which ignores a single step longer than a frame +/// burst. +Future captureGolden( + WidgetTester tester, + String name, + Widget scene, { + Duration freeze = goldenFreeze, + Future Function()? beforeFreeze, + bool frameByFrame = false, +}) async { + await tester.pumpWidget(scene); + await beforeFreeze?.call(); + // The first tick after a ticker starts reports zero elapsed time. + await tester.pump(); + if (frameByFrame) { + const frame = Duration(microseconds: 16667); + var left = freeze; + while (left > frame) { + await tester.pump(frame); + left -= frame; + } + await tester.pump(left); + } else { + await tester.pump(freeze); + } + await expectLater( + find.byKey(_captureKey), + matchesGoldenFile('goldens/$name.png'), + ); +} diff --git a/test/golden/goldens/line_dark_colorful.png b/test/golden/goldens/line_dark_colorful.png index 6c6514d..a303e18 100644 Binary files a/test/golden/goldens/line_dark_colorful.png and b/test/golden/goldens/line_dark_colorful.png differ diff --git a/test/golden/goldens/line_dark_colorful_late.png b/test/golden/goldens/line_dark_colorful_late.png index ca5d780..4697249 100644 Binary files a/test/golden/goldens/line_dark_colorful_late.png and b/test/golden/goldens/line_dark_colorful_late.png differ diff --git a/test/golden/goldens/line_dark_colorful_stadium.png b/test/golden/goldens/line_dark_colorful_stadium.png deleted file mode 100644 index f8a2fae..0000000 Binary files a/test/golden/goldens/line_dark_colorful_stadium.png and /dev/null differ diff --git a/test/golden/goldens/line_dark_mono.png b/test/golden/goldens/line_dark_mono.png index c61124f..69210e4 100644 Binary files a/test/golden/goldens/line_dark_mono.png and b/test/golden/goldens/line_dark_mono.png differ diff --git a/test/golden/goldens/line_dark_ocean.png b/test/golden/goldens/line_dark_ocean.png index 80d34ff..85ed80d 100644 Binary files a/test/golden/goldens/line_dark_ocean.png and b/test/golden/goldens/line_dark_ocean.png differ diff --git a/test/golden/goldens/line_dark_sunset.png b/test/golden/goldens/line_dark_sunset.png index a4189ff..d9a1b6c 100644 Binary files a/test/golden/goldens/line_dark_sunset.png and b/test/golden/goldens/line_dark_sunset.png differ diff --git a/test/golden/goldens/line_light_colorful.png b/test/golden/goldens/line_light_colorful.png index bde49ba..99dbb19 100644 Binary files a/test/golden/goldens/line_light_colorful.png and b/test/golden/goldens/line_light_colorful.png differ diff --git a/test/golden/goldens/line_light_colorful_late.png b/test/golden/goldens/line_light_colorful_late.png index 2a8d7fd..fa59bb0 100644 Binary files a/test/golden/goldens/line_light_colorful_late.png and b/test/golden/goldens/line_light_colorful_late.png differ diff --git a/test/golden/goldens/line_light_mono.png b/test/golden/goldens/line_light_mono.png index df2dab0..33135f4 100644 Binary files a/test/golden/goldens/line_light_mono.png and b/test/golden/goldens/line_light_mono.png differ diff --git a/test/golden/goldens/line_light_ocean.png b/test/golden/goldens/line_light_ocean.png index 543c62d..b3196c7 100644 Binary files a/test/golden/goldens/line_light_ocean.png and b/test/golden/goldens/line_light_ocean.png differ diff --git a/test/golden/goldens/line_light_sunset.png b/test/golden/goldens/line_light_sunset.png index 85490f1..3129923 100644 Binary files a/test/golden/goldens/line_light_sunset.png and b/test/golden/goldens/line_light_sunset.png differ diff --git a/test/golden/goldens/motion_line_reverse.png b/test/golden/goldens/motion_line_reverse.png index de172d5..72cf4d8 100644 Binary files a/test/golden/goldens/motion_line_reverse.png and b/test/golden/goldens/motion_line_reverse.png differ diff --git a/test/golden/goldens/motion_progress_0_5.png b/test/golden/goldens/motion_progress_0_5.png deleted file mode 100644 index f7066a6..0000000 Binary files a/test/golden/goldens/motion_progress_0_5.png and /dev/null differ diff --git a/test/golden/goldens/motion_progress_line_0_5.png b/test/golden/goldens/motion_progress_line_0_5.png new file mode 100644 index 0000000..71eb1da Binary files /dev/null and b/test/golden/goldens/motion_progress_line_0_5.png differ diff --git a/test/golden/goldens/motion_progress_rotate_0_5.png b/test/golden/goldens/motion_progress_rotate_0_5.png new file mode 100644 index 0000000..1fa7d6f Binary files /dev/null and b/test/golden/goldens/motion_progress_rotate_0_5.png differ diff --git a/test/golden/goldens/motion_rotate_beamcount2.png b/test/golden/goldens/motion_rotate_beamcount2.png deleted file mode 100644 index d191e36..0000000 Binary files a/test/golden/goldens/motion_rotate_beamcount2.png and /dev/null differ diff --git a/test/golden/goldens/motion_rotate_bounce_second_cycle.png b/test/golden/goldens/motion_rotate_bounce_second_cycle.png new file mode 100644 index 0000000..d757bef Binary files /dev/null and b/test/golden/goldens/motion_rotate_bounce_second_cycle.png differ diff --git a/test/golden/goldens/motion_rotate_count_2.png b/test/golden/goldens/motion_rotate_count_2.png new file mode 100644 index 0000000..28560a2 Binary files /dev/null and b/test/golden/goldens/motion_rotate_count_2.png differ diff --git a/test/golden/goldens/motion_rotate_count_4.png b/test/golden/goldens/motion_rotate_count_4.png new file mode 100644 index 0000000..688236f Binary files /dev/null and b/test/golden/goldens/motion_rotate_count_4.png differ diff --git a/test/golden/goldens/motion_rotate_cycle_gap_fading.png b/test/golden/goldens/motion_rotate_cycle_gap_fading.png new file mode 100644 index 0000000..c46980d Binary files /dev/null and b/test/golden/goldens/motion_rotate_cycle_gap_fading.png differ diff --git a/test/golden/goldens/motion_rotate_phase_offset_half.png b/test/golden/goldens/motion_rotate_phase_offset_half.png new file mode 100644 index 0000000..f3cd4d8 Binary files /dev/null and b/test/golden/goldens/motion_rotate_phase_offset_half.png differ diff --git a/test/golden/goldens/motion_rotate_reverse.png b/test/golden/goldens/motion_rotate_reverse.png index f4db45c..0119413 100644 Binary files a/test/golden/goldens/motion_rotate_reverse.png and b/test/golden/goldens/motion_rotate_reverse.png differ diff --git a/test/golden/goldens/palette_aurora.png b/test/golden/goldens/palette_aurora.png index ac36fd7..ea45cc7 100644 Binary files a/test/golden/goldens/palette_aurora.png and b/test/golden/goldens/palette_aurora.png differ diff --git a/test/golden/goldens/palette_candy.png b/test/golden/goldens/palette_candy.png index 574a51f..26ca83c 100644 Binary files a/test/golden/goldens/palette_candy.png and b/test/golden/goldens/palette_candy.png differ diff --git a/test/golden/goldens/palette_citrus.png b/test/golden/goldens/palette_citrus.png new file mode 100644 index 0000000..1fb308b Binary files /dev/null and b/test/golden/goldens/palette_citrus.png differ diff --git a/test/golden/goldens/palette_colorful.png b/test/golden/goldens/palette_colorful.png new file mode 100644 index 0000000..58da143 Binary files /dev/null and b/test/golden/goldens/palette_colorful.png differ diff --git a/test/golden/goldens/palette_colorful_hue_base_120.png b/test/golden/goldens/palette_colorful_hue_base_120.png new file mode 100644 index 0000000..0934d12 Binary files /dev/null and b/test/golden/goldens/palette_colorful_hue_base_120.png differ diff --git a/test/golden/goldens/palette_cosmic.png b/test/golden/goldens/palette_cosmic.png new file mode 100644 index 0000000..339fdde Binary files /dev/null and b/test/golden/goldens/palette_cosmic.png differ diff --git a/test/golden/goldens/palette_custom.png b/test/golden/goldens/palette_custom.png new file mode 100644 index 0000000..9d4fa17 Binary files /dev/null and b/test/golden/goldens/palette_custom.png differ diff --git a/test/golden/goldens/palette_custom_stops.png b/test/golden/goldens/palette_custom_stops.png new file mode 100644 index 0000000..42baeae Binary files /dev/null and b/test/golden/goldens/palette_custom_stops.png differ diff --git a/test/golden/goldens/palette_dusk.png b/test/golden/goldens/palette_dusk.png new file mode 100644 index 0000000..d3e4145 Binary files /dev/null and b/test/golden/goldens/palette_dusk.png differ diff --git a/test/golden/goldens/palette_ember.png b/test/golden/goldens/palette_ember.png index e642597..dcdd275 100644 Binary files a/test/golden/goldens/palette_ember.png and b/test/golden/goldens/palette_ember.png differ diff --git a/test/golden/goldens/palette_forest.png b/test/golden/goldens/palette_forest.png new file mode 100644 index 0000000..9e9e2c9 Binary files /dev/null and b/test/golden/goldens/palette_forest.png differ diff --git a/test/golden/goldens/palette_from_seed.png b/test/golden/goldens/palette_from_seed.png deleted file mode 100644 index 255f983..0000000 Binary files a/test/golden/goldens/palette_from_seed.png and /dev/null differ diff --git a/test/golden/goldens/palette_gold.png b/test/golden/goldens/palette_gold.png index 14329d7..d4e081c 100644 Binary files a/test/golden/goldens/palette_gold.png and b/test/golden/goldens/palette_gold.png differ diff --git a/test/golden/goldens/palette_holographic.png b/test/golden/goldens/palette_holographic.png index 2e74193..26ebd41 100644 Binary files a/test/golden/goldens/palette_holographic.png and b/test/golden/goldens/palette_holographic.png differ diff --git a/test/golden/goldens/palette_ice.png b/test/golden/goldens/palette_ice.png index 64d26aa..f8c9279 100644 Binary files a/test/golden/goldens/palette_ice.png and b/test/golden/goldens/palette_ice.png differ diff --git a/test/golden/goldens/palette_lagoon.png b/test/golden/goldens/palette_lagoon.png new file mode 100644 index 0000000..6c9d1b9 Binary files /dev/null and b/test/golden/goldens/palette_lagoon.png differ diff --git a/test/golden/goldens/palette_lavender.png b/test/golden/goldens/palette_lavender.png new file mode 100644 index 0000000..bf04d47 Binary files /dev/null and b/test/golden/goldens/palette_lavender.png differ diff --git a/test/golden/goldens/palette_lerp_ocean_sunset.png b/test/golden/goldens/palette_lerp_ocean_sunset.png index 8927a17..0c5add7 100644 Binary files a/test/golden/goldens/palette_lerp_ocean_sunset.png and b/test/golden/goldens/palette_lerp_ocean_sunset.png differ diff --git a/test/golden/goldens/palette_mono.png b/test/golden/goldens/palette_mono.png new file mode 100644 index 0000000..17d644a Binary files /dev/null and b/test/golden/goldens/palette_mono.png differ diff --git a/test/golden/goldens/palette_neon.png b/test/golden/goldens/palette_neon.png index 3e94e4b..e85fe3a 100644 Binary files a/test/golden/goldens/palette_neon.png and b/test/golden/goldens/palette_neon.png differ diff --git a/test/golden/goldens/palette_ocean.png b/test/golden/goldens/palette_ocean.png new file mode 100644 index 0000000..9213201 Binary files /dev/null and b/test/golden/goldens/palette_ocean.png differ diff --git a/test/golden/goldens/palette_rose.png b/test/golden/goldens/palette_rose.png new file mode 100644 index 0000000..41e194c Binary files /dev/null and b/test/golden/goldens/palette_rose.png differ diff --git a/test/golden/goldens/palette_scale_alpha_half.png b/test/golden/goldens/palette_scale_alpha_half.png new file mode 100644 index 0000000..856446c Binary files /dev/null and b/test/golden/goldens/palette_scale_alpha_half.png differ diff --git a/test/golden/goldens/palette_scheme.png b/test/golden/goldens/palette_scheme.png new file mode 100644 index 0000000..8cb5403 Binary files /dev/null and b/test/golden/goldens/palette_scheme.png differ diff --git a/test/golden/goldens/palette_seed_analogous.png b/test/golden/goldens/palette_seed_analogous.png new file mode 100644 index 0000000..f624fa0 Binary files /dev/null and b/test/golden/goldens/palette_seed_analogous.png differ diff --git a/test/golden/goldens/palette_seed_complementary.png b/test/golden/goldens/palette_seed_complementary.png new file mode 100644 index 0000000..a33cee7 Binary files /dev/null and b/test/golden/goldens/palette_seed_complementary.png differ diff --git a/test/golden/goldens/palette_seed_monochrome.png b/test/golden/goldens/palette_seed_monochrome.png new file mode 100644 index 0000000..77214b7 Binary files /dev/null and b/test/golden/goldens/palette_seed_monochrome.png differ diff --git a/test/golden/goldens/palette_seed_triadic.png b/test/golden/goldens/palette_seed_triadic.png new file mode 100644 index 0000000..bfbd148 Binary files /dev/null and b/test/golden/goldens/palette_seed_triadic.png differ diff --git a/test/golden/goldens/palette_sky.png b/test/golden/goldens/palette_sky.png new file mode 100644 index 0000000..0b77bbf Binary files /dev/null and b/test/golden/goldens/palette_sky.png differ diff --git a/test/golden/goldens/palette_solid.png b/test/golden/goldens/palette_solid.png new file mode 100644 index 0000000..ed4b17a Binary files /dev/null and b/test/golden/goldens/palette_solid.png differ diff --git a/test/golden/goldens/palette_sunset.png b/test/golden/goldens/palette_sunset.png new file mode 100644 index 0000000..bc77118 Binary files /dev/null and b/test/golden/goldens/palette_sunset.png differ diff --git a/test/golden/goldens/pulse_dark_colorful.png b/test/golden/goldens/pulse_dark_colorful.png new file mode 100644 index 0000000..129cc8b Binary files /dev/null and b/test/golden/goldens/pulse_dark_colorful.png differ diff --git a/test/golden/goldens/pulse_dark_mono.png b/test/golden/goldens/pulse_dark_mono.png new file mode 100644 index 0000000..17d644a Binary files /dev/null and b/test/golden/goldens/pulse_dark_mono.png differ diff --git a/test/golden/goldens/pulse_dark_ocean.png b/test/golden/goldens/pulse_dark_ocean.png new file mode 100644 index 0000000..bfa2a55 Binary files /dev/null and b/test/golden/goldens/pulse_dark_ocean.png differ diff --git a/test/golden/goldens/pulse_dark_sunset.png b/test/golden/goldens/pulse_dark_sunset.png new file mode 100644 index 0000000..2d104b7 Binary files /dev/null and b/test/golden/goldens/pulse_dark_sunset.png differ diff --git a/test/golden/goldens/pulse_inside_dark_colorful.png b/test/golden/goldens/pulse_inside_dark_colorful.png deleted file mode 100644 index 3468dd0..0000000 Binary files a/test/golden/goldens/pulse_inside_dark_colorful.png and /dev/null differ diff --git a/test/golden/goldens/pulse_inside_dark_mono.png b/test/golden/goldens/pulse_inside_dark_mono.png deleted file mode 100644 index 9ec741b..0000000 Binary files a/test/golden/goldens/pulse_inside_dark_mono.png and /dev/null differ diff --git a/test/golden/goldens/pulse_inside_dark_ocean.png b/test/golden/goldens/pulse_inside_dark_ocean.png deleted file mode 100644 index c9a4b3b..0000000 Binary files a/test/golden/goldens/pulse_inside_dark_ocean.png and /dev/null differ diff --git a/test/golden/goldens/pulse_inside_dark_sunset.png b/test/golden/goldens/pulse_inside_dark_sunset.png deleted file mode 100644 index ba8ed96..0000000 Binary files a/test/golden/goldens/pulse_inside_dark_sunset.png and /dev/null differ diff --git a/test/golden/goldens/pulse_inside_light_colorful.png b/test/golden/goldens/pulse_inside_light_colorful.png deleted file mode 100644 index 9015be2..0000000 Binary files a/test/golden/goldens/pulse_inside_light_colorful.png and /dev/null differ diff --git a/test/golden/goldens/pulse_inside_light_mono.png b/test/golden/goldens/pulse_inside_light_mono.png deleted file mode 100644 index 7226559..0000000 Binary files a/test/golden/goldens/pulse_inside_light_mono.png and /dev/null differ diff --git a/test/golden/goldens/pulse_inside_light_ocean.png b/test/golden/goldens/pulse_inside_light_ocean.png deleted file mode 100644 index bf918af..0000000 Binary files a/test/golden/goldens/pulse_inside_light_ocean.png and /dev/null differ diff --git a/test/golden/goldens/pulse_inside_light_sunset.png b/test/golden/goldens/pulse_inside_light_sunset.png deleted file mode 100644 index e42dda0..0000000 Binary files a/test/golden/goldens/pulse_inside_light_sunset.png and /dev/null differ diff --git a/test/golden/goldens/pulse_light_colorful.png b/test/golden/goldens/pulse_light_colorful.png new file mode 100644 index 0000000..207b81c Binary files /dev/null and b/test/golden/goldens/pulse_light_colorful.png differ diff --git a/test/golden/goldens/pulse_light_mono.png b/test/golden/goldens/pulse_light_mono.png new file mode 100644 index 0000000..f1a06b8 Binary files /dev/null and b/test/golden/goldens/pulse_light_mono.png differ diff --git a/test/golden/goldens/pulse_light_ocean.png b/test/golden/goldens/pulse_light_ocean.png new file mode 100644 index 0000000..5d1dc26 Binary files /dev/null and b/test/golden/goldens/pulse_light_ocean.png differ diff --git a/test/golden/goldens/pulse_light_sunset.png b/test/golden/goldens/pulse_light_sunset.png new file mode 100644 index 0000000..1644295 Binary files /dev/null and b/test/golden/goldens/pulse_light_sunset.png differ diff --git a/test/golden/goldens/pulse_outside_dark_colorful.png b/test/golden/goldens/pulse_outside_dark_colorful.png deleted file mode 100644 index 517df9c..0000000 Binary files a/test/golden/goldens/pulse_outside_dark_colorful.png and /dev/null differ diff --git a/test/golden/goldens/pulse_outside_dark_mono.png b/test/golden/goldens/pulse_outside_dark_mono.png deleted file mode 100644 index 8acc814..0000000 Binary files a/test/golden/goldens/pulse_outside_dark_mono.png and /dev/null differ diff --git a/test/golden/goldens/pulse_outside_dark_ocean.png b/test/golden/goldens/pulse_outside_dark_ocean.png deleted file mode 100644 index 2001630..0000000 Binary files a/test/golden/goldens/pulse_outside_dark_ocean.png and /dev/null differ diff --git a/test/golden/goldens/pulse_outside_dark_sunset.png b/test/golden/goldens/pulse_outside_dark_sunset.png deleted file mode 100644 index 35d46c2..0000000 Binary files a/test/golden/goldens/pulse_outside_dark_sunset.png and /dev/null differ diff --git a/test/golden/goldens/pulse_outside_light_colorful.png b/test/golden/goldens/pulse_outside_light_colorful.png deleted file mode 100644 index 76cd13f..0000000 Binary files a/test/golden/goldens/pulse_outside_light_colorful.png and /dev/null differ diff --git a/test/golden/goldens/pulse_outside_light_mono.png b/test/golden/goldens/pulse_outside_light_mono.png deleted file mode 100644 index 02ab189..0000000 Binary files a/test/golden/goldens/pulse_outside_light_mono.png and /dev/null differ diff --git a/test/golden/goldens/pulse_outside_light_ocean.png b/test/golden/goldens/pulse_outside_light_ocean.png deleted file mode 100644 index 4db2818..0000000 Binary files a/test/golden/goldens/pulse_outside_light_ocean.png and /dev/null differ diff --git a/test/golden/goldens/pulse_outside_light_sunset.png b/test/golden/goldens/pulse_outside_light_sunset.png deleted file mode 100644 index d8102d9..0000000 Binary files a/test/golden/goldens/pulse_outside_light_sunset.png and /dev/null differ diff --git a/test/golden/goldens/research_pulse_inside_inner_scale_0_6.png b/test/golden/goldens/research_pulse_inside_inner_scale_0_6.png deleted file mode 100644 index 0f61c20..0000000 Binary files a/test/golden/goldens/research_pulse_inside_inner_scale_0_6.png and /dev/null differ diff --git a/test/golden/goldens/research_pulse_outside_stock_dark.png b/test/golden/goldens/research_pulse_outside_stock_dark.png deleted file mode 100644 index 8e8162e..0000000 Binary files a/test/golden/goldens/research_pulse_outside_stock_dark.png and /dev/null differ diff --git a/test/golden/goldens/research_pulse_outside_stock_light.png b/test/golden/goldens/research_pulse_outside_stock_light.png deleted file mode 100644 index 111d01f..0000000 Binary files a/test/golden/goldens/research_pulse_outside_stock_light.png and /dev/null differ diff --git a/test/golden/goldens/research_rotate_large_default.png b/test/golden/goldens/research_rotate_large_default.png deleted file mode 100644 index 4377a9f..0000000 Binary files a/test/golden/goldens/research_rotate_large_default.png and /dev/null differ diff --git a/test/golden/goldens/research_rotate_render_scale_0_5.png b/test/golden/goldens/research_rotate_render_scale_0_5.png deleted file mode 100644 index 8e1245e..0000000 Binary files a/test/golden/goldens/research_rotate_render_scale_0_5.png and /dev/null differ diff --git a/test/golden/goldens/rotate_dark_chip.png b/test/golden/goldens/rotate_dark_chip.png new file mode 100644 index 0000000..fc93512 Binary files /dev/null and b/test/golden/goldens/rotate_dark_chip.png differ diff --git a/test/golden/goldens/rotate_dark_colorful.png b/test/golden/goldens/rotate_dark_colorful.png index 583837f..908c959 100644 Binary files a/test/golden/goldens/rotate_dark_colorful.png and b/test/golden/goldens/rotate_dark_colorful.png differ diff --git a/test/golden/goldens/rotate_dark_colorful_corners.png b/test/golden/goldens/rotate_dark_colorful_corners.png deleted file mode 100644 index 765c6f5..0000000 Binary files a/test/golden/goldens/rotate_dark_colorful_corners.png and /dev/null differ diff --git a/test/golden/goldens/rotate_dark_colorful_corners_squircle.png b/test/golden/goldens/rotate_dark_colorful_corners_squircle.png deleted file mode 100644 index cb82e9f..0000000 Binary files a/test/golden/goldens/rotate_dark_colorful_corners_squircle.png and /dev/null differ diff --git a/test/golden/goldens/rotate_dark_colorful_late.png b/test/golden/goldens/rotate_dark_colorful_late.png index a386550..4adba73 100644 Binary files a/test/golden/goldens/rotate_dark_colorful_late.png and b/test/golden/goldens/rotate_dark_colorful_late.png differ diff --git a/test/golden/goldens/rotate_dark_colorful_stadium.png b/test/golden/goldens/rotate_dark_colorful_stadium.png deleted file mode 100644 index 6bdaefc..0000000 Binary files a/test/golden/goldens/rotate_dark_colorful_stadium.png and /dev/null differ diff --git a/test/golden/goldens/rotate_dark_comet.png b/test/golden/goldens/rotate_dark_comet.png new file mode 100644 index 0000000..b68978c Binary files /dev/null and b/test/golden/goldens/rotate_dark_comet.png differ diff --git a/test/golden/goldens/rotate_dark_custom.png b/test/golden/goldens/rotate_dark_custom.png deleted file mode 100644 index 310c35a..0000000 Binary files a/test/golden/goldens/rotate_dark_custom.png and /dev/null differ diff --git a/test/golden/goldens/rotate_dark_glow_2.png b/test/golden/goldens/rotate_dark_glow_2.png new file mode 100644 index 0000000..39ce424 Binary files /dev/null and b/test/golden/goldens/rotate_dark_glow_2.png differ diff --git a/test/golden/goldens/rotate_dark_long_tail.png b/test/golden/goldens/rotate_dark_long_tail.png new file mode 100644 index 0000000..60a7597 Binary files /dev/null and b/test/golden/goldens/rotate_dark_long_tail.png differ diff --git a/test/golden/goldens/rotate_dark_mono.png b/test/golden/goldens/rotate_dark_mono.png index 40e6e3c..4fbf183 100644 Binary files a/test/golden/goldens/rotate_dark_mono.png and b/test/golden/goldens/rotate_dark_mono.png differ diff --git a/test/golden/goldens/rotate_dark_ocean.png b/test/golden/goldens/rotate_dark_ocean.png index 5a3223b..a3bb245 100644 Binary files a/test/golden/goldens/rotate_dark_ocean.png and b/test/golden/goldens/rotate_dark_ocean.png differ diff --git a/test/golden/goldens/rotate_dark_ocean_squircle.png b/test/golden/goldens/rotate_dark_ocean_squircle.png deleted file mode 100644 index 5077051..0000000 Binary files a/test/golden/goldens/rotate_dark_ocean_squircle.png and /dev/null differ diff --git a/test/golden/goldens/rotate_dark_sunset.png b/test/golden/goldens/rotate_dark_sunset.png index 6c25e60..95922a5 100644 Binary files a/test/golden/goldens/rotate_dark_sunset.png and b/test/golden/goldens/rotate_dark_sunset.png differ diff --git a/test/golden/goldens/rotate_light_chip.png b/test/golden/goldens/rotate_light_chip.png new file mode 100644 index 0000000..dd3d8da Binary files /dev/null and b/test/golden/goldens/rotate_light_chip.png differ diff --git a/test/golden/goldens/rotate_light_colorful.png b/test/golden/goldens/rotate_light_colorful.png index 0e27e13..4ec02ca 100644 Binary files a/test/golden/goldens/rotate_light_colorful.png and b/test/golden/goldens/rotate_light_colorful.png differ diff --git a/test/golden/goldens/rotate_light_colorful_late.png b/test/golden/goldens/rotate_light_colorful_late.png index 8307de2..27a4676 100644 Binary files a/test/golden/goldens/rotate_light_colorful_late.png and b/test/golden/goldens/rotate_light_colorful_late.png differ diff --git a/test/golden/goldens/rotate_light_mono.png b/test/golden/goldens/rotate_light_mono.png index f266546..95d3f71 100644 Binary files a/test/golden/goldens/rotate_light_mono.png and b/test/golden/goldens/rotate_light_mono.png differ diff --git a/test/golden/goldens/rotate_light_ocean.png b/test/golden/goldens/rotate_light_ocean.png index 727e24d..cee8acc 100644 Binary files a/test/golden/goldens/rotate_light_ocean.png and b/test/golden/goldens/rotate_light_ocean.png differ diff --git a/test/golden/goldens/rotate_light_ocean_squircle.png b/test/golden/goldens/rotate_light_ocean_squircle.png deleted file mode 100644 index 2a4ff98..0000000 Binary files a/test/golden/goldens/rotate_light_ocean_squircle.png and /dev/null differ diff --git a/test/golden/goldens/rotate_light_sunset.png b/test/golden/goldens/rotate_light_sunset.png index a49d51e..d61d314 100644 Binary files a/test/golden/goldens/rotate_light_sunset.png and b/test/golden/goldens/rotate_light_sunset.png differ diff --git a/test/golden/goldens/segment_line_bottom_half.png b/test/golden/goldens/segment_line_bottom_half.png deleted file mode 100644 index c8b7d70..0000000 Binary files a/test/golden/goldens/segment_line_bottom_half.png and /dev/null differ diff --git a/test/golden/goldens/segment_line_bottom_half_late.png b/test/golden/goldens/segment_line_bottom_half_late.png deleted file mode 100644 index e182edb..0000000 Binary files a/test/golden/goldens/segment_line_bottom_half_late.png and /dev/null differ diff --git a/test/golden/goldens/segment_line_wrap_corners.png b/test/golden/goldens/segment_line_wrap_corners.png deleted file mode 100644 index f5f2b23..0000000 Binary files a/test/golden/goldens/segment_line_wrap_corners.png and /dev/null differ diff --git a/test/golden/goldens/segment_pulse_inside_bottom_half.png b/test/golden/goldens/segment_pulse_inside_bottom_half.png deleted file mode 100644 index 95c588c..0000000 Binary files a/test/golden/goldens/segment_pulse_inside_bottom_half.png and /dev/null differ diff --git a/test/golden/goldens/segment_pulse_outside_bottom_half.png b/test/golden/goldens/segment_pulse_outside_bottom_half.png deleted file mode 100644 index f460b23..0000000 Binary files a/test/golden/goldens/segment_pulse_outside_bottom_half.png and /dev/null differ diff --git a/test/golden/goldens/segment_rotate_bottom_half.png b/test/golden/goldens/segment_rotate_bottom_half.png deleted file mode 100644 index 6cba8fe..0000000 Binary files a/test/golden/goldens/segment_rotate_bottom_half.png and /dev/null differ diff --git a/test/golden/goldens/segment_rotate_bottom_half_late.png b/test/golden/goldens/segment_rotate_bottom_half_late.png deleted file mode 100644 index 35aa876..0000000 Binary files a/test/golden/goldens/segment_rotate_bottom_half_late.png and /dev/null differ diff --git a/test/golden/goldens/segment_rotate_feather_0.png b/test/golden/goldens/segment_rotate_feather_0.png deleted file mode 100644 index d839248..0000000 Binary files a/test/golden/goldens/segment_rotate_feather_0.png and /dev/null differ diff --git a/test/golden/goldens/segment_rotate_top_edge.png b/test/golden/goldens/segment_rotate_top_edge.png deleted file mode 100644 index 516c7a2..0000000 Binary files a/test/golden/goldens/segment_rotate_top_edge.png and /dev/null differ diff --git a/test/golden/goldens/segment_small_bottom_half.png b/test/golden/goldens/segment_small_bottom_half.png deleted file mode 100644 index b8aff49..0000000 Binary files a/test/golden/goldens/segment_small_bottom_half.png and /dev/null differ diff --git a/test/golden/goldens/small_dark_colorful.png b/test/golden/goldens/small_dark_colorful.png deleted file mode 100644 index 559f3b0..0000000 Binary files a/test/golden/goldens/small_dark_colorful.png and /dev/null differ diff --git a/test/golden/goldens/small_dark_mono.png b/test/golden/goldens/small_dark_mono.png deleted file mode 100644 index 7268711..0000000 Binary files a/test/golden/goldens/small_dark_mono.png and /dev/null differ diff --git a/test/golden/goldens/small_dark_ocean.png b/test/golden/goldens/small_dark_ocean.png deleted file mode 100644 index 458dff9..0000000 Binary files a/test/golden/goldens/small_dark_ocean.png and /dev/null differ diff --git a/test/golden/goldens/small_dark_sunset.png b/test/golden/goldens/small_dark_sunset.png deleted file mode 100644 index b1ae6b1..0000000 Binary files a/test/golden/goldens/small_dark_sunset.png and /dev/null differ diff --git a/test/golden/goldens/small_light_colorful.png b/test/golden/goldens/small_light_colorful.png deleted file mode 100644 index e4ff42a..0000000 Binary files a/test/golden/goldens/small_light_colorful.png and /dev/null differ diff --git a/test/golden/goldens/small_light_mono.png b/test/golden/goldens/small_light_mono.png deleted file mode 100644 index d413d1f..0000000 Binary files a/test/golden/goldens/small_light_mono.png and /dev/null differ diff --git a/test/golden/goldens/small_light_ocean.png b/test/golden/goldens/small_light_ocean.png deleted file mode 100644 index f968948..0000000 Binary files a/test/golden/goldens/small_light_ocean.png and /dev/null differ diff --git a/test/golden/goldens/small_light_sunset.png b/test/golden/goldens/small_light_sunset.png deleted file mode 100644 index e9faefa..0000000 Binary files a/test/golden/goldens/small_light_sunset.png and /dev/null differ diff --git a/test/golden/goldens/surface_line_bottom.png b/test/golden/goldens/surface_line_bottom.png new file mode 100644 index 0000000..a303e18 Binary files /dev/null and b/test/golden/goldens/surface_line_bottom.png differ diff --git a/test/golden/goldens/surface_line_edge_left.png b/test/golden/goldens/surface_line_edge_left.png deleted file mode 100644 index 85a5cc0..0000000 Binary files a/test/golden/goldens/surface_line_edge_left.png and /dev/null differ diff --git a/test/golden/goldens/surface_line_edge_top.png b/test/golden/goldens/surface_line_edge_top.png deleted file mode 100644 index 038438f..0000000 Binary files a/test/golden/goldens/surface_line_edge_top.png and /dev/null differ diff --git a/test/golden/goldens/surface_line_left.png b/test/golden/goldens/surface_line_left.png new file mode 100644 index 0000000..81ff97d Binary files /dev/null and b/test/golden/goldens/surface_line_left.png differ diff --git a/test/golden/goldens/surface_line_right.png b/test/golden/goldens/surface_line_right.png new file mode 100644 index 0000000..9aa24f7 Binary files /dev/null and b/test/golden/goldens/surface_line_right.png differ diff --git a/test/golden/goldens/surface_line_top.png b/test/golden/goldens/surface_line_top.png new file mode 100644 index 0000000..44aaa7a Binary files /dev/null and b/test/golden/goldens/surface_line_top.png differ diff --git a/test/golden/goldens/surface_pulse_outside_glowspread2.png b/test/golden/goldens/surface_pulse_outside_glowspread2.png deleted file mode 100644 index 700b0bc..0000000 Binary files a/test/golden/goldens/surface_pulse_outside_glowspread2.png and /dev/null differ diff --git a/test/golden/goldens/surface_pulse_stadium_circle.png b/test/golden/goldens/surface_pulse_stadium_circle.png new file mode 100644 index 0000000..44d71f9 Binary files /dev/null and b/test/golden/goldens/surface_pulse_stadium_circle.png differ diff --git a/test/golden/goldens/surface_rotate_beamcount3.png b/test/golden/goldens/surface_rotate_beamcount3.png deleted file mode 100644 index 79ad658..0000000 Binary files a/test/golden/goldens/surface_rotate_beamcount3.png and /dev/null differ diff --git a/test/golden/goldens/surface_rotate_border_width_3.png b/test/golden/goldens/surface_rotate_border_width_3.png new file mode 100644 index 0000000..8f0cb08 Binary files /dev/null and b/test/golden/goldens/surface_rotate_border_width_3.png differ diff --git a/test/golden/goldens/surface_rotate_comet.png b/test/golden/goldens/surface_rotate_comet.png deleted file mode 100644 index 237813c..0000000 Binary files a/test/golden/goldens/surface_rotate_comet.png and /dev/null differ diff --git a/test/golden/goldens/surface_rotate_contour_star.png b/test/golden/goldens/surface_rotate_contour_star.png deleted file mode 100644 index a53fcf1..0000000 Binary files a/test/golden/goldens/surface_rotate_contour_star.png and /dev/null differ diff --git a/test/golden/goldens/surface_rotate_dashes_12.png b/test/golden/goldens/surface_rotate_dashes_12.png new file mode 100644 index 0000000..0074988 Binary files /dev/null and b/test/golden/goldens/surface_rotate_dashes_12.png differ diff --git a/test/golden/goldens/surface_rotate_glowspread2.png b/test/golden/goldens/surface_rotate_glowspread2.png deleted file mode 100644 index fa13810..0000000 Binary files a/test/golden/goldens/surface_rotate_glowspread2.png and /dev/null differ diff --git a/test/golden/goldens/surface_rotate_per_corner.png b/test/golden/goldens/surface_rotate_per_corner.png new file mode 100644 index 0000000..d4f6b85 Binary files /dev/null and b/test/golden/goldens/surface_rotate_per_corner.png differ diff --git a/test/golden/goldens/surface_rotate_ring_offset_8.png b/test/golden/goldens/surface_rotate_ring_offset_8.png new file mode 100644 index 0000000..b5bfea3 Binary files /dev/null and b/test/golden/goldens/surface_rotate_ring_offset_8.png differ diff --git a/test/golden/goldens/surface_rotate_ring_offset_neg_6.png b/test/golden/goldens/surface_rotate_ring_offset_neg_6.png new file mode 100644 index 0000000..0d01429 Binary files /dev/null and b/test/golden/goldens/surface_rotate_ring_offset_neg_6.png differ diff --git a/test/golden/goldens/surface_rotate_ringoffset8.png b/test/golden/goldens/surface_rotate_ringoffset8.png deleted file mode 100644 index ec95db6..0000000 Binary files a/test/golden/goldens/surface_rotate_ringoffset8.png and /dev/null differ diff --git a/test/golden/goldens/surface_rotate_segments8.png b/test/golden/goldens/surface_rotate_segments8.png deleted file mode 100644 index 262ed3b..0000000 Binary files a/test/golden/goldens/surface_rotate_segments8.png and /dev/null differ diff --git a/test/golden/goldens/surface_rotate_sparkle.png b/test/golden/goldens/surface_rotate_sparkle.png deleted file mode 100644 index b9cb6cc..0000000 Binary files a/test/golden/goldens/surface_rotate_sparkle.png and /dev/null differ diff --git a/test/golden/goldens/surface_rotate_squircle.png b/test/golden/goldens/surface_rotate_squircle.png new file mode 100644 index 0000000..f885f3b Binary files /dev/null and b/test/golden/goldens/surface_rotate_squircle.png differ diff --git a/test/golden/goldens/surface_rotate_stadium.png b/test/golden/goldens/surface_rotate_stadium.png new file mode 100644 index 0000000..de6aa7a Binary files /dev/null and b/test/golden/goldens/surface_rotate_stadium.png differ diff --git a/test/golden/goldens/surface_rotate_tail2.png b/test/golden/goldens/surface_rotate_tail2.png deleted file mode 100644 index 371cd70..0000000 Binary files a/test/golden/goldens/surface_rotate_tail2.png and /dev/null differ diff --git a/test/golden/goldens/surface_segment_pulse_top_half.png b/test/golden/goldens/surface_segment_pulse_top_half.png new file mode 100644 index 0000000..7809221 Binary files /dev/null and b/test/golden/goldens/surface_segment_pulse_top_half.png differ diff --git a/test/golden/goldens/surface_segment_rotate_bottom_half.png b/test/golden/goldens/surface_segment_rotate_bottom_half.png new file mode 100644 index 0000000..50214c1 Binary files /dev/null and b/test/golden/goldens/surface_segment_rotate_bottom_half.png differ diff --git a/test/golden/goldens/surface_segment_rotate_hard_cut.png b/test/golden/goldens/surface_segment_rotate_hard_cut.png new file mode 100644 index 0000000..63ab39c Binary files /dev/null and b/test/golden/goldens/surface_segment_rotate_hard_cut.png differ diff --git a/test/golden/goldens/widgets_decoration_pulse.png b/test/golden/goldens/widgets_decoration_pulse.png new file mode 100644 index 0000000..f873493 Binary files /dev/null and b/test/golden/goldens/widgets_decoration_pulse.png differ diff --git a/test/golden/goldens/widgets_decoration_rotate.png b/test/golden/goldens/widgets_decoration_rotate.png index 583837f..dcac17a 100644 Binary files a/test/golden/goldens/widgets_decoration_rotate.png and b/test/golden/goldens/widgets_decoration_rotate.png differ diff --git a/test/golden/goldens/widgets_focus_ring_active.png b/test/golden/goldens/widgets_focus_ring_active.png deleted file mode 100644 index 1e8bc77..0000000 Binary files a/test/golden/goldens/widgets_focus_ring_active.png and /dev/null differ diff --git a/test/golden/goldens/widgets_focus_ring_focused.png b/test/golden/goldens/widgets_focus_ring_focused.png new file mode 100644 index 0000000..81db11a Binary files /dev/null and b/test/golden/goldens/widgets_focus_ring_focused.png differ diff --git a/test/golden/goldens/widgets_hover_following.png b/test/golden/goldens/widgets_hover_following.png new file mode 100644 index 0000000..5fb0c05 Binary files /dev/null and b/test/golden/goldens/widgets_hover_following.png differ diff --git a/test/golden/goldens/widgets_press_held.png b/test/golden/goldens/widgets_press_held.png new file mode 100644 index 0000000..129cc8b Binary files /dev/null and b/test/golden/goldens/widgets_press_held.png differ diff --git a/test/golden/motion_golden_test.dart b/test/golden/motion_golden_test.dart index e5b88dc..47f6f24 100644 --- a/test/golden/motion_golden_test.dart +++ b/test/golden/motion_golden_test.dart @@ -1,111 +1,115 @@ @Tags(['golden']) library; -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -/// Golden scenes for the motion options — travel direction, several beams on -/// one contour, and a sweep driven from a value instead of the clock. -/// -/// They share the frozen-clock convention of `beam_golden_test.dart` (dark -/// theme, colorful palette, t = 1.3s) so each image can be read against the -/// plain `rotate_dark_colorful` / `line_dark_colorful` frame it varies. +import 'golden_scene.dart'; + +/// The motion family: travel direction, several beams on one border, the +/// rest between sweeps, phase offset, and a sweep driven from a value +/// instead of the clock. /// -/// Regenerate with: -/// flutter test --update-goldens --tags golden +/// Dark theme, colorful palette, t = 1.3s unless a scene says otherwise, so +/// each image reads against the plain `_dark_colorful` frame it +/// varies. void main() { - Widget scene({ - required Widget beam, - double width = 350, - double height = 140, - }) => MaterialApp( - debugShowCheckedModeBanner: false, - theme: ThemeData(brightness: Brightness.dark), - home: ColoredBox( - // The demo backdrop of the source library. - color: const Color(0xFF070707), - child: Center( - child: SizedBox(width: width, height: height, child: beam), - ), - ), - ); + setUpAll(BorderBeam.precache); - Widget mockSurface({double radius = 16}) => DecoratedBox( - decoration: BoxDecoration( - color: const Color(0xFF1D1D1D), - borderRadius: BorderRadius.circular(radius), - border: Border.all(color: const Color(0x14FFFFFF)), - ), - ); + Widget beam(BeamEffect effect, {BeamTiming? timing, double? progress}) => + goldenScene( + BorderBeam( + effect: effect, + borderRadius: 16, + style: const BeamStyle(theme: BeamTheme.dark), + timing: timing, + progress: progress, + child: mockSurface(Brightness.dark), + ), + ); - Future capture( - WidgetTester tester, - String name, - Widget beam, { - Duration freeze = const Duration(milliseconds: 1300), - }) async { - await tester.pumpWidget(scene(beam: beam)); - await tester.pump(); - await tester.pump(freeze); - await expectLater( - find.byType(MaterialApp), - matchesGoldenFile('goldens/$name.png'), - ); - } + const reverse = BeamTiming(direction: BeamDirection.reverse); - // The mirror of `rotate_dark_colorful`: same instant, same hue, the head - // the same distance round the border — the other way. + // The mirror of `rotate_dark_colorful`: same instant, the head the same + // distance round the border, the other way. testWidgets('rotate reverse', (tester) async { - await capture( + await captureGolden( tester, 'motion_rotate_reverse', - BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark), - timing: const BeamTiming(direction: BeamDirection.reverse), - child: mockSurface(), - ), + beam(const BeamEffect.rotate(), timing: reverse), + ); + }); + + testWidgets('line reverse', (tester) async { + await captureGolden( + tester, + 'motion_line_reverse', + beam(const BeamEffect.line(), timing: reverse), ); }); - // Two beams half a cycle apart: opposite sides of the border at every - // instant. - testWidgets('rotate with two beams', (tester) async { - await capture( + // Bounce runs its second cycle backwards: 0.4s into it. + testWidgets('rotate bounce, second cycle', (tester) async { + await captureGolden( tester, - 'motion_rotate_beamcount2', - BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark), - timing: const BeamTiming(beamCount: 2), - child: mockSurface(), + 'motion_rotate_bounce_second_cycle', + beam( + const BeamEffect.rotate(), + timing: const BeamTiming( + cycle: Duration(seconds: 1), + direction: BeamDirection.bounce, + ), ), + freeze: const Duration(milliseconds: 1400), ); }); - // A driven sweep: the beam sits at half its travel no matter how long the - // clock has run, which is what makes rotate readable as a progress ring. - testWidgets('rotate driven to half progress', (tester) async { - await capture( + for (final count in [2, 4]) { + testWidgets('rotate count $count', (tester) async { + await captureGolden( + tester, + 'motion_rotate_count_$count', + beam(BeamEffect.rotate(count: count)), + ); + }); + } + + testWidgets('rotate phase offset', (tester) async { + await captureGolden( tester, - 'motion_progress_0_5', - BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark), - progress: 0.5, - child: mockSurface(), + 'motion_rotate_phase_offset_half', + beam( + const BeamEffect.rotate(), + timing: const BeamTiming(phaseOffset: 0.5), ), ); }); - // The line beam travelling right-to-left, against `line_dark_colorful`. - testWidgets('line reverse', (tester) async { - await capture( + // A 1s sweep and a 1s rest, caught 0.1s into the rest: parked at the end + // of its travel and fading out. + testWidgets('rotate cycle gap', (tester) async { + await captureGolden( tester, - 'motion_line_reverse', - BorderBeam.line( - style: const BeamStyle(theme: BeamTheme.dark), - timing: const BeamTiming(direction: BeamDirection.reverse), - child: mockSurface(), + 'motion_rotate_cycle_gap_fading', + beam( + const BeamEffect.rotate(), + timing: const BeamTiming( + cycle: Duration(seconds: 1), + cycleGap: Duration(seconds: 1), + ), ), + freeze: const Duration(milliseconds: 1100), ); }); + + for (final effect in const [BeamEffect.rotate(), BeamEffect.line()]) { + testWidgets('${effect.name} progress 0.5', (tester) async { + await captureGolden( + tester, + 'motion_progress_${effect.name}_0_5', + beam(effect, progress: 0.5), + ); + }); + } } diff --git a/test/golden/palette_golden_test.dart b/test/golden/palette_golden_test.dart index 36516ae..ad37d2e 100644 --- a/test/golden/palette_golden_test.dart +++ b/test/golden/palette_golden_test.dart @@ -1,92 +1,79 @@ @Tags(['golden']) library; -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -/// One scene per palette the Flutter port adds on top of the React source's -/// four, plus the two derivation entry points ([BeamColors.fromSeed] and -/// [BeamColors.lerp]). -/// -/// Every scene uses the same frame the variant goldens do — rotate, dark -/// theme, clock frozen at 1.3s — so the only thing that varies between these -/// images is the palette, which is what they are here to pin. +import 'golden_scene.dart'; + +/// The palette family: every preset, and every way of building or +/// transforming colours, on one effect. /// -/// Regenerate with: -/// flutter test --update-goldens --tags golden +/// The pulse lights the whole border at once, and with the hue drift off +/// each image is the palette itself rather than a glimpse of it. Dark theme, +/// t = 1.3s. void main() { - Widget scene(Widget beam) => MaterialApp( - debugShowCheckedModeBanner: false, - theme: ThemeData(brightness: Brightness.dark), - home: ColoredBox( - // The demo backdrop of the source library. - color: const Color(0xFF070707), - child: Center(child: SizedBox(width: 350, height: 140, child: beam)), - ), - ); - - Widget mockSurface() => DecoratedBox( - decoration: BoxDecoration( - color: const Color(0xFF1D1D1D), - borderRadius: BorderRadius.circular(16), - border: Border.all(color: const Color(0x14FFFFFF)), - ), - ); + setUpAll(BorderBeam.precache); - Future capture( - WidgetTester tester, - String name, - BeamColors colors, - ) async { - await tester.pumpWidget( - scene( - BorderBeam.rotate( + Widget ring(BeamColors colors, {BeamStyle style = const BeamStyle()}) => + goldenScene( + BorderBeam( + effect: const BeamEffect.pulse(), colors: colors, - style: const BeamStyle(theme: BeamTheme.dark), - child: mockSurface(), + borderRadius: 16, + style: style.copyWith( + theme: BeamTheme.dark, + hueMode: BeamHueMode.none, + ), + child: mockSurface(Brightness.dark), ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1300)); - await expectLater( - find.byType(MaterialApp), - matchesGoldenFile('goldens/palette_$name.png'), - ); - } + ); - for (final MapEntry(key: name, value: colors) in const { - 'aurora': BeamColors.aurora, - 'neon': BeamColors.neon, - 'candy': BeamColors.candy, - 'ember': BeamColors.ember, - 'ice': BeamColors.ice, - 'gold': BeamColors.gold, - 'holographic': BeamColors.holographic, - }.entries) { - testWidgets('rotate dark $name', (tester) async { - await capture(tester, name, colors); + for (final MapEntry(key: name, value: colors) in BeamColors.presets.entries) { + testWidgets('preset $name', (tester) async { + await captureGolden(tester, 'palette_$name', ring(colors)); }); } - // The brand blue of the package's own demo, spread by the default - // (analogous) harmony. - testWidgets('rotate dark fromSeed', (tester) async { - await capture( - tester, - 'from_seed', - const BeamColors.fromSeed(Color(0xFF18A8F0)), - ); - }); + final built = { + 'custom': const BeamColors([ + Color(0xFFFF2D95), + Color(0xFF00E5FF), + Color(0xFFFFC400), + ]), + 'custom_stops': const BeamColors( + [Color(0xFFFF2D95), Color(0xFF00E5FF), Color(0xFFFFC400)], + stops: [0, 0.1, 0.5], + ), + 'solid': const BeamColors.solid(Color(0xFF7C4DFF)), + for (final harmony in BeamSeedHarmony.values) + 'seed_${harmony.name}': BeamColors.fromSeed( + const Color(0xFF18A8F0), + harmony: harmony, + ), + 'scheme': BeamColors.fromScheme( + ColorScheme.fromSeed(seedColor: const Color(0xFF00897B)), + ), + 'lerp_ocean_sunset': const BeamColors.lerp( + BeamColors.ocean, + BeamColors.sunset, + 0.5, + ), + 'scale_alpha_half': BeamColors.colorful.scaleAlpha(0.5), + }; + + for (final MapEntry(key: name, value: colors) in built.entries) { + testWidgets(name, (tester) async { + await captureGolden(tester, 'palette_$name', ring(colors)); + }); + } - // Halfway between two source presets: neither end's colors, both ends' - // geometry (they share it). - testWidgets('rotate dark lerp ocean to sunset', (tester) async { - await capture( + testWidgets('hue base', (tester) async { + await captureGolden( tester, - 'lerp_ocean_sunset', - const BeamColors.lerp(BeamColors.ocean, BeamColors.sunset, 0.5), + 'palette_colorful_hue_base_120', + ring(BeamColors.colorful, style: const BeamStyle(hueBase: 120)), ); }); } diff --git a/test/golden/research_golden_test.dart b/test/golden/research_golden_test.dart deleted file mode 100644 index 6e2a9f7..0000000 --- a/test/golden/research_golden_test.dart +++ /dev/null @@ -1,140 +0,0 @@ -@Tags(['golden']) -library; - -import 'package:flutter/material.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_test/flutter_test.dart'; - -/// Golden scenes for the options ported from the reference implementations: -/// the stock pulse-outside look, the pulse-inside wash scale, and the -/// render-scale magnification. -/// -/// They share the frozen-clock convention of `beam_golden_test.dart` -/// (colorful palette, t = 1.3s), so each image can be read against the plain -/// frame it varies — `pulse_outside_*_colorful` for the stock pair, -/// `pulse_inside_dark_colorful` for the wash scale, and the large default -/// captured here for the render scale. -/// -/// Regenerate with: -/// flutter test --update-goldens --tags golden -void main() { - Widget scene({ - required Widget beam, - required Brightness brightness, - double width = 350, - double height = 140, - }) { - final isDark = brightness == Brightness.dark; - return MaterialApp( - debugShowCheckedModeBanner: false, - theme: ThemeData(brightness: brightness), - home: ColoredBox( - // The demo backdrops of the source library. - color: isDark ? const Color(0xFF070707) : const Color(0xFFFDFDFD), - child: Center( - child: SizedBox(width: width, height: height, child: beam), - ), - ), - ); - } - - Widget mockSurface(Brightness brightness, {double radius = 16}) => - DecoratedBox( - decoration: BoxDecoration( - color: brightness == Brightness.dark - ? const Color(0xFF1D1D1D) - : const Color(0xFFFFFFFF), - borderRadius: BorderRadius.circular(radius), - border: Border.all( - color: brightness == Brightness.dark - ? const Color(0x14FFFFFF) - : const Color(0x14000000), - ), - ), - ); - - Future capture( - WidgetTester tester, - String name, - Widget beam, { - Brightness brightness = Brightness.dark, - double width = 350, - double height = 140, - }) async { - await tester.pumpWidget( - scene(beam: beam, brightness: brightness, width: width, height: height), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1300)); - await expectLater( - find.byType(MaterialApp), - matchesGoldenFile('goldens/$name.png'), - ); - } - - // The React library's own pulse-outside defaults: a tighter, dimmer halo - // than the demo recipe every other pulse-outside golden captures. - for (final brightness in Brightness.values) { - final theme = brightness == Brightness.dark ? 'dark' : 'light'; - testWidgets('pulse-outside stock $theme', (tester) async { - await capture( - tester, - 'research_pulse_outside_stock_$theme', - BorderBeam.pulseOutside( - style: BeamStyle.pulseOutsideStock.copyWith( - theme: brightness == Brightness.dark - ? BeamTheme.dark - : BeamTheme.light, - ), - child: mockSurface(brightness), - ), - brightness: brightness, - ); - }); - } - - // The inward wash at 0.6: the same border, less flood. - testWidgets('pulse-inside inner scale 0.6', (tester) async { - await capture( - tester, - 'research_pulse_inside_inner_scale_0_6', - BorderBeam.pulseInside( - style: const BeamStyle(theme: BeamTheme.dark, innerSizeScale: 0.6), - child: mockSurface(Brightness.dark), - ), - ); - }); - - // The render-scale pair, on a box twice the width the palettes were drawn - // for: the default frame is the reference, the scaled one is the same beam - // painted at half size and magnified back. - testWidgets('rotate on a large box', (tester) async { - await capture( - tester, - 'research_rotate_large_default', - BorderBeam.rotate( - borderRadius: 24, - style: const BeamStyle(theme: BeamTheme.dark), - child: mockSurface(Brightness.dark, radius: 24), - ), - width: 700, - height: 280, - ); - }); - - testWidgets('rotate on a large box at render scale 0.5', (tester) async { - await capture( - tester, - 'research_rotate_render_scale_0_5', - BorderBeam.rotate( - // The radius is a box-relative length: scaledBy halves it for the - // small canvas, so it still lands on the child's 24 once magnified. - borderRadius: 24, - style: const BeamStyle(theme: BeamTheme.dark, renderScale: 0.5), - child: mockSurface(Brightness.dark, radius: 24), - ), - width: 700, - height: 280, - ); - }); -} diff --git a/test/golden/segment_golden_test.dart b/test/golden/segment_golden_test.dart deleted file mode 100644 index 277f527..0000000 --- a/test/golden/segment_golden_test.dart +++ /dev/null @@ -1,182 +0,0 @@ -@Tags(['golden']) -library; - -import 'package:flutter/material.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_test/flutter_test.dart'; - -/// Golden scenes for partial-perimeter beams and corner-wrapped line travel. -/// -/// Regenerate on the pinned macOS Flutter SDK with: -/// flutter test --update-goldens --tags golden -void main() { - Widget surface() => DecoratedBox( - decoration: BoxDecoration( - color: const Color(0xFF1D1D1D), - borderRadius: BorderRadius.circular(24), - border: Border.all(color: const Color(0x14FFFFFF)), - ), - ); - - Widget scene(Widget beam) => MaterialApp( - debugShowCheckedModeBanner: false, - theme: ThemeData(brightness: Brightness.dark), - home: ColoredBox( - color: const Color(0xFF070707), - child: Center(child: SizedBox.square(dimension: 200, child: beam)), - ), - ); - - Future capture( - WidgetTester tester, - String name, - Widget beam, { - Duration freeze = const Duration(milliseconds: 1300), - }) async { - await tester.pumpWidget(scene(beam)); - await tester.pump(); - await tester.pump(freeze); - await expectLater( - find.byType(MaterialApp), - matchesGoldenFile('goldens/$name.png'), - ); - } - - const style = BeamStyle(theme: BeamTheme.dark); - BeamShape shape(BeamSegment segment) => BeamShape( - radius: const BorderRadius.all(Radius.circular(24)), - segment: segment, - ); - - testWidgets('rotate bottom half', (tester) async { - await capture( - tester, - 'segment_rotate_bottom_half', - BorderBeam.rotate( - style: style, - shape: shape(BeamSegment.bottomHalf), - child: surface(), - ), - ); - }); - - testWidgets('rotate bottom half late', (tester) async { - await capture( - tester, - 'segment_rotate_bottom_half_late', - BorderBeam.rotate( - style: style, - shape: shape(BeamSegment.bottomHalf), - child: surface(), - ), - freeze: const Duration(milliseconds: 2300), - ); - }); - - testWidgets('small bottom half', (tester) async { - await capture( - tester, - 'segment_small_bottom_half', - BorderBeam.small( - style: style, - shape: shape(BeamSegment.bottomHalf), - child: surface(), - ), - ); - }); - - testWidgets('line bottom half', (tester) async { - await capture( - tester, - 'segment_line_bottom_half', - BorderBeam.line( - style: style, - shape: shape(BeamSegment.bottomHalf), - child: surface(), - ), - ); - }); - - testWidgets('line bottom half late', (tester) async { - await capture( - tester, - 'segment_line_bottom_half_late', - BorderBeam.line( - style: style, - shape: shape(BeamSegment.bottomHalf), - child: surface(), - ), - freeze: const Duration(milliseconds: 2000), - ); - }); - - testWidgets('line wraps bottom corners', (tester) async { - await capture( - tester, - 'segment_line_wrap_corners', - BorderBeam.line( - style: style, - shape: const BeamShape( - radius: BorderRadius.all(Radius.circular(24)), - edge: BeamEdge.bottom, - wrapCorners: true, - ), - child: surface(), - ), - ); - }); - - testWidgets('pulse inside bottom half', (tester) async { - await capture( - tester, - 'segment_pulse_inside_bottom_half', - BorderBeam.pulseInside( - style: style, - shape: shape(BeamSegment.bottomHalf), - child: surface(), - ), - ); - }); - - testWidgets('pulse outside bottom half', (tester) async { - await capture( - tester, - 'segment_pulse_outside_bottom_half', - BorderBeam.pulseOutside( - style: style, - shape: shape(BeamSegment.bottomHalf), - child: surface(), - ), - ); - }); - - testWidgets('rotate top edge', (tester) async { - await capture( - tester, - 'segment_rotate_top_edge', - BorderBeam.rotate( - style: style, - shape: shape(BeamSegment.topEdge), - child: surface(), - ), - ); - }); - - testWidgets('rotate hard segment edge', (tester) async { - await capture( - tester, - 'segment_rotate_feather_0', - BorderBeam.rotate( - style: style, - shape: shape( - const BeamSegment( - start: BeamAnchor.rightCenter, - end: BeamAnchor.leftCenter, - feather: 0, - ), - ), - child: surface(), - ), - ); - }); -} diff --git a/test/golden/surface_golden_test.dart b/test/golden/surface_golden_test.dart index 167fdc4..ce3e737 100644 --- a/test/golden/surface_golden_test.dart +++ b/test/golden/surface_golden_test.dart @@ -1,212 +1,157 @@ @Tags(['golden']) library; -import 'dart:math' as math; - -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -/// Golden scenes for the surface options — the shape, travel, and glow -/// controls that change what a beam looks like without changing which variant -/// it is. -/// -/// Same recipe as the variant goldens: the fake clock is frozen 1.3s after -/// activation, past the fade-in and mid-cycle. Every scene is the dark theme -/// with the colorful palette unless its name says otherwise, so the option -/// under test is the only thing that moves between images. +import 'golden_scene.dart'; + +/// The surface family — the shape options: superellipse corners, per-corner +/// radii, stadium, ring offset, segments, dashes, stroke width, and the line +/// on each edge. /// -/// Regenerate with: -/// flutter test --update-goldens --tags golden +/// Dark theme, colorful palette, t = 1.3s, so each image reads against the +/// plain `_dark_colorful` frame it varies. void main() { - Widget scene({ - required Widget beam, - double width = 350, - double height = 140, - }) => MaterialApp( - debugShowCheckedModeBanner: false, - theme: ThemeData(brightness: Brightness.dark), - home: ColoredBox( - // The demo backdrop of the source library. - color: const Color(0xFF070707), - child: Center( - child: SizedBox(width: width, height: height, child: beam), - ), + setUpAll(BorderBeam.precache); + + Widget beam( + BeamEffect effect, + BeamShape shape, { + Widget? surface, + Size size = goldenCard, + double? progress, + }) => goldenScene( + BorderBeam( + effect: effect, + shape: shape, + progress: progress, + style: const BeamStyle(theme: BeamTheme.dark), + child: surface ?? mockSurface(Brightness.dark), ), + size: size, ); - Widget mockSurface({double radius = 16}) => DecoratedBox( - decoration: BoxDecoration( - color: const Color(0xFF1D1D1D), - borderRadius: BorderRadius.circular(radius), - border: Border.all(color: const Color(0x14FFFFFF)), - ), - ); - - Future capture( - WidgetTester tester, - String name, - Widget beam, { - double width = 350, - double height = 140, - }) async { - await tester.pumpWidget(scene(beam: beam, width: width, height: height)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1300)); - await expectLater( - find.byType(MaterialApp), - matchesGoldenFile('goldens/$name.png'), - ); - } - - testWidgets('line on the top edge', (tester) async { - await capture( + testWidgets('superellipse', (tester) async { + await captureGolden( tester, - 'surface_line_edge_top', - BorderBeam.line( - style: const BeamStyle(theme: BeamTheme.dark), - shape: const BeamShape(edge: BeamEdge.top), - child: mockSurface(), + 'surface_rotate_squircle', + beam( + const BeamEffect.rotate(), + const BeamShape.all(28, superellipse: true), + surface: mockSurface(Brightness.dark, radius: 28, superellipse: true), ), ); }); - testWidgets('line on the left edge', (tester) async { - await capture( - tester, - 'surface_line_edge_left', - BorderBeam.line( - style: const BeamStyle(theme: BeamTheme.dark), - shape: const BeamShape(edge: BeamEdge.left), - child: mockSurface(), - ), + testWidgets('per-corner radii', (tester) async { + const radii = BorderRadius.only( + topLeft: Radius.circular(40), + bottomRight: Radius.circular(8), ); - }); - - testWidgets('rotate with three beams', (tester) async { - await capture( - tester, - 'surface_rotate_beamcount3', - BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark), - timing: const BeamTiming(beamCount: 3), - child: mockSurface(), - ), - ); - }); - - testWidgets('rotate with a double-length tail', (tester) async { - await capture( + await captureGolden( tester, - 'surface_rotate_tail2', - BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark, tailLength: 2), - child: mockSurface(), + 'surface_rotate_per_corner', + beam( + const BeamEffect.rotate(), + const BeamShape(radius: radii), + surface: mockSurface(Brightness.dark, radii: radii), ), ); }); - testWidgets('rotate with a comet halo', (tester) async { - await capture( + testWidgets('stadium pill', (tester) async { + await captureGolden( tester, - 'surface_rotate_comet', - BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark, comet: true), - child: mockSurface(), + 'surface_rotate_stadium', + beam( + const BeamEffect.rotate(), + const BeamShape.stadium(), + surface: mockSurface(Brightness.dark, radius: 32), + size: const Size(350, 64), ), ); }); - testWidgets('rotate with sparkles', (tester) async { - await capture( + testWidgets('stadium circle', (tester) async { + await captureGolden( tester, - 'surface_rotate_sparkle', - BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark, sparkle: 1), - child: mockSurface(), + 'surface_pulse_stadium_circle', + beam( + const BeamEffect.pulse(), + const BeamShape.stadium(), + surface: mockSurface(Brightness.dark, radius: 60), + size: const Size(120, 120), ), ); }); - testWidgets('rotate on a dashed ring', (tester) async { - await capture( - tester, - 'surface_rotate_segments8', - BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark, segments: 8), - child: mockSurface(), - ), - ); - }); - - testWidgets('rotate with a wider glow', (tester) async { - await capture( - tester, - 'surface_rotate_glowspread2', - BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark, glowSpread: 2), - child: mockSurface(), - ), - ); + group('ring offset', () { + for (final (label, offset) in [('8', 8.0), ('neg_6', -6.0)]) { + testWidgets(label, (tester) async { + await captureGolden( + tester, + 'surface_rotate_ring_offset_$label', + beam( + const BeamEffect.rotate(), + BeamShape.all(16 + offset, ringOffset: offset), + ), + ); + }); + } }); - testWidgets('rotate with the ring pushed out', (tester) async { - await capture( - tester, - 'surface_rotate_ringoffset8', - BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark), - shape: const BeamShape( - ringOffset: 8, - radius: BorderRadius.all(Radius.circular(16)), + group('segments', () { + final scenes = { + 'rotate_bottom_half': (const BeamEffect.rotate(), BeamSegment.bottomHalf), + 'pulse_top_half': (const BeamEffect.pulse(), BeamSegment.topHalf), + 'rotate_hard_cut': ( + const BeamEffect.rotate(), + const BeamSegment( + start: BeamAnchor.fraction(0.1), + end: BeamAnchor.fraction(0.9), + feather: 0, ), - child: mockSurface(), ), - ); + }; + for (final MapEntry(key: name, value: (effect, segment)) + in scenes.entries) { + testWidgets(name, (tester) async { + await captureGolden( + tester, + 'surface_segment_$name', + beam(effect, BeamShape(segment: segment)), + ); + }); + } }); - // A square box, so the inscribed star is as large as it can be, and no - // surface behind it: the contour is the only thing the beam draws. - testWidgets('rotate around a star contour', (tester) async { - await capture( + testWidgets('dashes', (tester) async { + await captureGolden( tester, - 'surface_rotate_contour_star', - BorderBeam.rotate( - style: const BeamStyle(theme: BeamTheme.dark, tailLength: 2), - shape: BeamShape(contour: _star), - child: const SizedBox.expand(), - ), - width: 260, - height: 260, + 'surface_rotate_dashes_12', + beam(const BeamEffect.rotate(), const BeamShape(dashes: 12)), ); }); - testWidgets('pulse-outside with a wider halo', (tester) async { - await capture( + testWidgets('border width', (tester) async { + await captureGolden( tester, - 'surface_pulse_outside_glowspread2', - BorderBeam.pulseOutside( - style: const BeamStyle(theme: BeamTheme.dark, glowSpread: 2), - child: mockSurface(), - ), + 'surface_rotate_border_width_3', + beam(const BeamEffect.rotate(), const BeamShape(borderWidth: 3)), ); }); -} -/// A five-pointed star inscribed in the beam's bounds. -final _star = BeamPathContour((rect) { - final path = Path(); - final centre = rect.center; - final outer = rect.shortestSide / 2; - for (var i = 0; i < 10; i++) { - final r = i.isEven ? outer : outer * 0.5; - final a = -math.pi / 2 + i * math.pi / 5; - final p = centre + Offset(math.cos(a) * r, math.sin(a) * r); - if (i == 0) { - path.moveTo(p.dx, p.dy); - } else { - path.lineTo(p.dx, p.dy); + group('line edge', () { + for (final edge in BeamEdge.values) { + testWidgets(edge.name, (tester) async { + await captureGolden( + tester, + 'surface_line_${edge.name}', + beam(BeamEffect.line(edge: edge), const BeamShape()), + ); + }); } - } - return path..close(); -}, key: 'golden-star'); + }); +} diff --git a/test/golden/widgets_golden_test.dart b/test/golden/widgets_golden_test.dart index 3534068..070d0f3 100644 --- a/test/golden/widgets_golden_test.dart +++ b/test/golden/widgets_golden_test.dart @@ -1,97 +1,151 @@ @Tags(['golden']) library; -import 'package:flutter/material.dart'; +import 'package:flutter/gestures.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -/// Golden scenes for the surface and interaction wrappers, frozen at the same -/// 1.3s instant the variant goldens use (past the 0.6s fade-in, mid-cycle). -/// They pin what the wrappers *compose* — the decoration form painting the -/// same beam a widget does, and the focus ring lit — not the beam frames -/// themselves, which `beam_golden_test.dart` owns. +import 'golden_scene.dart'; + +/// The widgets family: what the decoration form and the three interaction +/// wrappers compose — the decoration painting the same beam a widget does, +/// the focus ring lit, the hover beam pulled toward the cursor, the press +/// beam held down. The beam frames themselves belong to +/// `beam_golden_test.dart`. /// -/// Regenerate with: -/// flutter test --update-goldens --tags golden +/// Dark theme, t = 1.3s after the interaction starts. void main() { - const surfaceRadius = 16.0; - - Widget scene(Widget body) => MaterialApp( - debugShowCheckedModeBanner: false, - theme: ThemeData(brightness: Brightness.dark), - home: ColoredBox( - // The demo backdrop of the source library. - color: const Color(0xFF070707), - child: Center(child: body), - ), - ); + setUpAll(BorderBeam.precache); - BoxDecoration surface({double radius = surfaceRadius}) => BoxDecoration( + BoxDecoration surface({double radius = 16}) => BoxDecoration( color: const Color(0xFF1D1D1D), borderRadius: BorderRadius.circular(radius), border: Border.all(color: const Color(0x14FFFFFF)), ); testWidgets('decoration rotate', (tester) async { - await tester.pumpWidget( - scene( + await captureGolden( + tester, + 'widgets_decoration_rotate', + goldenScene( Container( - width: 350, - height: 140, decoration: surface(), - // rotate paints over its child, so the beam takes the foreground - // slot and the surface takes the background one. + // The beam paints over its child, so it takes the foreground slot + // and the surface the background one. foregroundDecoration: const BeamDecoration( - variant: BeamVariant.rotate, brightness: Brightness.dark, + effect: BeamEffect.rotate(), style: BeamStyle(theme: BeamTheme.dark), - borderRadius: surfaceRadius, + borderRadius: 16, ), ), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1300)); + }); - await expectLater( - find.byType(MaterialApp), - matchesGoldenFile('goldens/widgets_decoration_rotate.png'), + testWidgets('decoration pulse', (tester) async { + await captureGolden( + tester, + 'widgets_decoration_pulse', + goldenScene( + Container( + decoration: surface(), + foregroundDecoration: const BeamDecoration( + brightness: Brightness.dark, + effect: BeamEffect.pulse(), + colors: BeamColors.ocean, + borderRadius: 16, + ), + ), + ), ); }); - testWidgets('focus ring active', (tester) async { + testWidgets('focus ring focused', (tester) async { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; - addTearDown(() { - FocusManager.instance.highlightStrategy = - FocusHighlightStrategy.automatic; - }); + addTearDown( + () => FocusManager.instance.highlightStrategy = + FocusHighlightStrategy.automatic, + ); final node = FocusNode(); addTearDown(node.dispose); - - await tester.pumpWidget( - scene( + await captureGolden( + tester, + 'widgets_focus_ring_focused', + goldenScene( BeamFocusRing( - borderRadius: 32, + borderRadius: 28, style: const BeamStyle(theme: BeamTheme.dark), child: Focus( focusNode: node, - child: Container( - width: 220, - height: 56, - decoration: surface(radius: 32), - ), + child: Container(decoration: surface(radius: 28)), ), ), + size: const Size(220, 56), ), + beforeFreeze: () async { + node.requestFocus(); + await tester.pump(); + }, ); - node.requestFocus(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1300)); + }); - await expectLater( - find.byType(MaterialApp), - matchesGoldenFile('goldens/widgets_focus_ring_active.png'), + testWidgets('hover follows the cursor', (tester) async { + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer(location: Offset.zero); + await captureGolden( + tester, + 'widgets_hover_following', + goldenScene( + BeamHover( + borderRadius: 16, + style: const BeamStyle(theme: BeamTheme.dark), + child: Container(decoration: surface()), + ), + ), + beforeFreeze: () async { + // Into the card near its top-right corner: the beam eases there. + final card = tester.getRect(find.byType(BeamHover)); + await mouse.moveTo(card.topRight + const Offset(-40, 20)); + await tester.pump(); + }, + frameByFrame: true, + ); + // Leave, and let the hold and the fade-out run down. One long pump only + // starts the fade on its single frame: wait out the hold, then play the + // fade frame by frame. + await mouse.removePointer(); + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('press held down', (tester) async { + late TestGesture finger; + await captureGolden( + tester, + 'widgets_press_held', + goldenScene( + BeamPress( + borderRadius: 16, + style: const BeamStyle(theme: BeamTheme.dark), + child: Container(decoration: surface()), + ), + ), + beforeFreeze: () async { + finger = await tester.startGesture( + tester.getCenter(find.byType(BeamPress)), + ); + await tester.pump(); + }, ); + await finger.up(); + // Let the minimum-duration timer and the release's fade-out run down, + // the fade frame by frame. + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + expect(tester.binding.transientCallbackCount, 0); }); } diff --git a/test/models/beam_colors_test.dart b/test/models/beam_colors_test.dart index a9400a3..4439066 100644 --- a/test/models/beam_colors_test.dart +++ b/test/models/beam_colors_test.dart @@ -1,711 +1,515 @@ -import 'package:flutter/material.dart'; +import 'dart:ui'; + import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam/src/constants/palettes.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; +import 'package:flutter_border_beam/src/models/beam_palette.dart'; +import 'package:flutter_border_beam/src/models/model_validation.dart'; +import 'package:flutter_border_beam/src/render/color_math.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart' show ColorScheme, HSLColor; + +const Color _red = Color(0xFFFF0000); +const Color _green = Color(0xFF00FF00); +const Color _blue = Color(0xFF0000FF); + +/// Asserts [p] is a well-formed palette: 1–8 colours, one stop each, +/// ascending inside `[0, 1)`. +void _expectWellFormed(BeamPalette p, {String? reason}) { + expect(p.colors.length, inInclusiveRange(1, maxPaletteStops), reason: reason); + expect(p.stops, hasLength(p.colors.length), reason: reason); + for (var i = 0; i < p.stops.length; i++) { + expect(p.stops[i], inInclusiveRange(0, 1), reason: reason); + expect(p.stops[i], lessThan(1), reason: reason); + if (i > 0) { + expect(p.stops[i], greaterThanOrEqualTo(p.stops[i - 1]), reason: reason); + } + } + expect( + () => validatePalette(p.colors, p.stops, 'test'), + returnsNormally, + reason: reason, + ); +} -const _blobA = BeamBlob( - color: Color(0xFFFF3264), - position: Offset(0.33, -0.074), - size: Size(70, 40), -); -const _blobB = BeamBlob( - color: Color(0xFF288CFF), - position: Offset(0.12, -0.05), - size: Size(60, 35), -); -const _pink = Color(0xFFFF0080); -const _cyan = Color(0xFF00E5FF); -const _brand = Color(0xFF18A8F0); - -const _lineBlob = LineBlob( - color: Color(0xFFFF3264), - sizeW: 120, - sizeH: 30, - offsetX: 0, - offsetY: 2, -); - -Widget _host(Widget child) => MaterialApp( - theme: ThemeData(brightness: Brightness.dark), - home: Scaffold( - body: Center(child: SizedBox(width: 350, height: 140, child: child)), - ), -); - -BeamPainter _beamPainter(WidgetTester tester) => tester - .widgetList( - find.descendant( - of: find.byType(BorderBeam), - matching: find.byType(CustomPaint), - ), - ) - .expand((paint) => [paint.painter, paint.foregroundPainter]) - .whereType() - .first; +/// [x] as a runtime value, so an expression built from it is never const. +double _rt(double x) => double.parse('$x'); -void main() { - group('BeamBlob equality', () { - test('compares color, position and size', () { - expect( - _blobA, - const BeamBlob( - color: Color(0xFFFF3264), - position: Offset(0.33, -0.074), - size: Size(70, 40), - ), - ); - expect( - _blobA.hashCode, - _blobA.withColor(const Color(0xFFFF3264)).hashCode, - ); - expect(_blobA, isNot(_blobB)); - expect(_blobA, isNot(_blobA.withColor(const Color(0xFF000000)))); - expect(_blobA.toString(), contains('BeamBlob')); - }); +/// Hue distance in degrees, around the wheel. +double _hueDistance(double a, double b) { + final d = (a - b).abs() % 360; + return d > 180 ? 360 - d : d; +} - test('LineBlob compares every geometry field', () { +/// `BeamColors` is the public colour choice: a value type that resolves to a +/// [BeamPalette] — a ring of colour stops — through a value-keyed memo. +void main() { + group('presets', () { + test('the map holds 19 distinct presets keyed by their names', () { + expect(BeamColors.presets, hasLength(19)); + expect(BeamColors.presets.values.toSet(), hasLength(19)); + for (final MapEntry(:key, :value) in BeamColors.presets.entries) { + expect(value.toString(), 'BeamColors.$key'); + } expect( - _lineBlob, - const LineBlob( - color: Color(0xFFFF3264), - sizeW: 120, - sizeH: 30, - offsetX: 0, - offsetY: 2, - ), - ); - expect(_lineBlob.hashCode, isNot(0)); - expect( - _lineBlob, - isNot( - const LineBlob( - color: Color(0xFFFF3264), - sizeW: 120, - sizeH: 30, - offsetX: 1, - offsetY: 2, - ), - ), + BeamColors.presets.values.map((c) => c.resolve()).toSet(), + hasLength(19), + reason: 'no two presets resolve to the same palette', ); - expect(_lineBlob.toString(), contains('LineBlob')); }); - }); - group('BeamColors equality', () { - test('equal custom lists are == with equal hashCodes', () { - final a = BeamColors.custom(const [Color(0xFFFF00AA), Color(0xFF00FFEE)]); - final b = BeamColors.custom([ - const Color(0xFFFF00AA), - const Color(0xFF00FFEE), + test('the map opens with the four originals', () { + expect(BeamColors.presets.keys.take(4), [ + 'colorful', + 'mono', + 'ocean', + 'sunset', ]); - expect(identical(a, b), isFalse, reason: 'distinct instances'); - expect(a, b); - expect(a.hashCode, b.hashCode); + expect(BeamColors.presets['colorful'], BeamColors.colorful); + expect(BeamColors.presets['ocean'], BeamColors.ocean); }); - test('custom order and length are significant', () { - final a = BeamColors.custom(const [Color(0xFFFF00AA), Color(0xFF00FFEE)]); - final reordered = BeamColors.custom(const [ - Color(0xFF00FFEE), - Color(0xFFFF00AA), - ]); - final shorter = BeamColors.custom(const [Color(0xFFFF00AA)]); - expect(a, isNot(reordered)); - expect(a, isNot(shorter)); - }); + for (final MapEntry(:key, :value) in BeamColors.presets.entries) { + test('$key resolves to a well-formed palette', () { + final palette = value.resolve(); + _expectWellFormed(palette, reason: key); + expect( + identical(value.resolve(), palette), + isTrue, + reason: 'a preset resolves to one canonical palette', + ); + }); + } - test('presets compare by identity of their table and mono flag', () { - expect(BeamColors.ocean, BeamColors.ocean); - expect(BeamColors.ocean.hashCode, BeamColors.ocean.hashCode); - expect(BeamColors.ocean, isNot(BeamColors.sunset)); - expect(BeamColors.mono, isNot(BeamColors.colorful)); - expect( - BeamColors.colorful, - isNot(BeamColors.custom(const [Color(0xFFFF00AA)])), - ); + test('only mono and gold fix the hue', () { + for (final MapEntry(:key, :value) in BeamColors.presets.entries) { + expect( + value.resolve().fixedHue, + key == 'mono' || key == 'gold', + reason: key, + ); + } }); - test('spec compares blob tables element-wise', () { - const a = BeamColors.spec(border: [_blobA, _blobB]); - const b = BeamColors.spec(border: [_blobA, _blobB]); - expect(a, b); - expect(a.hashCode, b.hashCode); - expect(a, isNot(const BeamColors.spec(border: [_blobB, _blobA]))); - expect( - a, - isNot(const BeamColors.spec(border: [_blobA, _blobB], lineBlobs: [])), - ); - expect( - const BeamColors.spec(border: [_blobA], smallBorder: [_blobB]), - const BeamColors.spec(border: [_blobA], smallBorder: [_blobB]), - ); - expect( - const BeamColors.spec(border: [_blobA], smallBorder: [_blobB]), - isNot(const BeamColors.spec(border: [_blobA])), - ); - expect( - const BeamColors.spec(border: [_blobA], lineBlobs: [_lineBlob]), - const BeamColors.spec(border: [_blobA], lineBlobs: [_lineBlob]), - ); + test('presets compare by name', () { + expect(BeamColors.ocean, BeamColors.presets['ocean']); + expect(BeamColors.ocean.hashCode, BeamColors.presets['ocean'].hashCode); + expect(BeamColors.ocean, isNot(BeamColors.sunset)); }); }); - group('BeamColors.resolve', () { - test('memoizes per instance', () { - final custom = BeamColors.custom(const [Color(0xFFFF00AA)]); - expect(identical(custom.resolve(), custom.resolve()), isTrue); - expect( - identical(BeamColors.ocean.resolve(), BeamColors.ocean.resolve()), - isTrue, - ); - const spec = BeamColors.spec(border: [_blobA]); - expect(identical(spec.resolve(), spec.resolve()), isTrue); + group('BeamColors(colors, stops)', () { + test('spaces the colours evenly by default', () { + final p = const BeamColors([_red, _green, _blue, _red]).resolve(); + expect(p.colors, [_red, _green, _blue, _red]); + expect(p.stops, BeamPalette.evenStops(4)); + expect(p.fixedHue, isFalse); }); - test('mutable custom inputs cannot corrupt the value cache', () { - final colors = [const Color(0xFFFF0000)]; - final custom = BeamColors.custom(colors); - final red = custom.resolve(); - - colors[0] = const Color(0xFF0000FF); - final blue = custom.resolve(); - - expect(identical(blue, red), isFalse); - expect(blue.data.border.first.color, const Color(0xFF0000FF)); - expect( - identical(blue, BeamColors.custom(const [Color(0xFF0000FF)]).resolve()), - isTrue, - reason: 'the mutated value should use a new stable cache key', - ); + test('honours explicit stops and alpha', () { + const translucent = Color(0x8000FF00); + final p = const BeamColors( + [_red, translucent], + stops: [0.2, 0.9], + ).resolve(); + expect(p.colors, [_red, translucent]); + expect(p.stops, [0.2, 0.9]); }); - test('mutable spec inputs cannot corrupt the value cache', () { - final border = [_blobA]; - final spec = BeamColors.spec(border: border); - final first = spec.resolve(); - - border[0] = _blobB; - final second = spec.resolve(); + test('equal neighbouring stops are allowed — a hard edge', () { + final p = const BeamColors( + [_red, _blue, _green], + stops: [0, 0.5, 0.5], + ).resolve(); + _expectWellFormed(p); + }); - expect(identical(second, first), isFalse); - expect(second.data.border, [_blobB]); - expect( - identical(second, const BeamColors.spec(border: [_blobB]).resolve()), - isTrue, - ); + test('a single colour is valid', () { + final p = const BeamColors([_blue]).resolve(); + expect(p.colors, [_blue]); + expect(p.stops, [0]); }); - test('an empty color table is rejected in release too', () { + test('equality covers colours, order and stops', () { expect( - () => BeamColors.custom([]).resolve(), - throwsA(isA()), + BeamColors([_red, Color(int.parse('0xFF00FF00'))]), + const BeamColors([_red, _green]), ); expect( - () => BeamColors.spec(border: []).resolve(), - throwsA(isA()), + BeamColors([_red, Color(int.parse('0xFF00FF00'))]).hashCode, + const BeamColors([_red, _green]).hashCode, ); - }); - - test('a resolved spec palette does not alias the caller lists', () { - final border = [_blobA]; - final small = [_blobA]; - final lines = [_lineBlob]; - final palette = BeamColors.spec( - border: border, - smallBorder: small, - lineBlobs: lines, - ).resolve(); - - border[0] = _blobB; - small[0] = _blobB; - lines.clear(); - - expect(palette.data.border, [_blobA]); - expect(palette.data.smallBorder, [_blobA]); - expect(palette.data.lineDark, [_lineBlob]); - expect(palette.data.lineLight, [_lineBlob]); expect( - () => palette.data.border.add(_blobB), - throwsUnsupportedError, - reason: 'the resolved tables are snapshots, not the caller list', + const BeamColors([_red, _green]), + isNot(const BeamColors([_green, _red])), ); - }); - - test('custom distributes colors and preserves preset alpha', () { - final palette = BeamColors.custom(const [Color(0xFFFF00AA)]).resolve(); - final reference = BeamColors.colorful.resolve(); - for (final (i, blob) in palette.data.smallInner.indexed) { - expect(blob.color.r, closeTo(1, 1e-6)); - expect(blob.color.g, closeTo(0, 1e-6)); - expect( - blob.color.a, - closeTo(reference.data.smallInner[i].color.a, 1e-6), - ); - expect(blob.position, reference.data.smallInner[i].position); - } - expect(palette.data.border.length, reference.data.border.length); - expect(palette.data.lineBloomDark.length, 5); - expect(palette.forcesStaticColors, isFalse); - }); - - test('mono preset carries the mono modifiers', () { - final mono = BeamColors.mono.resolve(); - expect(mono.forcesStaticColors, isTrue); - expect(mono.opacityMultiplier, 0.5); - expect(mono.monoTreatment, isTrue); - }); - - test('spec keeps the given tables and derives the rest', () { - const spec = BeamColors.spec( - border: [_blobA, _blobB], - smallBorder: [_blobA], + expect( + const BeamColors([_red, _green]), + isNot(const BeamColors([_red, _green], stops: [0, 0.5])), + reason: 'explicit stops are a different value, even when equal', ); - final palette = spec.resolve(); - final derived = BeamColors.custom(const [ - Color(0xFFFF3264), - Color(0xFF288CFF), - ]).resolve(); - expect(palette.data.border, const [_blobA, _blobB]); - expect(palette.data.smallBorder, const [_blobA]); - // smallInner is derived from the given smallBorder at 45% alpha. expect( - palette.data.smallInner.single.color.a, - closeTo(_blobA.color.a * 0.45, 1e-6), + const BeamColors([_red, _green], stops: [0, 0.3]), + isNot(const BeamColors([_red, _green], stops: [0, 0.4])), ); - // Untouched tables cycle the border colors over the default geometry. - expect(palette.data.lineInner, derived.data.lineInner); - expect(palette.data.lineBloomDark, derived.data.lineBloomDark); - expect(palette.data.spike, derived.data.spike); - }); - - test('spec without a smallBorder derives one', () { - const spec = BeamColors.spec(border: [_blobA]); - final palette = spec.resolve(); - final derived = BeamColors.custom(const [Color(0xFFFF3264)]).resolve(); - expect(palette.data.smallBorder, derived.data.smallBorder); - expect(palette.data.smallInner, derived.data.smallInner); - expect(palette.data.lineDark, derived.data.lineDark); }); }); - group('BeamColors.custom base', () { - test('base selects which tables supply geometry and alpha', () { - final overColorful = BeamColors.custom(const [_pink]).resolve(); - final overMono = BeamColors.custom(const [ - _pink, - ], base: BeamColors.mono).resolve(); - // mono's inner-glow table is half as opaque as colorful's, and that - // alpha structure is what `base` selects. - expect(overColorful.data.smallInner[0].color.a, closeTo(0.5, 1e-6)); - expect(overMono.data.smallInner[0].color.a, closeTo(0.25, 1e-6)); - // The hue still comes from the caller's list either way. - expect(overMono.data.smallInner[0].color.r, closeTo(_pink.r, 1e-6)); - expect(overMono.data.smallInner[0].color.g, closeTo(_pink.g, 1e-6)); - }); - - test('a mono base does not make the result mono', () { - final palette = BeamColors.custom(const [ - _pink, - ], base: BeamColors.mono).resolve(); - expect(palette.forcesStaticColors, isFalse); - expect(palette.opacityMultiplier, 1.0); - expect(palette.monoTreatment, isFalse); + group('BeamColors.solid', () { + test('is one colour all the way round', () { + final p = const BeamColors.solid(_green).resolve(); + expect(p.colors, [_green]); + expect(p.stops, [0]); + for (final u in [0.0, 0.25, 0.9]) { + expect(p.sample(u), _green); + } }); - test('base participates in equality', () { - expect( - BeamColors.custom(const [_pink]), - BeamColors.custom(const [_pink], base: BeamColors.colorful), - ); - expect( - BeamColors.custom(const [_pink]).hashCode, - BeamColors.custom(const [_pink], base: BeamColors.colorful).hashCode, - ); - expect( - BeamColors.custom(const [_pink]), - isNot(BeamColors.custom(const [_pink], base: BeamColors.mono)), - ); + test('compares by colour', () { + // Built at run time, so `==` runs instead of `identical` on one const. + final red = BeamColors.solid(Color(_red.toARGB32())); + expect(const BeamColors.solid(_red), red); + expect(const BeamColors.solid(_red).hashCode, red.hashCode); expect( - BeamColors.custom(const [_pink], base: BeamColors.ocean), - BeamColors.custom(const [_pink], base: BeamColors.ocean), + const BeamColors.solid(_red), + isNot(const BeamColors.solid(_blue)), ); expect( - BeamColors.custom(const [_pink], base: BeamColors.ocean).hashCode, - BeamColors.custom(const [_pink], base: BeamColors.ocean).hashCode, + const BeamColors.solid(_red), + isNot(const BeamColors([_red])), + reason: 'a different factory is a different value', ); }); - - test('a custom base nests', () { - final nested = BeamColors.custom(const [ - _cyan, - ], base: BeamColors.custom(const [_pink], base: BeamColors.mono)); - final palette = nested.resolve(); - // Alpha structure still comes from mono, two levels down. - expect(palette.data.smallInner[0].color.a, closeTo(0.25, 1e-6)); - // Colors come from the outermost list. - expect(palette.data.smallInner[0].color.b, closeTo(_cyan.b, 1e-6)); - }); }); group('BeamColors.fromSeed', () { - const seeds = { + const seeds = { 'black': Color(0xFF000000), 'white': Color(0xFFFFFFFF), - 'pure red': Color(0xFFFF0000), + 'grey': Color(0xFF808080), + 'dark navy': Color(0xFF0A0F2E), + 'pale pink': Color(0xFFFFE6EE), 'brand blue': Color(0xFF18A8F0), - 'mid gray': Color(0xFF808080), + 'red': Color(0xFFFF0000), }; for (final MapEntry(key: name, value: seed) in seeds.entries) { for (final harmony in BeamSeedHarmony.values) { - test('$name / ${harmony.name} gives 3-4 distinct in-band colors', () { - final palette = BeamColors.fromSeed(seed, harmony: harmony).resolve(); - // The 9-slot border table cycles the derived colors, so its - // distinct set is exactly the derived palette. - final derived = {for (final b in palette.data.border) b.color}; - expect(derived.length, inInclusiveRange(3, 4), reason: '$derived'); - for (final c in derived) { + test('$name / ${harmony.name}: distinct colours in the glow band', () { + final p = BeamColors.fromSeed(seed, harmony: harmony).resolve(); + _expectWellFormed(p); + expect( + p.colors, + hasLength(harmony == BeamSeedHarmony.triadic ? 3 : 4), + ); + expect(p.colors.toSet(), hasLength(p.colors.length)); + expect(p.stops, BeamPalette.evenStops(p.colors.length)); + expect(p.fixedHue, isFalse); + // 8-bit rounding in HSLColor.toColor moves the measured values a + // hair, hence the tolerance. + for (final c in p.colors) { final hsl = HSLColor.fromColor(c); - expect( - hsl.lightness, - inInclusiveRange(0.54, 0.71), - reason: '$c is outside the glow lightness band', - ); - // 0.55 floor, times monochrome's 0.7 lowest saturation step. - expect(hsl.saturation, greaterThanOrEqualTo(0.37), reason: '$c'); - expect(c.a, 1.0); + expect(hsl.lightness, inInclusiveRange(0.55 - 0.01, 0.70 + 0.01)); + expect(c.a, 1); + // Monochrome's saturation floor is pinned separately below. + if (harmony != BeamSeedHarmony.monochrome) { + expect(hsl.saturation, greaterThanOrEqualTo(0.55 - 0.02)); + } } }); } } - test('geometry comes from the colorful preset', () { - final palette = const BeamColors.fromSeed(_brand).resolve(); - for (final (i, blob) in palette.data.border.indexed) { - expect(blob.position, colorfulPreset.border[i].position); - expect(blob.size, colorfulPreset.border[i].size); + test('monochrome keeps saturation at or above 0.55 for every seed', () { + for (final MapEntry(key: name, value: seed) in seeds.entries) { + final p = BeamColors.fromSeed( + seed, + harmony: BeamSeedHarmony.monochrome, + ).resolve(); + for (final c in p.colors) { + expect( + HSLColor.fromColor(c).saturation, + greaterThanOrEqualTo(0.55 - 0.02), + reason: name, + ); + } } - expect(palette.data.smallInner, hasLength(8)); - expect(palette.data.lineBloomDark, hasLength(5)); - // Preset alpha survives the substitution. - expect(palette.data.smallInner[0].color.a, closeTo(0.5, 1e-6)); }); - test('resolves without mono modifiers', () { - final palette = const BeamColors.fromSeed(_brand).resolve(); - expect(palette.forcesStaticColors, isFalse); - expect(palette.opacityMultiplier, 1.0); - expect(palette.monoTreatment, isFalse); - }); + const seed = Color(0xFF18A8F0); + final seedHue = HSLColor.fromColor(seed).hue; + List huesOf(BeamSeedHarmony harmony) => [ + for (final c in BeamColors.fromSeed( + seed, + harmony: harmony, + ).resolve().colors) + HSLColor.fromColor(c).hue, + ]; test('the default harmony is analogous', () { expect( - const BeamColors.fromSeed(_brand), - const BeamColors.fromSeed(_brand, harmony: BeamSeedHarmony.analogous), + const BeamColors.fromSeed(seed), + const BeamColors.fromSeed(seed, harmony: BeamSeedHarmony.analogous), ); }); - test('equality covers seed and harmony', () { - expect( - BeamColors.fromSeed(const Color(0xFF18A8F0)), - BeamColors.fromSeed(const Color(0xFF18A8F0)), - ); + test('analogous stays near the seed hue', () { + final hues = huesOf(BeamSeedHarmony.analogous); + expect(_hueDistance(hues.first, seedHue), lessThan(2)); + for (final h in hues) { + expect(_hueDistance(h, seedHue), lessThanOrEqualTo(52)); + } + }); + + test('complementary reaches the opposite hue', () { + final hues = huesOf(BeamSeedHarmony.complementary); expect( - BeamColors.fromSeed(const Color(0xFF18A8F0)).hashCode, - BeamColors.fromSeed(const Color(0xFF18A8F0)).hashCode, + hues.any((h) => _hueDistance(h, seedHue + 180) < 2), + isTrue, + reason: '$hues around $seedHue', ); + }); + + test('triadic spreads three hues a third of the wheel apart', () { + final hues = huesOf(BeamSeedHarmony.triadic); + expect(_hueDistance(hues[0], seedHue), lessThan(2)); + expect(_hueDistance(hues[1], seedHue + 120), lessThan(2)); + expect(_hueDistance(hues[2], seedHue + 240), lessThan(2)); + }); + + test('monochrome keeps the seed hue', () { + for (final h in huesOf(BeamSeedHarmony.monochrome)) { + expect(_hueDistance(h, seedHue), lessThan(2)); + } + }); + + test('equality covers seed and harmony', () { expect( - const BeamColors.fromSeed(_brand), - isNot(const BeamColors.fromSeed(Color(0xFFF018A8))), + const BeamColors.fromSeed(seed), + isNot(const BeamColors.fromSeed(Color(0xFF18A8F1))), ); expect( - const BeamColors.fromSeed(_brand), - isNot( - const BeamColors.fromSeed(_brand, harmony: BeamSeedHarmony.triadic), - ), + const BeamColors.fromSeed(seed, harmony: BeamSeedHarmony.triadic), + isNot(const BeamColors.fromSeed(seed)), ); expect( - const BeamColors.fromSeed(_brand), - isNot(BeamColors.custom(const [_brand])), + const BeamColors.fromSeed( + seed, + harmony: BeamSeedHarmony.triadic, + ).resolve(), + isNot(const BeamColors.fromSeed(seed).resolve()), ); }); + }); - test('different harmonies produce different palettes', () { - final tables = { - for (final h in BeamSeedHarmony.values) - h: BeamColors.fromSeed(_brand, harmony: h).resolve().data.border[1], - }; - expect(tables.values.map((b) => b.color).toSet(), hasLength(4)); + group('BeamColors.fromScheme', () { + ColorScheme scheme(Color p, Color s, Color t) => + ColorScheme.dark(primary: p, secondary: s, tertiary: t); + + test('uses primary, secondary and tertiary, in order, evenly spaced', () { + final p = BeamColors.fromScheme(scheme(_red, _green, _blue)).resolve(); + expect(p.colors, [_red, _green, _blue]); + expect(p.stops, BeamPalette.evenStops(3)); }); - test('analogous harmony wraps hues below zero', () { - final palette = const BeamColors.fromSeed(Color(0xFFFF0000)).resolve(); - expect(palette.data.border, hasLength(9)); + test('drops a role that matches an earlier one', () { expect( - HSLColor.fromColor(palette.data.border[2].color).hue, - closeTo(335, 1), + BeamColors.fromScheme(scheme(_red, _red, _blue)).resolve().colors, + [_red, _blue], + ); + expect( + BeamColors.fromScheme(scheme(_red, _blue, _red)).resolve().colors, + [_red, _blue], ); }); - test('triadic spreads the seed hue by 120 degrees', () { - final palette = const BeamColors.fromSeed( - _brand, - harmony: BeamSeedHarmony.triadic, - ).resolve(); - final hues = [ - for (var i = 0; i < 3; i++) - HSLColor.fromColor(palette.data.border[i].color).hue, - ]; - expect((hues[1] - hues[0]) % 360, closeTo(120, 1)); - expect((hues[2] - hues[1]) % 360, closeTo(120, 1)); - }); - }); - - group('BeamColors.fromScheme', () { - test('uses primary, secondary and tertiary', () { - const scheme = ColorScheme.dark( - primary: Color(0xFFFF0000), - secondary: Color(0xFF00FF00), - tertiary: Color(0xFF0000FF), - ); + test('drops a near-duplicate role', () { + const almostRed = Color(0xFFFA0303); expect( - BeamColors.fromScheme(scheme), - BeamColors.custom(const [ - Color(0xFFFF0000), - Color(0xFF00FF00), - Color(0xFF0000FF), - ]), + BeamColors.fromScheme(scheme(_red, almostRed, _blue)).resolve().colors, + [_red, _blue], ); }); - test('drops near-duplicate roles', () { - const scheme = ColorScheme.dark( - primary: Color(0xFFFF0000), - secondary: Color(0xFFFF0102), - tertiary: Color(0xFF0000FF), - ); + test('keeps roles that are merely similar', () { + const darkerRed = Color(0xFFB00000); expect( - BeamColors.fromScheme(scheme), - BeamColors.custom(const [Color(0xFFFF0000), Color(0xFF0000FF)]), + BeamColors.fromScheme(scheme(_red, darkerRed, _blue)).resolve().colors, + [_red, darkerRed, _blue], ); }); - test('an all-identical scheme collapses to one color', () { - const scheme = ColorScheme.dark( - primary: _pink, - secondary: _pink, - tertiary: _pink, + test('an all-identical scheme collapses to one colour', () { + expect( + BeamColors.fromScheme(scheme(_green, _green, _green)).resolve().colors, + [_green], ); - expect(BeamColors.fromScheme(scheme), BeamColors.custom(const [_pink])); - expect(BeamColors.fromScheme(scheme).resolve().data.border, hasLength(9)); }); - test('value-equal on the three roles only', () { - const a = ColorScheme.dark( - primary: Color(0xFFFF0000), - secondary: Color(0xFF00FF00), - tertiary: Color(0xFF0000FF), - surface: Color(0xFF111111), - ); - const b = ColorScheme.dark( - primary: Color(0xFFFF0000), - secondary: Color(0xFF00FF00), - tertiary: Color(0xFF0000FF), - surface: Color(0xFF222222), - ); - expect(BeamColors.fromScheme(a), BeamColors.fromScheme(b)); + test('equal schemes give equal colours', () { expect( - BeamColors.fromScheme(a).hashCode, - BeamColors.fromScheme(b).hashCode, + BeamColors.fromScheme(scheme(_red, _green, _blue)), + BeamColors.fromScheme(scheme(_red, _green, _blue)), ); expect( - BeamColors.fromScheme(a), - isNot( - BeamColors.fromScheme( - const ColorScheme.dark( - primary: Color(0xFF00FF00), - secondary: Color(0xFFFF0000), - tertiary: Color(0xFF0000FF), - ), - ), - ), + BeamColors.fromScheme(scheme(_red, _green, _blue)), + isNot(BeamColors.fromScheme(scheme(_red, _blue, _green))), ); }); + }); - test('geometry comes from the colorful preset', () { - const scheme = ColorScheme.dark( - primary: Color(0xFFFF0000), - secondary: Color(0xFF00FF00), - tertiary: Color(0xFF0000FF), - ); - final palette = BeamColors.fromScheme(scheme).resolve(); - for (final (i, blob) in palette.data.border.indexed) { - expect(blob.position, colorfulPreset.border[i].position); - expect(blob.size, colorfulPreset.border[i].size); + group('BeamColors.lerp', () { + const a = BeamColors.ocean; + const b = BeamColors.sunset; + + test('t = 0 and t = 1 are the ends unchanged', () { + expect(const BeamColors.lerp(a, b, 0).resolve(), a.resolve()); + expect(const BeamColors.lerp(a, b, 1).resolve(), b.resolve()); + }); + + test('t is clamped to 0–1, and NaN reads as 0', () { + expect(const BeamColors.lerp(a, b, -2).resolve(), a.resolve()); + expect(const BeamColors.lerp(a, b, 7).resolve(), b.resolve()); + expect(const BeamColors.lerp(a, b, double.nan).resolve(), a.resolve()); + }); + + test('in between, both ends are sampled at eight even positions', () { + final p = const BeamColors.lerp(a, b, 0.5).resolve(); + expect(p.colors, hasLength(maxPaletteStops)); + expect(p.stops, BeamPalette.evenStops(maxPaletteStops)); + _expectWellFormed(p); + }); + + test('each sample lies between the two ends at that position', () { + final pa = a.resolve(); + final pb = b.resolve(); + for (final t in [0.1, 0.5, 0.9]) { + final p = BeamColors.lerp(a, b, t).resolve(); + for (var i = 0; i < p.length; i++) { + final u = p.stops[i]; + final ca = pa.sample(u); + final cb = pb.sample(u); + final c = p.colors[i]; + for (final (x, y, z) in [ + (ca.r, cb.r, c.r), + (ca.g, cb.g, c.g), + (ca.b, cb.b, c.b), + (ca.a, cb.a, c.a), + ]) { + final lo = x < y ? x : y; + final hi = x < y ? y : x; + expect(z, inInclusiveRange(lo - 1e-9, hi + 1e-9)); + } + // Gamma-aware, the same blend the shader uses. + expect(c, mixColor(ca, cb, t)); + } } }); - }); - group('BeamColors.lerp', () { - const ocean = BeamColors.ocean; - const sunset = BeamColors.sunset; + test('moves monotonically from a towards b', () { + final pb = b.resolve(); + double distanceToB(double t) { + final p = BeamColors.lerp(a, b, t).resolve(); + var sum = 0.0; + for (var i = 0; i < p.length; i++) { + final target = pb.sample(p.stops[i]); + sum += + (p.colors[i].r - target.r).abs() + + (p.colors[i].g - target.g).abs() + + (p.colors[i].b - target.b).abs(); + } + return sum; + } - test('t = 0 reproduces the tables of a', () { - expect( - const BeamColors.lerp(ocean, sunset, 0).resolve().data, - ocean.resolve().data, - ); + expect(distanceToB(0.25), greaterThan(distanceToB(0.5))); + expect(distanceToB(0.5), greaterThan(distanceToB(0.75))); }); - test('t = 1 reproduces the tables of b', () { + test('fixes the hue when the nearer end does', () { expect( - const BeamColors.lerp(ocean, sunset, 1).resolve().data, - sunset.resolve().data, + const BeamColors.lerp(BeamColors.mono, b, 0.3).resolve().fixedHue, + isTrue, ); - }); - - test('the midpoint is the per-entry Color.lerp of both ends', () { - final a = ocean.resolve().data; - final b = sunset.resolve().data; - final mid = const BeamColors.lerp(ocean, sunset, 0.5).resolve().data; - for (final (i, blob) in mid.border.indexed) { - expect( - blob.color, - Color.lerp(a.border[i].color, b.border[i].color, .5), - ); - expect(blob.position, a.border[i].position); - expect(blob.size, a.border[i].size); - } - for (final (i, blob) in mid.lineInner.indexed) { - expect( - blob.color, - Color.lerp(a.lineInner[i].color, b.lineInner[i].color, .5), - ); - expect(blob.sizeW, a.lineInner[i].sizeW); - expect(blob.offsetX, a.lineInner[i].offsetX); - } expect( - mid.spike.primary, - Color.lerp(a.spike.primary, b.spike.primary, .5), + const BeamColors.lerp(BeamColors.mono, b, 0.7).resolve().fixedHue, + isFalse, ); expect( - mid.spikeLt.secondary, - Color.lerp(a.spikeLt.secondary, b.spikeLt.secondary, .5), + const BeamColors.lerp(a, BeamColors.gold, 0.8).resolve().fixedHue, + isTrue, ); expect( - mid.lineBloomDark[2].color2, - Color.lerp(a.lineBloomDark[2].color2, b.lineBloomDark[2].color2, .5), + const BeamColors.lerp(a, BeamColors.gold, 0.2).resolve().fixedHue, + isFalse, ); - expect(mid.smallInner, hasLength(8)); - }); - - test('the mono modifiers come from the nearer end', () { - final nearMono = const BeamColors.lerp( - BeamColors.mono, - ocean, - 0.2, - ).resolve(); - expect(nearMono.forcesStaticColors, isTrue); - expect(nearMono.monoTreatment, isTrue); - expect(nearMono.opacityMultiplier, closeTo(0.6, 1e-9)); - - final nearOcean = const BeamColors.lerp( - BeamColors.mono, - ocean, - 0.8, - ).resolve(); - expect(nearOcean.forcesStaticColors, isFalse); - expect(nearOcean.monoTreatment, isFalse); - expect(nearOcean.opacityMultiplier, closeTo(0.9, 1e-9)); - }); - - test('a shorter b table cycles', () { - const spec = BeamColors.spec(border: [_blobA]); - final lerped = const BeamColors.lerp(ocean, spec, 1).resolve().data; - expect(lerped.border, hasLength(9)); - expect(lerped.border.map((b) => b.color).toSet(), hasLength(1)); - // Geometry still comes from a. - expect(lerped.border[4].size, ocean.resolve().data.border[4].size); }); test('equality covers both ends and t', () { expect( - const BeamColors.lerp(ocean, sunset, 0.25), - const BeamColors.lerp(ocean, sunset, 0.25), + const BeamColors.lerp(a, b, 0.5), + BeamColors.lerp(a, b, double.parse('0.5')), ); expect( - const BeamColors.lerp(ocean, sunset, 0.25).hashCode, - const BeamColors.lerp(ocean, sunset, 0.25).hashCode, + const BeamColors.lerp(a, b, 0.5).hashCode, + BeamColors.lerp(a, b, double.parse('0.5')).hashCode, ); expect( - const BeamColors.lerp(ocean, sunset, 0.25), - isNot(const BeamColors.lerp(ocean, sunset, 0.75)), + const BeamColors.lerp(a, b, 0.5), + isNot(const BeamColors.lerp(b, a, 0.5)), ); expect( - const BeamColors.lerp(ocean, sunset, 0.25), - isNot(const BeamColors.lerp(sunset, ocean, 0.25)), + const BeamColors.lerp(a, b, 0.5), + isNot(const BeamColors.lerp(a, b, 0.6)), ); - expect(const BeamColors.lerp(ocean, sunset, 0), isNot(ocean)); }); - test('extrapolates past 1', () { - final past = const BeamColors.lerp(ocean, sunset, 2).resolve().data; - final a = ocean.resolve().data; - final b = sunset.resolve().data; + test('an invalid end throws on resolve', () { expect( - past.border[0].color, - Color.lerp(a.border[0].color, b.border[0].color, 2), + () => const BeamColors.lerp(a, BeamColors([]), 0.5).resolve(), + throwsArgumentError, ); }); }); - group('BeamColors.scaleAlpha', () { - test('multiplies every table entry alpha and keeps the hue', () { - final base = BeamColors.colorful.resolve().data; - final dim = BeamColors.colorful.scaleAlpha(0.5).resolve().data; - for (final (i, blob) in dim.smallInner.indexed) { - expect(blob.color.a, closeTo(base.smallInner[i].color.a * 0.5, 1e-6)); - expect(blob.color.r, closeTo(base.smallInner[i].color.r, 1e-6)); - expect(blob.position, base.smallInner[i].position); - expect(blob.size, base.smallInner[i].size); + group('scaleAlpha', () { + test('multiplies every stop alpha and keeps the rest', () { + const source = BeamColors([_red, Color(0x8000FF00)], stops: [0.1, 0.6]); + final p = source.scaleAlpha(0.5).resolve(); + expect(p.colors[0].a, closeTo(0.5, 1e-9)); + expect(p.colors[1].a, closeTo(source.resolve().colors[1].a / 2, 1e-9)); + expect(p.stops, [0.1, 0.6]); + for (var i = 0; i < p.length; i++) { + final c = p.colors[i]; + final s = source.resolve().colors[i]; + expect((c.r, c.g, c.b), (s.r, s.g, s.b)); } - expect(dim.border.first.color.a, closeTo(0.5, 1e-6)); - expect(dim.spike.primary.a, closeTo(base.spike.primary.a * 0.5, 1e-6)); - expect( - dim.lineBloomDark[0].color2.a, - closeTo(base.lineBloomDark[0].color2.a * 0.5, 1e-6), - ); - expect(dim.lineInner[3].sizeW, base.lineInner[3].sizeW); }); - test('clamps the product at 1', () { - final bright = BeamColors.colorful.scaleAlpha(4).resolve().data; - for (final blob in [...bright.border, ...bright.smallInner]) { - expect(blob.color.a, lessThanOrEqualTo(1.0)); - } - // colorful's smallInner[0] is 0.5 -> 2.0 before the clamp. - expect(bright.smallInner[0].color.a, 1.0); - expect(bright.border.first.color.a, 1.0); + test('clamps the product to 0–1', () { + const source = BeamColors([_red, Color(0x8000FF00)]); + final up = source.scaleAlpha(3).resolve(); + expect(up.colors.map((c) => c.a), everyElement(1)); + final down = source.scaleAlpha(0).resolve(); + expect(down.colors.map((c) => c.a), everyElement(0)); }); - test('a zero factor makes every entry transparent', () { - final gone = BeamColors.colorful.scaleAlpha(0).resolve().data; - for (final blob in gone.border) { - expect(blob.color.a, 0.0); + test('keeps the source palette fixedHue', () { + expect(BeamColors.mono.scaleAlpha(0.5).resolve().fixedHue, isTrue); + expect(BeamColors.ocean.scaleAlpha(0.5).resolve().fixedHue, isFalse); + }); + + test('stacks multiplicatively', () { + final twice = BeamColors.ocean.scaleAlpha(0.5).scaleAlpha(0.5).resolve(); + final once = BeamColors.ocean.scaleAlpha(0.25).resolve(); + for (var i = 0; i < once.length; i++) { + expect(twice.colors[i].a, closeTo(once.colors[i].a, 1e-9)); } - expect(gone.spike.primary.a, 0.0); - expect(gone.lineBloomLight[4].color1.a, 0.0); }); - test('keeps the source palette modifiers', () { - final dim = BeamColors.mono.scaleAlpha(0.5).resolve(); - expect(dim.forcesStaticColors, isTrue); - expect(dim.opacityMultiplier, 0.5); - expect(dim.monoTreatment, isTrue); + test('a negative or NaN factor throws on resolve, not construction', () { + final negative = BeamColors.ocean.scaleAlpha(-0.5); + expect(negative.resolve, throwsArgumentError); expect( - BeamColors.gold.scaleAlpha(0.5).resolve().forcesStaticColors, - isTrue, + BeamColors.ocean.scaleAlpha(double.nan).resolve, + throwsArgumentError, ); }); @@ -726,104 +530,198 @@ void main() { BeamColors.ocean.scaleAlpha(0.5), isNot(BeamColors.sunset.scaleAlpha(0.5)), ); - expect(BeamColors.ocean.scaleAlpha(1), isNot(BeamColors.ocean)); }); + }); + + group('validation', () { + // Each is a const value — construction never throws; resolution does, + // in release builds too. + final bad = { + 'no colours': const BeamColors([]), + 'nine colours': const BeamColors([ + _red, + _green, + _blue, + _red, + _green, + _blue, + _red, + _green, + _blue, + ]), + 'fewer stops than colours': const BeamColors( + [_red, _green, _blue], + stops: [0, 0.5], + ), + 'more stops than colours': const BeamColors( + [_red, _green], + stops: [0, 0.3, 0.6], + ), + 'descending stops': const BeamColors([_red, _green], stops: [0.6, 0.3]), + 'a stop at 1': const BeamColors([_red, _green], stops: [0, 1]), + 'a negative stop': const BeamColors([_red, _green], stops: [-0.1, 0.5]), + 'a NaN stop': const BeamColors([_red, _green], stops: [0, double.nan]), + 'an infinite stop': const BeamColors( + [_red, _green], + stops: [0, double.infinity], + ), + }; - test('stacks', () { - final twice = BeamColors.colorful.scaleAlpha(0.5).scaleAlpha(0.5); - expect(twice.resolve().data.border.first.color.a, closeTo(0.25, 1e-6)); + for (final MapEntry(:key, :value) in bad.entries) { + test('$key throws an ArgumentError on resolve', () { + expect(value.resolve, throwsArgumentError); + // A failed resolve is not cached: it fails again. + expect(value.resolve, throwsArgumentError); + }); + } + + test('eight colours is the most that resolves', () { + final p = const BeamColors([ + _red, + _green, + _blue, + _red, + _green, + _blue, + _red, + _green, + ]).resolve(); + expect(p.length, maxPaletteStops); }); - test('rejects a negative factor', () { + test('a scaled invalid palette throws too', () { expect( - () => BeamColors.colorful.scaleAlpha(-1).resolve(), - throwsA(isA()), + const BeamColors([]).scaleAlpha(0.5).resolve, + throwsArgumentError, ); }); }); - group('Flutter-only presets', () { - test('gold pins the hue but keeps full layer opacity', () { - final gold = BeamColors.gold.resolve(); - expect(gold.forcesStaticColors, isTrue); - expect(gold.opacityMultiplier, 1.0); - expect(gold.monoTreatment, isFalse); - }); - - test('every other new preset animates its hue', () { - for (final colors in const [ - BeamColors.aurora, - BeamColors.neon, - BeamColors.candy, - BeamColors.ember, - BeamColors.ice, - BeamColors.holographic, + group('the resolve memo', () { + test('equal values resolve to the identical palette', () { + final a = BeamColors([_red, Color(int.parse('0xFF123456'))]); + final b = BeamColors([_red, Color(int.parse('0xFF123456'))]); + expect(identical(a, b), isFalse); + expect(identical(a.resolve(), b.resolve()), isTrue); + + for (final (x, y) in [ + ( + BeamColors.fromSeed(Color(int.parse('0xFF18A8F0'))), + BeamColors.fromSeed(Color(int.parse('0xFF18A8F0'))), + ), + ( + BeamColors.lerp(BeamColors.ocean, BeamColors.sunset, _rt(0.4)), + BeamColors.lerp(BeamColors.ocean, BeamColors.sunset, _rt(0.4)), + ), + (BeamColors.ocean.scaleAlpha(0.4), BeamColors.ocean.scaleAlpha(0.4)), + ( + BeamColors.solid(Color(int.parse('0xFF445566'))), + BeamColors.solid(Color(int.parse('0xFF445566'))), + ), ]) { - final palette = colors.resolve(); - expect(palette.forcesStaticColors, isFalse, reason: '$colors'); - expect(palette.opacityMultiplier, 1.0, reason: '$colors'); - expect(palette.monoTreatment, isFalse, reason: '$colors'); + expect(identical(x.resolve(), y.resolve()), isTrue, reason: '$x'); } }); - test('the new presets are all distinct from each other', () { - const all = [ - BeamColors.aurora, - BeamColors.neon, - BeamColors.candy, - BeamColors.ember, - BeamColors.ice, - BeamColors.gold, - BeamColors.holographic, - BeamColors.colorful, - BeamColors.mono, - BeamColors.ocean, - BeamColors.sunset, - ]; - expect(all.toSet(), hasLength(all.length)); + test('unequal values resolve to unequal palettes', () { expect( - all.map((c) => c.resolve().data.border[0].color).toSet(), - hasLength(all.length), + const BeamColors([_red]).resolve(), + isNot(const BeamColors([_blue]).resolve()), ); }); - }); - group('BeamBlob.size semantics', () { - test('a spec blob keeps the radii it was given', () { - // `size` is the ellipse RADII, not its diameters: painters pass - // `size.width`/`size.height` straight through as radiusX/radiusY, so a - // 70x40 blob spans 140x80 logical pixels. Nothing in the resolve path - // may halve or double it. - const blob = BeamBlob( - color: Color(0xFFFF0080), - position: Offset(0.33, -0.074), - size: Size(70, 40), - ); - final palette = const BeamColors.spec(border: [blob]).resolve(); - expect(palette.data.border.single.size, const Size(70, 40)); - expect(palette.data.border.single.position, const Offset(0.33, -0.074)); - // The derived tables keep the source library's radii too. - expect(palette.data.border.single.size, colorfulPreset.border[0].size); + test('eviction past capacity still yields an equal palette', () { + // Keys distinct from every other test in this file. + BeamColors key(int i) => BeamColors([Color(0xFF7F0000 | i)]); + final oldest = key(0); + final first = oldest.resolve(); + // Far past any reasonable capacity, never touching `oldest`. + for (var i = 1; i <= 200; i++) { + key(i).resolve(); + } + final again = oldest.resolve(); + expect(again, first, reason: 'rebuilt, and equal to the evicted one'); + expect( + identical(again, first), + isFalse, + reason: 'the memo is bounded, so the old entry was dropped', + ); + }); + + test('a hit keeps an entry fresh: the memo drops the least recent', () { + // Keys distinct from every other test in this file. + BeamColors key(int i) => BeamColors([Color(0xFF5F0000 | i)]); + final kept = BeamColors([const Color(0xFF5E0000)]); + final first = kept.resolve(); + // The same churn that evicts an untouched entry, but `kept` is read + // again every few resolves — well inside any capacity worth having. + for (var i = 1; i <= 200; i++) { + key(i).resolve(); + if (i % 8 == 0) { + expect(identical(kept.resolve(), first), isTrue, reason: '$i'); + } + } + }); + + test('presets survive any amount of churn', () { + final ocean = BeamColors.ocean.resolve(); + for (var i = 0; i < 200; i++) { + BeamColors([Color(0xFF3F0000 | i)]).resolve(); + } + expect(identical(BeamColors.ocean.resolve(), ocean), isTrue); + }); + + test('mutating the source lists cannot corrupt a cached palette', () { + final colors = [const Color(0xFF0A0B0C), const Color(0xFF0D0E0F)]; + final stops = [0.1, 0.6]; + final choice = BeamColors(colors, stops: stops); + final palette = choice.resolve(); + + colors[0] = _green; + stops[1] = 0.9; + + expect(palette.colors, const [Color(0xFF0A0B0C), Color(0xFF0D0E0F)]); + expect(palette.stops, const [0.1, 0.6]); + expect( + identical( + const BeamColors( + [Color(0xFF0A0B0C), Color(0xFF0D0E0F)], + stops: [0.1, 0.6], + ).resolve(), + palette, + ), + isTrue, + reason: 'the original value still finds its palette', + ); + // The mutated choice is now a different value with its own palette. + final mutated = choice.resolve(); + expect(mutated.colors, [_green, const Color(0xFF0D0E0F)]); + expect(mutated.stops, [0.1, 0.9]); + }); + + test('resolved palettes are unmodifiable', () { + final p = BeamColors([_red, Color(int.parse('0xFF0F0F0F'))]).resolve(); + expect(() => p.colors[0] = _blue, throwsUnsupportedError); + expect(() => p.stops[0] = 0.5, throwsUnsupportedError); }); }); - testWidgets('equal custom colors do not re-resolve the config', ( - tester, - ) async { - Widget build() => _host( - BorderBeam.rotate( - colors: BeamColors.custom([ - const Color(0xFFFF00AA), - const Color(0xFF00FFEE), - ]), - child: const SizedBox.expand(), - ), + test('toString names the factory', () { + expect(BeamColors.ocean.toString(), 'BeamColors.ocean'); + expect( + const BeamColors.solid(_red).toString(), + startsWith('BeamColors.solid('), + ); + expect( + const BeamColors.fromSeed( + _red, + harmony: BeamSeedHarmony.triadic, + ).toString(), + endsWith('harmony: triadic)'), + ); + expect( + BeamColors.ocean.scaleAlpha(0.5).toString(), + 'BeamColors.ocean.scaleAlpha(0.5)', ); - - await tester.pumpWidget(build()); - final first = _beamPainter(tester).config; - // A fresh widget carrying a fresh — but equal — BeamColors instance. - await tester.pumpWidget(build()); - expect(identical(_beamPainter(tester).config, first), isTrue); }); } diff --git a/test/models/beam_config_test.dart b/test/models/beam_config_test.dart index a6ac8c3..a1c88e0 100644 --- a/test/models/beam_config_test.dart +++ b/test/models/beam_config_test.dart @@ -1,57 +1,25 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/scheduler.dart'; +import 'dart:ui' show Brightness; + +import 'package:flutter/painting.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam/src/animation/beam_clock.dart'; -import 'package:flutter_border_beam/src/animation/beam_phases.dart'; import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; +import 'package:flutter_border_beam/src/models/beam_palette.dart'; import 'package:flutter_test/flutter_test.dart'; -const _style = BeamStyle( - strength: 0.8, - brightness: 1.1, - saturation: 1.4, - hueRange: 20, - hueBase: 5, - staticColors: false, - strokeOpacityFactor: 0.9, - innerOpacityFactor: 0.8, - bloomOpacityFactor: 0.7, - glowBoost: 1.2, - coreBlur: 3, - bloomBlur: 4, - glowBrightness: 1.5, - glowSaturation: 1.6, -); - -const _shape = BeamShape( - radius: BorderRadius.all(Radius.circular(10)), - borderWidth: 2, - superellipse: false, -); - -const _timing = BeamTiming( - cycle: Duration(seconds: 2), - cycleGap: Duration(seconds: 1), - speed: 1, - huePeriod: Duration(seconds: 5), - bloomHuePeriod: Duration(seconds: 6), - breatheFactor: 1.1, - spikeFactor: 1.2, - spike2Factor: 1.3, -); +double _seconds(Duration d) => + d.inMicroseconds / Duration.microsecondsPerSecond; BeamConfig _resolve({ - BeamVariant variant = BeamVariant.rotate, - BeamColors colors = BeamColors.colorful, + BeamEffect effect = const BeamEffect.rotate(), + BeamPalette? palette, Brightness brightness = Brightness.dark, - BeamStyle style = _style, - BeamShape shape = _shape, - BeamTiming timing = _timing, + BeamStyle style = const BeamStyle(), + BeamShape shape = const BeamShape(), + BeamTiming timing = const BeamTiming(), TextDirection textDirection = TextDirection.ltr, }) => BeamConfig.resolve( - variant: variant, - palette: colors.resolve(), + effect: effect, + palette: palette ?? BeamColors.colorful.resolve(), brightness: brightness, style: style, shape: shape, @@ -59,470 +27,321 @@ BeamConfig _resolve({ textDirection: textDirection, ); -BeamPainter _beamPainter(WidgetTester tester) => tester - .widgetList( - find.descendant( - of: find.byType(BorderBeam), - matching: find.byType(CustomPaint), - ), - ) - .expand((paint) => [paint.painter, paint.foregroundPainter]) - .whereType() - .first; - -Widget _host(Widget child) => MaterialApp( - theme: ThemeData(brightness: Brightness.dark), - home: Scaffold( - body: Center(child: SizedBox(width: 350, height: 140, child: child)), - ), -); - -/// `BeamConfig` is the value the painter compares: two resolutions of the -/// same inputs must be `==` (so a rebuilt-inline style never repaints), and -/// every input that reaches a painted value must break that equality. +/// `BeamConfig` is the settled value the renderer paints from: every +/// inherited field filled in from the effect's defaults, every number +/// clamped to what the shader can use, and the whole thing value-equal so a +/// rebuilt-inline style never repaints. void main() { - test('resolution rejects invalid durations in release builds', () { - final zero = Duration.zero; - final negative = const Duration(microseconds: -1); - - expect( - () => _resolve(timing: BeamTiming(cycle: zero)), - throwsArgumentError, - ); - expect( - () => _resolve(timing: BeamTiming(cycleGap: negative)), - throwsArgumentError, - ); - expect( - () => _resolve(timing: BeamTiming(huePeriod: zero)), - throwsArgumentError, - ); - expect( - () => _resolve(timing: BeamTiming(bloomHuePeriod: zero)), - throwsArgumentError, - ); - }); - - group('equality', () { - test('two resolutions of the same inputs are equal', () { - final a = _resolve(); - final b = _resolve(); - expect(identical(a, b), isFalse); - expect(a, b); - expect(a.hashCode, b.hashCode); - }); + group('effect defaults', () { + for (final effect in BeamEffect.values) { + test( + '${effect.name}: unset timing and hue mode come from the effect', + () { + final config = _resolve(effect: effect); + expect(config.effect, effect); + expect( + config.cycleSeconds, + closeTo(_seconds(effect.defaultCycle), 1e-12), + ); + expect( + config.gapSeconds, + closeTo(_seconds(effect.defaultCycleGap), 1e-12), + ); + expect( + config.huePeriodSeconds, + closeTo(_seconds(effect.defaultHuePeriod), 1e-12), + ); + expect(config.hueMode, effect.defaultHueMode); + expect(config.cycleSeconds, greaterThan(0)); + expect(config.huePeriodSeconds, greaterThan(0)); + }, + ); - // Every input the painter reads, one at a time. - final mutations = { - 'variant': () => _resolve(variant: BeamVariant.small), - 'palette': () => _resolve(colors: BeamColors.ocean), - 'brightness': () => _resolve(brightness: Brightness.light), - 'style.strength': () => _resolve(style: _style.copyWith(strength: 0.81)), - 'style.brightness': () => - _resolve(style: _style.copyWith(brightness: 1.11)), - 'style.saturation': () => - _resolve(style: _style.copyWith(saturation: 1.41)), - 'style.hueRange': () => _resolve(style: _style.copyWith(hueRange: 21)), - 'style.hueBase': () => _resolve(style: _style.copyWith(hueBase: 6)), - 'style.staticColors': () => - _resolve(style: _style.copyWith(staticColors: true)), - 'style.strokeOpacityFactor': () => - _resolve(style: _style.copyWith(strokeOpacityFactor: 0.91)), - 'style.innerOpacityFactor': () => - _resolve(style: _style.copyWith(innerOpacityFactor: 0.81)), - 'style.bloomOpacityFactor': () => - _resolve(style: _style.copyWith(bloomOpacityFactor: 0.71)), - 'style.glowBoost': () => _resolve(style: _style.copyWith(glowBoost: 1.3)), - 'style.coreBlur': () => _resolve(style: _style.copyWith(coreBlur: 3.5)), - 'style.bloomBlur': () => _resolve(style: _style.copyWith(bloomBlur: 4.5)), - 'style.glowBrightness': () => - _resolve(style: _style.copyWith(glowBrightness: 1.51)), - 'style.glowSaturation': () => - _resolve(style: _style.copyWith(glowSaturation: 1.61)), - 'style.themeConfig': () => _resolve( - style: _style.copyWith( - themeConfig: BeamThemeConfig.presetFor( - BeamVariant.rotate, - Brightness.dark, - ).copyWith(bloomOpacity: 0.99), - ), - ), - 'shape.radius': () => - _resolve(shape: _shape.copyWith(radius: BorderRadius.circular(11))), - 'shape.radius (one corner)': () => _resolve( - shape: _shape.copyWith( - radius: const BorderRadius.only(topLeft: Radius.circular(10)), - ), - ), - 'shape.borderWidth': () => - _resolve(shape: _shape.copyWith(borderWidth: 2.5)), - 'shape.superellipse': () => - _resolve(shape: _shape.copyWith(superellipse: true)), - 'timing.cycle': () => _resolve( - timing: _timing.copyWith(cycle: const Duration(milliseconds: 2001)), - ), - 'timing.cycleGap': () => _resolve( - timing: _timing.copyWith(cycleGap: const Duration(milliseconds: 1001)), - ), - 'timing.huePeriod': () => _resolve( - timing: _timing.copyWith(huePeriod: const Duration(seconds: 6)), - ), - 'timing.bloomHuePeriod': () => _resolve( - timing: _timing.copyWith(bloomHuePeriod: const Duration(seconds: 7)), - ), - 'timing.breatheFactor': () => - _resolve(timing: _timing.copyWith(breatheFactor: 1.15)), - 'timing.spikeFactor': () => - _resolve(timing: _timing.copyWith(spikeFactor: 1.25)), - 'timing.spike2Factor': () => - _resolve(timing: _timing.copyWith(spike2Factor: 1.35)), - 'style.hueMode': () => - _resolve(style: _style.copyWith(hueMode: BeamHueMode.continuous)), - 'style.tailLength': () => - _resolve(style: _style.copyWith(tailLength: 1.5)), - 'style.glowSpread': () => - _resolve(style: _style.copyWith(glowSpread: 1.5)), - 'style.comet': () => _resolve(style: _style.copyWith(comet: true)), - 'style.sparkle': () => _resolve(style: _style.copyWith(sparkle: 0.5)), - 'style.segments': () => _resolve(style: _style.copyWith(segments: 6)), - 'shape.edge': () => _resolve(shape: _shape.copyWith(edge: BeamEdge.top)), - 'shape.ringOffset': () => _resolve(shape: _shape.copyWith(ringOffset: 4)), - 'shape.segment': () => - _resolve(shape: _shape.copyWith(segment: BeamSegment.bottomHalf)), - 'shape.wrapCorners': () => - _resolve(shape: _shape.copyWith(wrapCorners: true)), - 'shape.contour': () => _resolve( - shape: _shape.copyWith( - contour: BeamPathContour( - (rect) => Path()..addOval(rect), - key: 'oval', + test('${effect.name}: explicit timing and hue mode win', () { + final config = _resolve( + effect: effect, + style: const BeamStyle(hueMode: BeamHueMode.continuous), + timing: const BeamTiming( + cycle: Duration(milliseconds: 1234), + cycleGap: Duration(milliseconds: 321), + huePeriod: Duration(seconds: 5), ), - ), - ), - 'timing.direction': () => - _resolve(timing: _timing.copyWith(direction: BeamDirection.reverse)), - 'timing.phaseOffset': () => - _resolve(timing: _timing.copyWith(phaseOffset: 0.5)), - 'timing.beamCount': () => - _resolve(timing: _timing.copyWith(beamCount: 2)), - 'style.innerSizeScale': () => - _resolve(style: _style.copyWith(innerSizeScale: 0.6)), - 'style.renderScale': () => - _resolve(style: _style.copyWith(renderScale: 0.5)), - 'style.pulseOutsideTuning': () => _resolve( - style: _style.copyWith( - pulseOutsideTuning: BeamPulseOutsideTuning.stock, - ), - ), - }; - - for (final MapEntry(key: name, value: mutate) in mutations.entries) { - test('$name breaks equality', () { - final base = _resolve(); - final mutated = mutate(); - expect(mutated, isNot(base), reason: name); - expect(mutated.hashCode, isNot(base.hashCode), reason: name); + ); + expect(config.cycleSeconds, closeTo(1.234, 1e-12)); + expect(config.gapSeconds, closeTo(0.321, 1e-12)); + expect(config.huePeriodSeconds, closeTo(5, 1e-12)); + expect(config.hueMode, BeamHueMode.continuous); }); } + }); - test('textDirection breaks equality for a directional radius', () { - const shape = BeamShape( - radius: BorderRadiusDirectional.only(topStart: Radius.circular(20)), - ); - final ltr = _resolve(shape: shape); - final rtl = _resolve(shape: shape, textDirection: TextDirection.rtl); - expect(rtl, isNot(ltr)); - expect(rtl.borderRadius.topRight, const Radius.circular(20)); - expect( - _resolve(textDirection: TextDirection.rtl), - _resolve(), - reason: 'a non-directional radius resolves the same either way', - ); + group('hue', () { + test('a fixed-hue palette never drifts, whatever the style asks', () { + for (final colors in [BeamColors.mono, BeamColors.gold]) { + for (final mode in [null, ...BeamHueMode.values]) { + for (final effect in BeamEffect.values) { + final config = _resolve( + effect: effect, + palette: colors.resolve(), + style: BeamStyle(hueMode: mode), + ); + expect( + config.hueMode, + BeamHueMode.none, + reason: '$colors / $mode / ${effect.name}', + ); + } + } + } }); - test('two contours with the same key resolve equal', () { - BeamShape shaped(String key) => _shape.copyWith( - contour: BeamPathContour((rect) => Path()..addOval(rect), key: key), - ); - expect(_resolve(shape: shaped('oval')), _resolve(shape: shaped('oval'))); - expect( - _resolve(shape: shaped('oval')), - isNot(_resolve(shape: shaped('notch'))), - ); + test('a drifting palette keeps the requested mode', () { + for (final mode in BeamHueMode.values) { + expect(_resolve(style: BeamStyle(hueMode: mode)).hueMode, mode); + } }); - test('speed is not part of the painted value', () { - expect( - _resolve(timing: _timing.copyWith(speed: 4)), - _resolve(), - reason: 'the clock owns the rate; the painter never reads it', + test('hueShift and hueBase pass through', () { + final config = _resolve( + style: const BeamStyle(hueShift: 12, hueBase: -40), ); + expect(config.hueShift, 12); + expect(config.hueBase, -40); + expect(_resolve().hueShift, greaterThan(0)); + expect(_resolve().hueBase, 0); }); }); - group('defaults', () { - BeamConfig bare(BeamVariant variant) => BeamConfig.resolve( - variant: variant, - palette: BeamColors.colorful.resolve(), - brightness: Brightness.dark, + group('defaults and pass-through', () { + test( + 'an empty style, shape and timing resolve to the documented defaults', + () { + final c = _resolve(); + expect(c.strength, 1); + expect(c.glow, 1); + expect(c.borderWidth, 1); + expect(c.ringOffset, 0); + expect(c.superellipse, isFalse); + expect(c.segment, isNull); + expect(c.dashes, 0); + expect(c.direction, BeamDirection.forward); + expect(c.phaseOffset, 0); + }, ); - test('the hue mode follows the variant family', () { - for (final variant in BeamVariant.values) { - expect( - bare(variant).hueMode, - variant.isPulse ? BeamHueMode.continuous : BeamHueMode.pingPong, - reason: '$variant', - ); - } + test('set fields pass through unchanged', () { + final c = _resolve( + style: const BeamStyle(strength: 0.4, glow: 2.5), + shape: const BeamShape( + superellipse: true, + borderWidth: 3, + ringOffset: -6, + segment: BeamSegment.bottomEdge, + dashes: 12, + ), + timing: const BeamTiming( + direction: BeamDirection.bounce, + phaseOffset: 0.3, + ), + ); + expect(c.strength, 0.4); + expect(c.glow, 2.5); + expect(c.superellipse, isTrue); + expect(c.borderWidth, 3); + expect(c.ringOffset, -6); + expect(c.segment, BeamSegment.bottomEdge); + expect(c.dashes, 12); + expect(c.direction, BeamDirection.bounce); + expect(c.phaseOffset, 0.3); }); - test('an explicit hue mode overrides the family default', () { - expect( - BeamConfig.resolve( - variant: BeamVariant.rotate, - palette: BeamColors.colorful.resolve(), - brightness: Brightness.dark, - style: const BeamStyle(hueMode: BeamHueMode.continuous), - ).hueMode, - BeamHueMode.continuous, - ); + test('the palette is carried as given', () { + final palette = BeamColors.ocean.resolve(); + expect(identical(_resolve(palette: palette).palette, palette), isTrue); }); - test('the hue periods come from the variant accessors', () { - for (final variant in BeamVariant.values) { - final config = bare(variant); - expect( - config.huePeriodSeconds, - variant.defaultHuePeriod.inMicroseconds / - Duration.microsecondsPerSecond, - reason: '$variant', - ); - expect( - config.bloomHuePeriodSeconds, - variant.defaultBloomHuePeriod.inMicroseconds / - Duration.microsecondsPerSecond, - reason: '$variant', - ); - } + test('isDark follows the brightness', () { + expect(_resolve().isDark, isTrue); + expect(_resolve(brightness: Brightness.light).isDark, isFalse); }); + }); - test('every new field resolves to a render-neutral default', () { - for (final variant in BeamVariant.values) { - final config = bare(variant); - expect(config.tailLength, 1, reason: '$variant'); - expect(config.glowSpread, 1, reason: '$variant'); - expect(config.comet, isFalse, reason: '$variant'); - expect(config.sparkle, 0, reason: '$variant'); - expect(config.segments, isNull, reason: '$variant'); - expect(config.edge, BeamEdge.bottom, reason: '$variant'); - expect(config.ringOffset, 0, reason: '$variant'); - expect(config.contour, isNull, reason: '$variant'); - expect(config.segment, isNull, reason: '$variant'); - expect(config.wrapCorners, isFalse, reason: '$variant'); - expect(config.direction, BeamDirection.forward, reason: '$variant'); - expect(config.phaseOffset, 0, reason: '$variant'); - expect(config.beamCount, 1, reason: '$variant'); - expect(config.innerSizeScale, 1, reason: '$variant'); - expect(config.renderScale, 1, reason: '$variant'); - expect( - config.pulseOutsideTuning, - BeamPulseOutsideTuning.demo, - reason: '$variant', - ); - } + group('clamping', () { + test('strength is clamped to 0–1', () { + expect(_resolve(style: const BeamStyle(strength: 1.7)).strength, 1); + expect(_resolve(style: const BeamStyle(strength: -0.5)).strength, 0); + expect(_resolve(style: const BeamStyle(strength: 0)).strength, 0); }); - test('renderScale is clamped to the 0.25-1 window', () { - BeamConfig withScale(double scale) => BeamConfig.resolve( - variant: BeamVariant.rotate, - palette: BeamColors.colorful.resolve(), - brightness: Brightness.dark, - style: BeamStyle(renderScale: scale), - ); - expect(withScale(0).renderScale, 0.25); - expect(withScale(0.5).renderScale, 0.5); - expect(withScale(3).renderScale, 1); + test('glow 0 is kept — a bare stroke', () { + expect(_resolve(style: const BeamStyle(glow: 0)).glow, 0); }); - test('sparkle is clamped to 0-1', () { - BeamConfig withSparkle(double sparkle) => BeamConfig.resolve( - variant: BeamVariant.rotate, - palette: BeamColors.colorful.resolve(), - brightness: Brightness.dark, - style: BeamStyle(sparkle: sparkle), + test('a negative border width becomes 0', () { + expect(_resolve(shape: const BeamShape(borderWidth: -2)).borderWidth, 0); + }); + + test('a negative gap becomes 0', () { + final c = _resolve( + timing: const BeamTiming(cycleGap: Duration(milliseconds: -400)), ); - expect(withSparkle(-1).sparkle, 0); - expect(withSparkle(2).sparkle, 1); - expect(withSparkle(0.5).sparkle, 0.5); + expect(c.gapSeconds, 0); }); - test('scaledBy scales segment feather with other geometry lengths', () { - final config = _resolve( - shape: const BeamShape( - ringOffset: 6, - segment: BeamSegment( - start: BeamAnchor.topCenter, - end: BeamAnchor.bottomCenter, - feather: 20, - ), - wrapCorners: true, + test('a vanishing cycle or hue period is floored above zero', () { + final c = _resolve( + timing: const BeamTiming( + cycle: Duration(microseconds: 1), + huePeriod: Duration(microseconds: 1), ), ); - final scaled = config.scaledBy(0.5); - expect(scaled.ringOffset, 3); - expect(scaled.segment?.feather, 10); - expect(scaled.segment?.start, BeamAnchor.topCenter); - expect(scaled.wrapCorners, isTrue); + expect(c.cycleSeconds, greaterThan(1e-6)); + expect(c.huePeriodSeconds, greaterThan(1e-6)); + // The floor is a floor, not a replacement: an ordinary cycle is kept. + expect( + _resolve(timing: const BeamTiming(cycle: Duration(milliseconds: 250))) + .cycleSeconds, + closeTo(0.25, 1e-12), + ); }); }); - group('BeamPainter.shouldRepaint', () { - late BeamClock clock; - - setUp(() { - clock = BeamClock(createTicker: Ticker.new); - }); - tearDown(() => clock.dispose()); - - BeamPainter painter(BeamConfig config, {bool staticMode = false}) => - BeamPainter( - clock: clock, - config: config, - resolver: BeamPhaseResolver(config), - strategy: strategyFor(config.variant), - behind: false, - staticMode: staticMode, + group('radius', () { + test('defaults to 16 on every corner', () { + for (final dir in TextDirection.values) { + expect( + _resolve(textDirection: dir).borderRadius, + const BorderRadius.all(Radius.circular(16)), ); - - test('is false for an equal config', () { - final a = painter(_resolve()); - final b = painter(_resolve()); - expect(b.shouldRepaint(a), isFalse); + } }); - test('is true for any differing config', () { - final base = painter(_resolve()); - expect( - painter( - _resolve(style: _style.copyWith(strength: 0.5)), - ).shouldRepaint(base), - isTrue, - ); + test('a uniform radius resolves to itself', () { expect( - painter(_resolve(variant: BeamVariant.line)).shouldRepaint(base), - isTrue, + _resolve(shape: const BeamShape.all(24)).borderRadius, + BorderRadius.circular(24), ); }); - test('is true when the pass, the static mode, or the clock changes', () { - final config = _resolve(); - final base = painter(config); - expect(painter(config, staticMode: true).shouldRepaint(base), isTrue); - - final behind = BeamPainter( - clock: clock, - config: config, - resolver: BeamPhaseResolver(config), - strategy: strategyFor(config.variant), - behind: true, - staticMode: false, - ); - expect(behind.shouldRepaint(base), isTrue); - - final otherClock = BeamClock(createTicker: Ticker.new); - addTearDown(otherClock.dispose); - final rebound = BeamPainter( - clock: otherClock, - config: config, - resolver: BeamPhaseResolver(config), - strategy: strategyFor(config.variant), - behind: false, - staticMode: false, + test('a directional radius resolves for the text direction', () { + const shape = BeamShape( + radius: BorderRadiusDirectional.only(topStart: Radius.circular(10)), ); - expect(rebound.shouldRepaint(base), isTrue); + final ltr = _resolve(shape: shape).borderRadius; + final rtl = _resolve( + shape: shape, + textDirection: TextDirection.rtl, + ).borderRadius; + expect(ltr.topLeft, const Radius.circular(10)); + expect(ltr.topRight, Radius.zero); + expect(rtl.topRight, const Radius.circular(10)); + expect(rtl.topLeft, Radius.zero); + expect(ltr, isNot(rtl)); }); }); - group("the widget's config cache", () { - testWidgets('an equal style rebuilt inline keeps the same config object', ( - tester, - ) async { - // A runtime value, so each build allocates a fresh BeamStyle rather - // than reusing a canonicalized const one. - Widget build(double strength) => _host( - BorderBeam.rotate( - style: BeamStyle(strength: strength), - child: const SizedBox.expand(), - ), - ); + group('beamCount', () { + test('rotate carries its count', () { + for (var n = 1; n <= 4; n++) { + expect(_resolve(effect: BeamEffect.rotate(count: n)).beamCount, n); + } + }); - await tester.pumpWidget(build(0.5)); - final first = _beamPainter(tester).config; + test('every other effect is a single beam', () { + for (final effect in BeamEffect.values.where((e) => e is! RotateEffect)) { + expect(_resolve(effect: effect).beamCount, 1, reason: effect.name); + } + }); + }); - await tester.pumpWidget(build(0.5)); - expect( - identical(_beamPainter(tester).config, first), - isTrue, - reason: 'equal value objects must not re-resolve', + group('equality', () { + test('two resolutions of the same inputs are equal', () { + final a = _resolve( + style: BeamStyle(strength: double.parse('0.5')), + shape: BeamShape.circular(20), ); + final b = _resolve( + style: BeamStyle(strength: double.parse('0.5')), + shape: BeamShape.circular(20), + ); + expect(identical(a, b), isFalse); + expect(a, b); + expect(a.hashCode, b.hashCode); }); - testWidgets('a differing style resolves a new config object', ( - tester, - ) async { - Widget build(double strength) => _host( - BorderBeam.rotate( - style: BeamStyle(strength: strength), - child: const SizedBox.expand(), - ), - ); + // Every input that reaches a painted value, one at a time. + final mutations = { + 'effect': () => _resolve(effect: const BeamEffect.line()), + 'effect parameter': () => + _resolve(effect: const BeamEffect.rotate(comet: true)), + 'palette': () => _resolve(palette: BeamColors.ocean.resolve()), + 'brightness': () => _resolve(brightness: Brightness.light), + 'strength': () => _resolve(style: const BeamStyle(strength: 0.8)), + 'glow': () => _resolve(style: const BeamStyle(glow: 2)), + 'hueMode': () => + _resolve(style: const BeamStyle(hueMode: BeamHueMode.none)), + 'hueShift': () => _resolve(style: const BeamStyle(hueShift: 7)), + 'hueBase': () => _resolve(style: const BeamStyle(hueBase: 7)), + 'radius': () => _resolve(shape: const BeamShape.all(4)), + 'superellipse': () => + _resolve(shape: const BeamShape(superellipse: true)), + 'borderWidth': () => _resolve(shape: const BeamShape(borderWidth: 2)), + 'ringOffset': () => _resolve(shape: const BeamShape(ringOffset: 2)), + 'segment': () => + _resolve(shape: const BeamShape(segment: BeamSegment.topHalf)), + 'dashes': () => _resolve(shape: const BeamShape(dashes: 3)), + 'cycle': () => + _resolve(timing: const BeamTiming(cycle: Duration(seconds: 9))), + 'cycleGap': () => + _resolve(timing: const BeamTiming(cycleGap: Duration(seconds: 1))), + 'direction': () => + _resolve(timing: const BeamTiming(direction: BeamDirection.reverse)), + 'phaseOffset': () => _resolve(timing: const BeamTiming(phaseOffset: 0.5)), + 'huePeriod': () => + _resolve(timing: const BeamTiming(huePeriod: Duration(seconds: 2))), + }; - await tester.pumpWidget(build(0.5)); - final first = _beamPainter(tester).config; + for (final MapEntry(key: name, value: build) in mutations.entries) { + test('$name breaks equality', () { + // Only equality: unequal configs may share a hash code. + expect(build(), isNot(_resolve())); + }); + } - await tester.pumpWidget(build(0.6)); - final second = _beamPainter(tester).config; - expect(identical(second, first), isFalse); - expect(second, isNot(first)); - expect(second.strength, 0.6); + test('the mutations differ from each other too', () { + final configs = [for (final build in mutations.values) build()]; + expect(configs.toSet(), hasLength(configs.length)); }); - testWidgets('an equal shape and timing rebuilt inline keep the config', ( - tester, - ) async { - Widget build(double radius, int cycleMs) => _host( - BorderBeam.rotate( - shape: BeamShape.circular(radius, superellipse: true), - timing: BeamTiming( - cycle: Duration(milliseconds: cycleMs), - cycleGap: const Duration(milliseconds: 400), - ), - child: const SizedBox.expand(), - ), + test('text direction only matters for a directional radius', () { + expect(_resolve(textDirection: TextDirection.rtl), _resolve()); + const shape = BeamShape( + radius: BorderRadiusDirectional.only(topStart: Radius.circular(10)), + ); + expect( + _resolve(shape: shape, textDirection: TextDirection.rtl), + isNot(_resolve(shape: shape)), ); + }); - await tester.pumpWidget(build(24, 1500)); - final first = _beamPainter(tester).config; - await tester.pumpWidget(build(24, 1500)); - expect(identical(_beamPainter(tester).config, first), isTrue); + test('speed is not part of the painted value', () { + expect(_resolve(timing: const BeamTiming(speed: 3)), _resolve()); }); - testWidgets('an unrelated rebuild keeps the config and the resolver', ( - tester, - ) async { - Widget build(String label) => _host( - BorderBeam.rotate(colors: BeamColors.ocean, child: Text(label)), + test('an equal but separately resolved palette keeps equality', () { + final a = _resolve( + palette: BeamColors([ + const Color(0xFF102030), + Color(int.parse('0xFF405060')), + ]).resolve(), ); - - await tester.pumpWidget(build('a')); - final painter = _beamPainter(tester); - - await tester.pumpWidget(build('b')); - final next = _beamPainter(tester); - expect(identical(next.config, painter.config), isTrue); - expect(identical(next.resolver, painter.resolver), isTrue); - expect(next.shouldRepaint(painter), isFalse); + final b = _resolve( + palette: BeamPalette( + colors: const [Color(0xFF102030), Color(0xFF405060)], + stops: BeamPalette.evenStops(2), + ), + ); + expect(a, b); }); }); } diff --git a/test/models/beam_effect_test.dart b/test/models/beam_effect_test.dart new file mode 100644 index 0000000..1094ceb --- /dev/null +++ b/test/models/beam_effect_test.dart @@ -0,0 +1,202 @@ +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// `BeamEffect` is the sealed "what the beam does" value: three effects in +/// two families, each carrying its own defaults, and the parameterised ones +/// compare by value so a rebuilt-inline effect never re-resolves a config. +void main() { + const travelling = {'rotate', 'line'}; + const ambient = {'pulse'}; + + group('values', () { + test('lists all three effects in gallery order', () { + expect(BeamEffect.values.map((e) => e.name), ['rotate', 'line', 'pulse']); + }); + + test('every entry is a distinct effect with a distinct name', () { + expect(BeamEffect.values.map((e) => e.name).toSet(), hasLength(3)); + expect(BeamEffect.values.map((e) => e.runtimeType).toSet(), hasLength(3)); + expect(BeamEffect.values.toSet(), hasLength(3)); + }); + + test('carries each effect with its default parameters', () { + expect(BeamEffect.values, contains(const BeamEffect.rotate())); + expect(BeamEffect.values, contains(const BeamEffect.line())); + expect(BeamEffect.values, contains(const BeamEffect.pulse())); + }); + }); + + group('families', () { + for (final effect in BeamEffect.values) { + test('${effect.name} travels: ${travelling.contains(effect.name)}', () { + expect(effect.travels, travelling.contains(effect.name)); + expect(effect.travels, isNot(ambient.contains(effect.name))); + }); + } + + test('the two families partition the effects', () { + expect( + BeamEffect.values.where((e) => e.travels).map((e) => e.name).toSet(), + travelling, + ); + expect( + BeamEffect.values.where((e) => !e.travels).map((e) => e.name).toSet(), + ambient, + ); + }); + + test('parameters do not change the family', () { + expect(const BeamEffect.rotate(count: 3, comet: true).travels, isTrue); + expect(const BeamEffect.line(edge: BeamEdge.top).travels, isTrue); + }); + }); + + group('defaults', () { + for (final effect in BeamEffect.values) { + test('${effect.name}: cycle and hue period are positive', () { + expect(effect.defaultCycle, greaterThan(Duration.zero)); + expect(effect.defaultHuePeriod, greaterThan(Duration.zero)); + expect(effect.defaultCycleGap, greaterThanOrEqualTo(Duration.zero)); + }); + } + + // `BeamHueMode`'s docs name these; a change here belongs there too. + test('rotate and line ping-pong their hue; pulse revolves it', () { + expect(const BeamEffect.rotate().defaultHueMode, BeamHueMode.pingPong); + expect(const BeamEffect.line().defaultHueMode, BeamHueMode.pingPong); + expect(const BeamEffect.pulse().defaultHueMode, BeamHueMode.continuous); + }); + + test('no effect rests between sweeps by default', () { + for (final effect in BeamEffect.values) { + expect(effect.defaultCycleGap, Duration.zero, reason: effect.name); + } + }); + + test('parameters do not change the defaults', () { + const a = BeamEffect.rotate(); + const b = BeamEffect.rotate(length: 2, count: 4, comet: true); + expect(b.defaultCycle, a.defaultCycle); + expect(b.defaultCycleGap, a.defaultCycleGap); + expect(b.defaultHueMode, a.defaultHueMode); + expect(b.defaultHuePeriod, a.defaultHuePeriod); + const c = BeamEffect.line(); + const d = BeamEffect.line(edge: BeamEdge.left); + expect(d.defaultCycle, c.defaultCycle); + expect(d.defaultCycleGap, c.defaultCycleGap); + expect(d.defaultHueMode, c.defaultHueMode); + expect(d.defaultHuePeriod, c.defaultHuePeriod); + }); + + test('rotate defaults to one plain beam of unit length', () { + const rotate = RotateEffect(); + expect(rotate.length, 1); + expect(rotate.count, 1); + expect(rotate.comet, isFalse); + }); + + test('line rides the bottom edge by default', () { + expect(const LineEffect().edge, BeamEdge.bottom); + }); + }); + + group('equality', () { + test('equal parameters are equal with equal hash codes', () { + // The right-hand sides are built at run time: two equal const + // expressions are one canonical instance, and `==` would never get + // past `identical`. + final pairs = <(BeamEffect, BeamEffect)>[ + ( + const BeamEffect.rotate(), + RotateEffect(length: double.parse('1'), count: int.parse('1')), + ), + ( + const BeamEffect.rotate(length: 1.5, count: 2, comet: true), + RotateEffect( + length: double.parse('1.5'), + count: int.parse('2'), + comet: bool.parse('true'), + ), + ), + ( + const BeamEffect.line(edge: BeamEdge.left), + LineEffect(edge: BeamEdge.values.byName('left')), + ), + // PulseEffect has no fields: a non-const call is the only way to get + // a second instance. + (const BeamEffect.pulse(), PulseEffect()), + ]; + for (final (a, b) in pairs) { + expect(identical(a, b), isFalse, reason: '$a: two instances'); + expect(a, b); + expect(a.hashCode, b.hashCode, reason: '$a'); + } + }); + + test('every parameter is part of the value', () { + const base = BeamEffect.rotate(); + for (final other in const [ + BeamEffect.rotate(length: 2), + BeamEffect.rotate(count: 2), + BeamEffect.rotate(comet: true), + ]) { + // Only equality: unequal values may share a hash code. + expect(other, isNot(base), reason: '$other'); + } + expect( + const BeamEffect.line(edge: BeamEdge.top), + isNot(const BeamEffect.line()), + ); + }); + + test('different effects are never equal', () { + final effects = BeamEffect.values; + for (var i = 0; i < effects.length; i++) { + for (var j = 0; j < effects.length; j++) { + if (i == j) continue; + expect(effects[i], isNot(effects[j])); + } + } + }); + }); + + group('toString', () { + test('names the effect and its parameters', () { + expect( + const BeamEffect.rotate(length: 1.5, count: 2, comet: true).toString(), + 'BeamEffect.rotate(length: 1.5, count: 2, comet: true)', + ); + expect( + const BeamEffect.line(edge: BeamEdge.top).toString(), + 'BeamEffect.line(edge: top)', + ); + }); + + test('a parameterless effect prints empty parentheses', () { + expect(const BeamEffect.pulse().toString(), 'BeamEffect.pulse()'); + }); + }); + + group('rotate asserts', () { + // Runtime values, so the analyzer cannot fold the constructor into a + // const evaluation and report the failing assert at compile time. + final zero = double.parse('0'); + final negative = double.parse('-1'); + + test('rejects a non-positive length', () { + expect(() => RotateEffect(length: zero), throwsAssertionError); + expect(() => RotateEffect(length: negative), throwsAssertionError); + }); + + test('rejects a count outside 1–4', () { + expect(() => RotateEffect(count: int.parse('0')), throwsAssertionError); + expect(() => RotateEffect(count: int.parse('5')), throwsAssertionError); + }); + + test('accepts the whole 1–4 count range', () { + for (var count = 1; count <= 4; count++) { + expect(RotateEffect(count: count).count, count); + } + }); + }); +} diff --git a/test/models/beam_palette_test.dart b/test/models/beam_palette_test.dart index 26e0273..63331e9 100644 --- a/test/models/beam_palette_test.dart +++ b/test/models/beam_palette_test.dart @@ -1,282 +1,173 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_border_beam/src/constants/palettes.dart'; -import 'package:flutter_border_beam/src/models/beam_blob.dart'; -import 'package:flutter_border_beam/src/models/beam_colors.dart'; +import 'dart:ui'; + +import 'package:flutter/foundation.dart' show describeIdentity; +import 'package:flutter_border_beam/src/look/palette_tables.dart'; import 'package:flutter_border_beam/src/models/beam_palette.dart'; +import 'package:flutter_border_beam/src/render/color_math.dart'; import 'package:flutter_test/flutter_test.dart'; -/// Builds a palette that differs from [colorfulPreset] only in the field the -/// caller replaces, so each equality test isolates one table. -BeamPresetData _presetWith({ - List? border, - SpikeColors? spike, - SpikeColors? spikeLt, - List? smallBorder, - List? smallInner, - List? lineDark, - List? lineLight, - List? lineInner, - List? lineBloomDark, - List? lineBloomLight, -}) => BeamPresetData( - border: border ?? colorfulPreset.border, - spike: spike ?? colorfulPreset.spike, - spikeLt: spikeLt ?? colorfulPreset.spikeLt, - smallBorder: smallBorder ?? colorfulPreset.smallBorder, - smallInner: smallInner ?? colorfulPreset.smallInner, - lineDark: lineDark ?? colorfulPreset.lineDark, - lineLight: lineLight ?? colorfulPreset.lineLight, - lineInner: lineInner ?? colorfulPreset.lineInner, - lineBloomDark: lineBloomDark ?? colorfulPreset.lineBloomDark, - lineBloomLight: lineBloomLight ?? colorfulPreset.lineBloomLight, -); +const Color _red = Color(0xFFFF0000); +const Color _green = Color(0xFF00FF00); +const Color _blue = Color(0xFF0000FF); -/// A copy of a blob list with one entry recolored — enough to break equality. -List _recolored(List source) => [ - source.first.withColor(const Color(0xFF010203)), - ...source.skip(1), -]; +void _expectColor(Color actual, Color expected, {String? reason}) { + expect(actual.a, closeTo(expected.a, 1e-9), reason: reason); + expect(actual.r, closeTo(expected.r, 1e-9), reason: reason); + expect(actual.g, closeTo(expected.g, 1e-9), reason: reason); + expect(actual.b, closeTo(expected.b, 1e-9), reason: reason); +} +/// [BeamPalette] is the resolved ring of colour stops the shader shades by; +/// its `sample` is the CPU mirror of the shader's palette lookup. void main() { - group('BeamPresetData equality', () { - test('a field-by-field copy of a preset is ==', () { - final copy = _presetWith(); - expect(copy, colorfulPreset); - expect(copy.hashCode, colorfulPreset.hashCode); - }); - - test('a rebuilt table with equal values is ==', () { - // A fresh list of fresh blobs: nothing here is identical to the preset. - final rebuilt = _presetWith( - border: [for (final b in colorfulPreset.border) b.withColor(b.color)], - ); - expect(identical(rebuilt.border, colorfulPreset.border), isFalse); - expect(rebuilt, colorfulPreset); - expect(rebuilt.hashCode, colorfulPreset.hashCode); + const palette = BeamPalette( + colors: [_red, _green, _blue], + stops: [0.1, 0.4, 0.7], + ); + + group('sample', () { + test('returns each stop colour at its stop', () { + for (var i = 0; i < palette.length; i++) { + _expectColor( + palette.sample(palette.stops[i]), + palette.colors[i], + reason: 'stop $i', + ); + } }); - test('every table participates', () { - final variants = { - 'border': _presetWith(border: _recolored(colorfulPreset.border)), - 'spike': _presetWith( - spike: const SpikeColors( - primary: Color(0xFF010203), - secondary: Color(0xFF040506), - ), - ), - 'spikeLt': _presetWith( - spikeLt: const SpikeColors( - primary: Color(0xFF010203), - secondary: Color(0xFF040506), - ), - ), - 'smallBorder': _presetWith( - smallBorder: _recolored(colorfulPreset.smallBorder), - ), - 'smallInner': _presetWith( - smallInner: _recolored(colorfulPreset.smallInner), - ), - 'lineDark': _presetWith( - lineDark: [ - colorfulPreset.lineDark.first.withColor(const Color(0xFF010203)), - ...colorfulPreset.lineDark.skip(1), - ], - ), - 'lineLight': _presetWith( - lineLight: [ - colorfulPreset.lineLight.first.withColor(const Color(0xFF010203)), - ...colorfulPreset.lineLight.skip(1), - ], - ), - 'lineInner': _presetWith( - lineInner: [ - colorfulPreset.lineInner.first.withColor(const Color(0xFF010203)), - ...colorfulPreset.lineInner.skip(1), - ], - ), - 'lineBloomDark': _presetWith( - lineBloomDark: [ - const SpikePair(Color(0xFF010203), Color(0xFF040506)), - ...colorfulPreset.lineBloomDark.skip(1), - ], - ), - 'lineBloomLight': _presetWith( - lineBloomLight: [ - const SpikePair(Color(0xFF010203), Color(0xFF040506)), - ...colorfulPreset.lineBloomLight.skip(1), - ], - ), - }; - for (final MapEntry(key: field, value: data) in variants.entries) { - expect(data, isNot(colorfulPreset), reason: '$field ignored by =='); + test('matches samplePalette everywhere in [0, 1)', () { + for (var i = 0; i < 200; i++) { + final u = i / 200; + expect( + palette.sample(u), + samplePalette(palette.colors, palette.stops, u, wrap: true), + reason: 'u = $u', + ); } - // Each variant differs from every other, not just from the preset. - expect(variants.values.toSet(), hasLength(variants.length)); }); - test('a table of different length is not equal', () { - expect( - _presetWith(border: colorfulPreset.border.take(8).toList()), - isNot(colorfulPreset), - ); + test('wraps any coordinate into the ring', () { + for (final u in [0.05, 0.3, 0.55, 0.85]) { + for (final turns in [-2, -1, 1, 3]) { + _expectColor( + palette.sample(u + turns), + palette.sample(u), + reason: 'u = $u, turns = $turns', + ); + } + } + _expectColor(palette.sample(1), palette.sample(0)); }); - test('the presets differ from one another', () { - expect({ - colorfulPreset, - monoPreset, - oceanPreset, - sunsetPreset, - }, hasLength(4)); + test('blends the last stop back into the first across top-centre', () { + // Halfway between the last stop (0.7) and the first (0.1 + 1). + _expectColor(palette.sample(0.9), mixColor(_blue, _red, 0.5)); + // Top-centre sits on that same blend, three quarters of the way across. + _expectColor(palette.sample(0), mixColor(_blue, _red, 0.75)); }); - }); - group('BeamPalette equality', () { - test('compares tables and every paint-time modifier', () { - const a = BeamPalette(data: colorfulPreset); - const b = BeamPalette(data: colorfulPreset); - expect(a, b); - expect(a.hashCode, b.hashCode); - expect( - a, - isNot( - const BeamPalette(data: colorfulPreset, forcesStaticColors: true), - ), - ); - expect( - a, - isNot(const BeamPalette(data: colorfulPreset, opacityMultiplier: 0.5)), - ); - expect( - a, - isNot(const BeamPalette(data: colorfulPreset, monoTreatment: true)), - ); - expect(a, isNot(const BeamPalette(data: oceanPreset))); - expect(a.toString(), contains('BeamPalette')); + test('blends neighbouring stops in between', () { + _expectColor(palette.sample(0.25), mixColor(_red, _green, 0.5)); + final mid = palette.sample(0.55); + expect(mid.g, greaterThan(0)); + expect(mid.b, greaterThan(0)); + expect(mid.r, closeTo(0, 1e-9)); }); - test('a palette rebuilt from equal tables is ==', () { - final rebuilt = BeamPalette(data: _presetWith()); - expect(rebuilt, const BeamPalette(data: colorfulPreset)); - expect( - rebuilt.hashCode, - const BeamPalette(data: colorfulPreset).hashCode, - ); + test('a single stop is that colour all the way round', () { + const solid = BeamPalette(colors: [_green], stops: [0.3]); + for (final u in [0.0, 0.3, 0.6, 0.99, 1.5]) { + expect(solid.sample(u), _green); + } }); }); - group('the resolve memo', () { - test('equal color choices resolve to the identical palette', () { - // Two separately built — never identical — but equal instances. - final a = BeamColors.custom([ - const Color(0xFF123456), - const Color(0xFF654321), - ]); - final b = BeamColors.custom([ - const Color(0xFF123456), - const Color(0xFF654321), - ]); - expect(identical(a, b), isFalse); - expect(identical(a.resolve(), b.resolve()), isTrue); + group('evenStops', () { + test('spaces n stops evenly from zero', () { + for (var n = 1; n <= maxPaletteStops; n++) { + final stops = BeamPalette.evenStops(n); + expect(stops, hasLength(n)); + expect(stops.first, 0); + for (var i = 0; i < n; i++) { + expect(stops[i], closeTo(i / n, 1e-12)); + expect(stops[i], lessThan(1)); + } + } }); - test('every factory shares the memo', () { - expect( - identical( - BeamColors.fromSeed(const Color(0xFF18A8F0)).resolve(), - BeamColors.fromSeed(const Color(0xFF18A8F0)).resolve(), - ), - isTrue, - ); - expect( - identical( - BeamColors.lerp(BeamColors.ocean, BeamColors.sunset, 0.5).resolve(), - BeamColors.lerp(BeamColors.ocean, BeamColors.sunset, 0.5).resolve(), - ), - isTrue, - ); - expect( - identical( - BeamColors.ocean.scaleAlpha(0.5).resolve(), - BeamColors.ocean.scaleAlpha(0.5).resolve(), - ), - isTrue, - ); - expect( - identical( - BeamColors.fromScheme(_scheme).resolve(), - BeamColors.fromScheme(_scheme).resolve(), - ), - isTrue, - ); + test('is unmodifiable', () { + expect(() => BeamPalette.evenStops(3).add(0.9), throwsUnsupportedError); }); + }); - test('unequal color choices resolve to different palettes', () { - final a = BeamColors.custom(const [Color(0xFF123456)]); - final b = BeamColors.custom(const [Color(0xFF654321)]); - expect(identical(a.resolve(), b.resolve()), isFalse); - expect(a.resolve(), isNot(b.resolve())); - expect( - identical( - const BeamColors.fromSeed( - Color(0xFF18A8F0), - harmony: BeamSeedHarmony.triadic, - ).resolve(), - const BeamColors.fromSeed(Color(0xFF18A8F0)).resolve(), - ), - isFalse, + group('equality', () { + test('compares colours, stops, and fixedHue by value', () { + final rebuilt = BeamPalette( + colors: List.of(palette.colors), + stops: List.of(palette.stops), ); - }); + expect(rebuilt, palette); + expect(rebuilt.hashCode, palette.hashCode); - test('presets keep one palette for the life of the isolate', () { - final ocean = BeamColors.ocean.resolve(); - // Flood the value cache well past its bound; a preset must survive it. - for (var i = 0; i < 200; i++) { - BeamColors.custom([Color(0xFF000000 | i)]).resolve(); + for (final other in [ + const BeamPalette( + colors: [_red, _green, _blue], + stops: [0.1, 0.4, 0.8], + ), + const BeamPalette(colors: [_red, _blue, _blue], stops: [0.1, 0.4, 0.7]), + const BeamPalette( + colors: [_red, _green, _blue], + stops: [0.1, 0.4, 0.7], + fixedHue: true, + ), + const BeamPalette(colors: [_red, _green], stops: [0.1, 0.4]), + ]) { + expect(other, isNot(palette), reason: '$other'); } - expect(identical(BeamColors.ocean.resolve(), ocean), isTrue); }); - test('the value cache is bounded and evicts least-recently-used first', () { - // Distinct from every other key used in this file. - BeamColors key(int i) => BeamColors.custom([Color(0xFF7F0000 | i)]); + test('length counts the stops', () { + expect(palette.length, 3); + expect(const BeamPalette(colors: [_red], stops: [0]).length, 1); + }); - final oldest = key(0); - final oldestPalette = oldest.resolve(); - final newest = key(32); - // 32 further distinct palettes: the capacity, so `oldest` — never - // touched again — falls off the front. - for (var i = 1; i <= 32; i++) { - key(i).resolve(); - } - expect( - identical(oldest.resolve(), oldestPalette), - isFalse, - reason: 'the least recently used entry should have been evicted', + test('toString names every field', () { + final s = palette.toString(); + expect(s, startsWith('BeamPalette(')); + expect(s, contains('colors: ${palette.colors}')); + expect(s, contains('stops: [0.1, 0.4, 0.7]')); + expect(s, contains('fixedHue: false')); + expect(s, contains('mono: false')); + // Unset tables are left out, as an unset value-object field is. + expect(s, isNot(contains('tables'))); + + const drawn = BeamPalette( + colors: [_red], + stops: [0], + tables: colorfulTables, + tableColors: [_green, _blue], + mono: true, ); - // An evicted palette rebuilds to an equal one, so nothing observable - // changes for a painter comparing configs. - expect(oldest.resolve(), oldestPalette); - // The most recent insert is still cached. - expect(identical(newest.resolve(), key(32).resolve()), isTrue); + final d = drawn.toString(); + expect(d, contains('mono: true')); + expect(d, contains('tables: ${describeIdentity(colorfulTables)}')); + expect(d, contains('tableColors: [$_green, $_blue]')); }); - test('a hit refreshes the entry, so a re-read survives eviction', () { - BeamColors key(int i) => BeamColors.custom([Color(0xFF3F0000 | i)]); - final kept = key(0); - final keptPalette = kept.resolve(); - for (var i = 1; i <= 24; i++) { - key(i).resolve(); - // Touching `kept` moves it back to the most-recent end. - kept.resolve(); - } - expect(identical(kept.resolve(), keptPalette), isTrue); + test('toString tells apart palettes that paint differently', () { + // Equal colours and stops, each drawn another way: every one of these + // compares unequal, so none may print the same. + const plain = BeamPalette(colors: [_red], stops: [0]); + final variants = [ + plain, + const BeamPalette(colors: [_red], stops: [0], mono: true), + const BeamPalette(colors: [_red], stops: [0], tables: colorfulTables), + const BeamPalette(colors: [_red], stops: [0], tables: monoTables), + const BeamPalette(colors: [_red], stops: [0], tableColors: [_blue]), + ]; + final printed = {for (final p in variants) p.toString()}; + expect(printed, hasLength(variants.length)); }); }); } - -const ColorScheme _scheme = ColorScheme.dark( - primary: Color(0xFFFF0000), - secondary: Color(0xFF00FF00), - tertiary: Color(0xFF0000FF), -); diff --git a/test/models/beam_segment_test.dart b/test/models/beam_segment_test.dart index 5b4433b..319ad99 100644 --- a/test/models/beam_segment_test.dart +++ b/test/models/beam_segment_test.dart @@ -1,85 +1,300 @@ +import 'dart:math' as math; + import 'package:flutter/painting.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam/src/painting/ring_geometry.dart'; +import 'package:flutter_border_beam/src/render/beam_outline.dart'; import 'package:flutter_test/flutter_test.dart'; +/// Distance between two perimeter coordinates around the ring. +double _ringDistance(double a, double b) => ((a - b + 0.5) % 1 - 0.5).abs(); + +/// [BeamAnchor]s and [BeamSegment]s resolve to perimeter coordinates on a +/// [BeamOutline]: `u` in `[0, 1)`, 0 at top-centre, clockwise by arc length. void main() { - final perimeter = BeamPerimeter( - Path()..addRect(const Rect.fromLTWH(0, 0, 100, 100)), - const Rect.fromLTWH(0, 0, 100, 100), - radii: BorderRadius.zero, - ); - - test('anchors and segments compare by value', () { - expect(const BeamAnchor.fraction(0.25), const BeamAnchor.fraction(0.25)); - expect( - const BeamAnchor.edge(BeamEdge.right), - const BeamAnchor.edge(BeamEdge.right, 0.5), - ); - expect( - const BeamSegment( - start: BeamAnchor.topCenter, - end: BeamAnchor.bottomCenter, + const rect = Rect.fromLTWH(0, 0, 200, 100); + const radius = 12.0; + + for (final superellipse in [false, true]) { + group(superellipse ? 'superellipse outline' : 'circular outline', () { + final outline = BeamOutline( + rect, + BorderRadius.circular(radius), + superellipse: superellipse, + ); + // How far the corner curve reaches along each edge. + final corner = outline.cornerSizes.first; + + void expectAt(BeamAnchor anchor, Offset point, {String? reason}) { + final u = anchor.resolve(outline); + expect(u, inInclusiveRange(0, 1), reason: reason ?? '$anchor'); + expect(u, lessThan(1), reason: reason ?? '$anchor'); + final p = outline.pointAt(u); + expect(p.dx, closeTo(point.dx, 1e-3), reason: reason ?? '$anchor'); + expect(p.dy, closeTo(point.dy, 1e-3), reason: reason ?? '$anchor'); + } + + test('the named anchors sit at the centre of each side', () { + expectAt(BeamAnchor.topCenter, rect.topCenter); + expectAt(BeamAnchor.rightCenter, rect.centerRight); + expectAt(BeamAnchor.bottomCenter, rect.bottomCenter); + expectAt(BeamAnchor.leftCenter, rect.centerLeft); + }); + + test('edge centres run clockwise from top-centre', () { + final top = BeamAnchor.topCenter.resolve(outline); + final right = BeamAnchor.rightCenter.resolve(outline); + final bottom = BeamAnchor.bottomCenter.resolve(outline); + final left = BeamAnchor.leftCenter.resolve(outline); + expect(_ringDistance(top, 0), lessThan(1e-6)); + expect(right, greaterThan(0)); + expect(right, lessThan(bottom)); + expect(bottom, closeTo(0.5, 1e-6), reason: 'a symmetric box'); + expect(left, greaterThan(bottom)); + expect(left, lessThan(1)); + }); + + test('edge anchors travel clockwise along the straight run', () { + // Top: left to right. + expectAt( + const BeamAnchor.edge(BeamEdge.top, 0), + Offset(rect.left + corner, rect.top), + ); + expectAt( + const BeamAnchor.edge(BeamEdge.top, 1), + Offset(rect.right - corner, rect.top), + ); + // Right: top to bottom. + expectAt( + const BeamAnchor.edge(BeamEdge.right, 0), + Offset(rect.right, rect.top + corner), + ); + // Bottom: right to left. + expectAt( + const BeamAnchor.edge(BeamEdge.bottom, 0), + Offset(rect.right - corner, rect.bottom), + ); + expectAt( + const BeamAnchor.edge(BeamEdge.bottom, 0.25), + Offset(rect.right - corner - (rect.width - 2 * corner) / 4, 100), + ); + // Left: bottom to top. + expectAt( + const BeamAnchor.edge(BeamEdge.left, 1), + Offset(rect.left, rect.top + corner), + ); + }); + + test('corner anchors span the curve between two edges', () { + for (final (c, before, after) in const [ + (BeamCorner.topLeft, BeamEdge.left, BeamEdge.top), + (BeamCorner.topRight, BeamEdge.top, BeamEdge.right), + (BeamCorner.bottomRight, BeamEdge.right, BeamEdge.bottom), + (BeamCorner.bottomLeft, BeamEdge.bottom, BeamEdge.left), + ]) { + final start = BeamAnchor.corner(c, 0).resolve(outline); + final end = BeamAnchor.corner(c, 1).resolve(outline); + final mid = BeamAnchor.corner(c).resolve(outline); + expect( + _ringDistance(start, BeamAnchor.edge(before, 1).resolve(outline)), + lessThan(1e-9), + reason: '$c starts where $before ends', + ); + expect( + _ringDistance(end, BeamAnchor.edge(after, 0).resolve(outline)), + lessThan(1e-9), + reason: '$c ends where $after starts', + ); + // The midpoint is halfway along the arc, clockwise. + expect( + _ringDistance(mid, start), + closeTo(_ringDistance(end, start) / 2, 1e-9), + reason: '$c midpoint', + ); + // And it is off both edges: inside the corner box. + final p = outline.pointAt(mid); + expect( + math.min( + math.min(p.dx - rect.left, rect.right - p.dx), + math.min(p.dy - rect.top, rect.bottom - p.dy), + ), + greaterThan(0.1), + reason: '$c midpoint leaves the straight runs', + ); + } + }); + + test('fraction anchors wrap modulo one', () { + double at(double t) => BeamAnchor.fraction(t).resolve(outline); + expect(at(0.25), closeTo(0.25, 1e-12)); + expect(at(1.25), closeTo(0.25, 1e-12)); + expect(at(-0.25), closeTo(0.75, 1e-12)); + expect(at(1), 0); + expect(at(-3), 0); + }); + + test('edge and corner positions are clamped to their run', () { + // A fraction wraps, but t past an edge's ends stays on that edge. + expect( + const BeamAnchor.edge(BeamEdge.right, 1.5).resolve(outline), + const BeamAnchor.edge(BeamEdge.right, 1).resolve(outline), + ); + expect( + const BeamAnchor.corner(BeamCorner.topLeft, -1).resolve(outline), + const BeamAnchor.corner(BeamCorner.topLeft, 0).resolve(outline), + ); + }); + + test('the half segments run between opposite side centres', () { + final top = BeamAnchor.topCenter.resolve(outline); + final right = BeamAnchor.rightCenter.resolve(outline); + final bottom = BeamAnchor.bottomCenter.resolve(outline); + final left = BeamAnchor.leftCenter.resolve(outline); + + final bottomHalf = BeamSegment.bottomHalf.resolve(outline); + expect(bottomHalf.from, closeTo(right, 1e-12)); + expect(bottomHalf.to, closeTo(left, 1e-12)); + expect(bottomHalf.to, greaterThan(bottomHalf.from)); + + final topHalf = BeamSegment.topHalf.resolve(outline); + expect(topHalf.from, closeTo(left, 1e-12)); + expect(topHalf.to, closeTo(right, 1e-12)); + expect( + topHalf.to, + lessThan(topHalf.from), + reason: 'wraps through top-centre', + ); + + final rightHalf = BeamSegment.rightHalf.resolve(outline); + expect(_ringDistance(rightHalf.from, top), lessThan(1e-6)); + expect(rightHalf.to, closeTo(bottom, 1e-12)); + + final leftHalf = BeamSegment.leftHalf.resolve(outline); + expect(leftHalf.from, closeTo(bottom, 1e-12)); + expect(_ringDistance(leftHalf.to, top), lessThan(1e-6)); + + // On a symmetric box each half is half the perimeter. + for (final s in [bottomHalf, topHalf, rightHalf, leftHalf]) { + expect((s.to - s.from) % 1, closeTo(0.5, 1e-6)); + } + }); + + test('the edge segments cover one straight run and both corners', () { + // One corner curve's share of the perimeter. + final arc = outline.cornerArcs.first / outline.length; + final horizontal = (rect.width - 2 * corner) / outline.length; + final vertical = (rect.height - 2 * corner) / outline.length; + for (final (segment, run) in [ + (BeamSegment.topEdge, horizontal), + (BeamSegment.bottomEdge, horizontal), + (BeamSegment.leftEdge, vertical), + (BeamSegment.rightEdge, vertical), + ]) { + final r = segment.resolve(outline); + expect( + (r.to - r.from) % 1, + closeTo(run + 2 * arc, 1e-6), + reason: '$segment', + ); + } + // The bottom edge contains bottom-centre; the top edge contains 0. + final bottomEdge = BeamSegment.bottomEdge.resolve(outline); + expect(bottomEdge.from, lessThan(0.5)); + expect(bottomEdge.to, greaterThan(0.5)); + final topEdge = BeamSegment.topEdge.resolve(outline); + expect(topEdge.to, lessThan(topEdge.from)); + }); + }); + } + + test('edge anchors follow per-corner radii', () { + final outline = BeamOutline( + rect, + const BorderRadius.only( + topLeft: Radius.circular(4), + topRight: Radius.circular(30), ), - BeamSegment.rightHalf, ); - expect(BeamSegment.rightHalf, isNot(BeamSegment.leftHalf)); - expect( - BeamSegment.rightHalf.hashCode, - isNot(BeamSegment.leftHalf.hashCode), + final mid = outline.pointAt( + const BeamAnchor.edge(BeamEdge.top).resolve(outline), ); + // Halfway between the end of the top-left arc and the start of the + // top-right one, not the box's centre. + expect(mid.dx, closeTo((4 + (200 - 30)) / 2, 1e-3)); + expect(mid.dy, closeTo(0, 1e-3)); }); - test('fraction anchors wrap modulo one when resolved', () { - expect( - const BeamAnchor.fraction(1.25).resolve(perimeter), - closeTo(0.25, 1e-9), - ); - expect( - const BeamAnchor.fraction(-0.25).resolve(perimeter), - closeTo(0.75, 1e-9), - ); - }); + group('equality and toString', () { + test('anchors compare by value, defaults included', () { + // The right-hand sides are built at run time: two equal const + // expressions are one canonical instance, and `==` would never get + // past `identical`. + final quarter = BeamAnchor.fraction(double.parse('0.25')); + expect(const BeamAnchor.fraction(0.25), quarter); + expect(const BeamAnchor.fraction(0.25).hashCode, quarter.hashCode); + expect( + const BeamAnchor.edge(BeamEdge.right), + BeamAnchor.edge(BeamEdge.right, double.parse('0.5')), + ); + expect( + const BeamAnchor.corner(BeamCorner.topLeft), + BeamAnchor.corner(BeamCorner.topLeft, double.parse('0.5')), + ); + expect(BeamAnchor.rightCenter, const BeamAnchor.edge(BeamEdge.right)); + expect(BeamAnchor.topCenter, const BeamAnchor.fraction(0)); + }); - test('half presets use the documented clockwise anchors', () { - expect(BeamSegment.bottomHalf.start, BeamAnchor.rightCenter); - expect(BeamSegment.bottomHalf.end, BeamAnchor.leftCenter); - expect(BeamSegment.topHalf.start, BeamAnchor.leftCenter); - expect(BeamSegment.topHalf.end, BeamAnchor.rightCenter); - expect(BeamSegment.leftHalf.start, BeamAnchor.bottomCenter); - expect(BeamSegment.leftHalf.end, BeamAnchor.topCenter); - expect(BeamSegment.rightHalf.start, BeamAnchor.topCenter); - expect(BeamSegment.rightHalf.end, BeamAnchor.bottomCenter); - }); + test('kind, side and position all count', () { + const anchors = [ + BeamAnchor.fraction(0.5), + BeamAnchor.fraction(0.6), + BeamAnchor.edge(BeamEdge.bottom), + BeamAnchor.edge(BeamEdge.top), + BeamAnchor.edge(BeamEdge.bottom, 0.4), + BeamAnchor.corner(BeamCorner.bottomLeft), + BeamAnchor.corner(BeamCorner.topRight), + BeamAnchor.corner(BeamCorner.bottomLeft, 0.2), + ]; + for (var i = 0; i < anchors.length; i++) { + for (var j = i + 1; j < anchors.length; j++) { + expect(anchors[i], isNot(anchors[j])); + } + } + }); - test('edge presets include both adjoining corner arcs', () { - expect( - BeamSegment.bottomEdge.start, - const BeamAnchor.corner(BeamCorner.bottomRight, 0), - ); - expect( - BeamSegment.bottomEdge.end, - const BeamAnchor.corner(BeamCorner.bottomLeft, 1), - ); - expect( - BeamSegment.topEdge.start, - const BeamAnchor.corner(BeamCorner.topLeft, 0), - ); - expect( - BeamSegment.rightEdge.end, - const BeamAnchor.corner(BeamCorner.bottomRight, 1), - ); - }); + test('segments compare start, end and feather', () { + final rightHalf = BeamSegment( + start: BeamAnchor.fraction(double.parse('0')), + end: BeamAnchor.edge(BeamEdge.bottom, double.parse('0.5')), + ); + expect(identical(rightHalf, BeamSegment.rightHalf), isFalse); + expect(rightHalf, BeamSegment.rightHalf); + expect(rightHalf.hashCode, BeamSegment.rightHalf.hashCode); + expect(BeamSegment.rightHalf, isNot(BeamSegment.leftHalf)); + expect( + const BeamSegment( + start: BeamAnchor.topCenter, + end: BeamAnchor.bottomCenter, + feather: 0, + ), + isNot(BeamSegment.rightHalf), + ); + expect(BeamSegment.rightHalf.feather, greaterThan(0)); + }); - test('toString exposes the complete value', () { - expect( - const BeamSegment( - start: BeamAnchor.fraction(0.1), - end: BeamAnchor.edge(BeamEdge.bottom), - feather: 8, - ).toString(), - 'BeamSegment(start: BeamAnchor.fraction(0.1), end: ' - 'BeamAnchor.edge(BeamEdge.bottom, 0.5), feather: 8.0)', - ); + test('toString exposes the complete value', () { + expect( + const BeamSegment( + start: BeamAnchor.fraction(0.1), + end: BeamAnchor.edge(BeamEdge.bottom), + feather: 8, + ).toString(), + 'BeamSegment(start: BeamAnchor.fraction(0.1), end: ' + 'BeamAnchor.edge(BeamEdge.bottom, 0.5), feather: 8.0)', + ); + expect( + const BeamAnchor.corner(BeamCorner.topLeft, 0).toString(), + 'BeamAnchor.corner(BeamCorner.topLeft, 0.0)', + ); + }); }); } diff --git a/test/models/beam_variant_test.dart b/test/models/beam_variant_test.dart deleted file mode 100644 index 33df3e8..0000000 --- a/test/models/beam_variant_test.dart +++ /dev/null @@ -1,82 +0,0 @@ -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_test/flutter_test.dart'; - -/// `BeamVariant` carries every per-variant default a beam resolves against, -/// so tooling reads them from the enum rather than transcribing them out of -/// doc comments. -void main() { - group('BeamVariant', () { - test('isPulse splits the two families', () { - expect(BeamVariant.rotate.isPulse, isFalse); - expect(BeamVariant.small.isPulse, isFalse); - expect(BeamVariant.line.isPulse, isFalse); - expect(BeamVariant.pulseInside.isPulse, isTrue); - expect(BeamVariant.pulseOutside.isPulse, isTrue); - }); - - test('cycle, radius, and border width match the source presets', () { - expect( - BeamVariant.rotate.defaultCycleDuration, - const Duration(milliseconds: 1960), - ); - expect( - BeamVariant.small.defaultCycleDuration, - const Duration(milliseconds: 1960), - ); - expect( - BeamVariant.line.defaultCycleDuration, - const Duration(milliseconds: 3100), - ); - expect( - BeamVariant.pulseInside.defaultCycleDuration, - const Duration(milliseconds: 2300), - ); - expect( - BeamVariant.pulseOutside.defaultCycleDuration, - const Duration(milliseconds: 2300), - ); - expect(BeamVariant.small.defaultBorderRadius, 32); - for (final variant in BeamVariant.values) { - if (variant != BeamVariant.small) { - expect(variant.defaultBorderRadius, 16, reason: '$variant'); - } - expect(variant.defaultBorderWidth, 1, reason: '$variant'); - } - }); - - test('the traveling variants share the 12s hue period', () { - for (final variant in [ - BeamVariant.rotate, - BeamVariant.small, - BeamVariant.line, - ]) { - expect( - variant.defaultHuePeriod, - const Duration(seconds: 12), - reason: '$variant', - ); - } - }); - - test('the pulse variants carry their own hue periods', () { - expect( - BeamVariant.pulseInside.defaultHuePeriod, - const Duration(seconds: 16), - ); - expect( - BeamVariant.pulseOutside.defaultHuePeriod, - const Duration(seconds: 14), - ); - }); - - test('the bloom hue period is 8s for every variant', () { - for (final variant in BeamVariant.values) { - expect( - variant.defaultBloomHuePeriod, - const Duration(seconds: 8), - reason: '$variant', - ); - } - }); - }); -} diff --git a/test/models/value_objects_test.dart b/test/models/value_objects_test.dart index f3ed929..a928890 100644 --- a/test/models/value_objects_test.dart +++ b/test/models/value_objects_test.dart @@ -1,236 +1,132 @@ -import 'dart:ui' show Brightness, Path, Rect; - import 'package:flutter/animation.dart'; import 'package:flutter/painting.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/models/model_validation.dart'; import 'package:flutter_test/flutter_test.dart'; -/// The four beam value objects and the theme data share one contract: every -/// field is nullable and means *inherit*, `merge` layers the argument over -/// the receiver, `copyWith` keeps what it is not given, and equality is by -/// value so a rebuilt-inline object never re-resolves a config. +/// The four beam value objects share one contract: every field is nullable +/// and means *inherit*, `merge` layers the argument over the receiver, +/// `copyWith` keeps what it is not given, and equality is by value so a +/// rebuilt-inline object never re-resolves a config. `BorderBeamThemeData`, +/// which holds them, is covered in `test/widget/border_beam_theme_test.dart`. void main() { + /// Asserts each of [variants] differs from [base] and from every other. + // Equal operands are built at run time (`double.parse`, non-const calls): + // two equal const expressions are one canonical instance, so comparing + // them never gets past `identical` and pins nothing about `==`. + void expectEveryFieldCounts(T base, List variants) { + for (final v in variants) { + expect(v, isNot(base), reason: '$v'); + expect(v.hashCode, isNot(base.hashCode), reason: '$v'); + } + for (var i = 0; i < variants.length; i++) { + for (var j = i + 1; j < variants.length; j++) { + expect(variants[i], isNot(variants[j])); + } + } + } + group('BeamStyle', () { + const full = BeamStyle( + colors: BeamColors.ocean, + theme: BeamTheme.dark, + strength: 0.5, + glow: 1.5, + hueShift: 20, + hueMode: BeamHueMode.continuous, + hueBase: 10, + ); + test('merge lets the argument win field by field', () { - const base = BeamStyle( - colors: BeamColors.ocean, - strength: 0.5, - hueBase: 10, + final merged = full.merge( + const BeamStyle(colors: BeamColors.sunset, glow: 2), ); - const over = BeamStyle(colors: BeamColors.sunset, glowBoost: 2); - final merged = base.merge(over); expect(merged.colors, BeamColors.sunset, reason: 'argument wins'); - expect(merged.strength, 0.5, reason: 'null inherits'); + expect(merged.glow, 2); + expect(merged.theme, BeamTheme.dark, reason: 'null inherits'); + expect(merged.strength, 0.5); + expect(merged.hueShift, 20); + expect(merged.hueMode, BeamHueMode.continuous); expect(merged.hueBase, 10); - expect(merged.glowBoost, 2); }); - test('merge(null) returns the receiver unchanged', () { - const base = BeamStyle(strength: 0.25); - expect(base.merge(null), base); + test('merging onto an empty style takes every field', () { + expect(const BeamStyle().merge(full), full); + }); + + test('merge(null) returns the receiver', () { + expect(identical(full.merge(null), full), isTrue); }); test('copyWith keeps unnamed fields', () { - const base = BeamStyle(colors: BeamColors.mono, saturation: 2); - final copy = base.copyWith(saturation: 3); - expect(copy.colors, BeamColors.mono); - expect(copy.saturation, 3); + final copy = full.copyWith(strength: 0.9, hueMode: BeamHueMode.none); + expect(copy.strength, 0.9); + expect(copy.hueMode, BeamHueMode.none); + expect(copy.colors, BeamColors.ocean); + expect(copy.glow, 1.5); + expect(copy.hueBase, 10); + expect(full.copyWith(), full); }); test('equality and hashCode are by value', () { const a = BeamStyle(colors: BeamColors.ocean, strength: 0.4); - const b = BeamStyle(colors: BeamColors.ocean, strength: 0.4); + final b = BeamStyle( + colors: BeamColors.ocean, + strength: double.parse('0.4'), + ); expect(a, b); expect(a.hashCode, b.hashCode); - expect(a, isNot(const BeamStyle(colors: BeamColors.ocean))); - }); - - test('themeConfig is part of the value', () { - final preset = BeamThemeConfig.presetFor( - BeamVariant.rotate, - Brightness.dark, - ); - expect( - BeamStyle(themeConfig: preset), - BeamStyle(themeConfig: preset.copyWith()), - ); - expect( - BeamStyle(themeConfig: preset), - isNot(BeamStyle(themeConfig: preset.copyWith(bloomOpacity: 0.1))), - ); }); - test('the beam-shaping fields follow the inherit contract', () { - const base = BeamStyle( - hueMode: BeamHueMode.continuous, - tailLength: 2, - glowSpread: 1.5, - comet: true, - sparkle: 0.4, - segments: 8, - ); - final merged = base.merge( - const BeamStyle(tailLength: 3, comet: false, segments: 12), - ); - expect(merged.hueMode, BeamHueMode.continuous, reason: 'null inherits'); - expect(merged.tailLength, 3, reason: 'argument wins'); - expect(merged.glowSpread, 1.5); - expect(merged.comet, isFalse, reason: 'false is a value, not a null'); - expect(merged.sparkle, 0.4); - expect(merged.segments, 12); - - final copy = base.copyWith(sparkle: 0.9); - expect(copy.sparkle, 0.9); - expect(copy.hueMode, BeamHueMode.continuous); - expect(copy.tailLength, 2); - expect(copy.glowSpread, 1.5); - expect(copy.comet, isTrue); - expect(copy.segments, 8); - }); - - test('every beam-shaping field is part of the value', () { - const base = BeamStyle(); - const variants = [ - BeamStyle(hueMode: BeamHueMode.continuous), - BeamStyle(tailLength: 2), - BeamStyle(glowSpread: 2), - BeamStyle(comet: true), - BeamStyle(sparkle: 0.5), - BeamStyle(segments: 6), - ]; - for (final variant in variants) { - expect(variant, isNot(base), reason: '$variant'); - expect(variant.hashCode, isNot(base.hashCode), reason: '$variant'); - } - expect( - const BeamStyle(tailLength: 2, comet: true), - const BeamStyle(tailLength: 2, comet: true), - ); + test('every field is part of the value', () { + expectEveryFieldCounts(const BeamStyle(), const [ + BeamStyle(colors: BeamColors.ocean), + BeamStyle(theme: BeamTheme.light), + BeamStyle(strength: 0.5), + BeamStyle(glow: 2), + BeamStyle(hueShift: 12), + BeamStyle(hueMode: BeamHueMode.none), + BeamStyle(hueBase: 90), + ]); }); test('toString lists only the fields that are set', () { + expect(const BeamStyle().toString(), 'BeamStyle()'); expect( const BeamStyle( + strength: 0.5, hueMode: BeamHueMode.pingPong, - tailLength: 2, - glowSpread: 1.5, - comet: true, - sparkle: 0.25, - segments: 4, ).toString(), - 'BeamStyle(hueMode: BeamHueMode.pingPong, tailLength: 2.0, ' - 'glowSpread: 1.5, comet: true, sparkle: 0.25, segments: 4)', + 'BeamStyle(strength: 0.5, hueMode: BeamHueMode.pingPong)', ); - expect(const BeamStyle().toString(), 'BeamStyle()'); }); - }); - - test('the reference-port fields follow the inherit contract', () { - const base = BeamStyle( - innerSizeScale: 0.6, - renderScale: 0.5, - pulseOutsideTuning: BeamPulseOutsideTuning.stock, - ); - final merged = base.merge(const BeamStyle(renderScale: 0.25)); - expect(merged.innerSizeScale, 0.6, reason: 'null inherits'); - expect(merged.renderScale, 0.25, reason: 'argument wins'); - expect(merged.pulseOutsideTuning, BeamPulseOutsideTuning.stock); - - final copy = base.copyWith(innerSizeScale: 1.4); - expect(copy.innerSizeScale, 1.4); - expect(copy.renderScale, 0.5); - expect(copy.pulseOutsideTuning, BeamPulseOutsideTuning.stock); - }); - - test('every reference-port field is part of the value', () { - const base = BeamStyle(); - const variants = [ - BeamStyle(innerSizeScale: 0.6), - BeamStyle(renderScale: 0.5), - BeamStyle(pulseOutsideTuning: BeamPulseOutsideTuning.stock), - ]; - for (final variant in variants) { - expect(variant, isNot(base), reason: '$variant'); - expect(variant.hashCode, isNot(base.hashCode), reason: '$variant'); - } - expect( - const BeamStyle(innerSizeScale: 0.6, renderScale: 0.5), - const BeamStyle(innerSizeScale: 0.6, renderScale: 0.5), - ); - expect( - const BeamStyle(pulseOutsideTuning: BeamPulseOutsideTuning.demo), - isNot(const BeamStyle(pulseOutsideTuning: BeamPulseOutsideTuning.stock)), - ); - }); - test('toString lists the reference-port fields', () { - expect( - const BeamStyle( - innerSizeScale: 0.6, - renderScale: 0.5, - pulseOutsideTuning: BeamPulseOutsideTuning.stock, - ).toString(), - 'BeamStyle(innerSizeScale: 0.6, renderScale: 0.5, ' - 'pulseOutsideTuning: BeamPulseOutsideTuning.stock)', - ); - }); - - test('pulseOutsideStock cancels the demo tuning it can reach', () { - const stock = BeamStyle.pulseOutsideStock; - expect(stock.pulseOutsideTuning, BeamPulseOutsideTuning.stock); - expect(stock.glowBoost, 1); - expect(stock.strokeOpacityFactor, closeTo(1 / 1.71, 1e-12)); - expect(stock.innerOpacityFactor, stock.strokeOpacityFactor); - expect(stock.bloomOpacityFactor, stock.strokeOpacityFactor); - expect(stock.glowBrightness, 1.3); - expect(stock.glowSaturation, 1.2); - expect( - stock.merge(const BeamStyle(glowBrightness: 2)).glowBrightness, - 2, - reason: 'it is a starting point, not a lock', - ); + test('rejects a negative glow', () { + expect(() => BeamStyle(glow: double.parse('-0.1')), throwsAssertionError); + expect(BeamStyle(glow: double.parse('0')).glow, 0); + }); }); group('BeamShape', () { - test('circular fills all four corners', () { - final shape = BeamShape.circular(12, superellipse: true); - expect(shape.radius, BorderRadius.circular(12)); - expect(shape.superellipse, isTrue); - expect(shape.borderWidth, isNull); - }); - - test('stadium is an infinite radius the geometry clamps', () { - const shape = BeamShape.stadium(); + test('all and circular are the same value for the same number', () { + expect(const BeamShape.all(24), BeamShape.circular(24)); + expect(const BeamShape.all(24).hashCode, BeamShape.circular(24).hashCode); expect( - shape.radius, - const BorderRadius.all(Radius.circular(double.infinity)), - ); - }); - - test('merge and copyWith follow the inherit contract', () { - const base = BeamShape(borderWidth: 2); - final merged = base.merge( - const BeamShape(radius: BorderRadius.zero, superellipse: true), + const BeamShape.all(24, borderWidth: 2, superellipse: true), + BeamShape.circular(24, borderWidth: 2, superellipse: true), ); - expect(merged.borderWidth, 2); - expect(merged.radius, BorderRadius.zero); - expect(merged.superellipse, isTrue); - expect(base.copyWith(superellipse: false).borderWidth, 2); - }); - - test('equality is by value', () { expect( - const BeamShape(radius: BorderRadius.zero, borderWidth: 1), - const BeamShape(radius: BorderRadius.zero, borderWidth: 1), + const BeamShape.all(24), + const BeamShape(radius: BorderRadius.all(Radius.circular(24))), ); + expect(const BeamShape.all(24), isNot(BeamShape.circular(25))); expect( - const BeamShape(radius: BorderRadius.zero, borderWidth: 1).hashCode, - const BeamShape(radius: BorderRadius.zero, borderWidth: 1).hashCode, + const BeamShape.all(24).toString(), + BeamShape.circular(24).toString(), ); - expect(BeamShape.circular(4), isNot(BeamShape.circular(5))); }); - test('all is the const path to a uniform radius', () { + test('all grows its number into a uniform BorderRadius', () { const shape = BeamShape.all(24, superellipse: true); expect(shape.radius, BorderRadius.circular(24)); expect(shape.superellipse, isTrue); @@ -242,254 +138,321 @@ void main() { ); }); - test('all and circular are the same value', () { - expect(const BeamShape.all(24), BeamShape.circular(24)); - expect(const BeamShape.all(24).hashCode, BeamShape.circular(24).hashCode); - expect( - const BeamShape.all(24, borderWidth: 2), - BeamShape.circular(24, borderWidth: 2), - ); - expect(const BeamShape.all(24), isNot(BeamShape.circular(25))); + test('stadium is an infinite radius on every corner', () { + const shape = BeamShape.stadium(borderWidth: 2); expect( - const BeamShape.all(24), - const BeamShape(radius: BorderRadius.all(Radius.circular(24))), + shape.radius, + const BorderRadius.all(Radius.circular(double.infinity)), ); - expect( - const BeamShape.all(24).toString(), - BeamShape.circular(24).toString(), + expect(shape.borderWidth, 2); + expect(shape, BeamShape.stadium(borderWidth: double.parse('2'))); + }); + + test('resolveRadius falls back to the default on every corner', () { + expect(BeamShape.defaultRadius, 16); + for (final dir in TextDirection.values) { + expect( + const BeamShape().resolveRadius(dir), + const BorderRadius.all(Radius.circular(BeamShape.defaultRadius)), + ); + } + }); + + test('resolveRadius resolves a directional radius per text direction', () { + const shape = BeamShape( + radius: BorderRadiusDirectional.only( + topStart: Radius.circular(8), + bottomEnd: Radius.circular(20), + ), ); + final ltr = shape.resolveRadius(TextDirection.ltr); + expect(ltr.topLeft, const Radius.circular(8)); + expect(ltr.bottomRight, const Radius.circular(20)); + expect(ltr.topRight, Radius.zero); + final rtl = shape.resolveRadius(TextDirection.rtl); + expect(rtl.topRight, const Radius.circular(8)); + expect(rtl.bottomLeft, const Radius.circular(20)); + expect(rtl.topLeft, Radius.zero); }); - test('copyWith and merge carry a uniform radius through', () { - const base = BeamShape.all(24); - expect(base.copyWith(borderWidth: 2).radius, BorderRadius.circular(24)); - expect( - base.merge(const BeamShape(superellipse: true)).radius, - BorderRadius.circular(24), + test('resolveRadius leaves an absolute radius alone', () { + final shape = BeamShape.circular(9); + expect(shape.resolveRadius(TextDirection.rtl), BorderRadius.circular(9)); + }); + + test('merge lets the argument win field by field', () { + const base = BeamShape.all( + 24, + borderWidth: 2, + ringOffset: 4, + segment: BeamSegment.bottomHalf, + dashes: 6, ); + final merged = base.merge(const BeamShape(superellipse: true, dashes: 8)); + expect(merged.radius, BorderRadius.circular(24), reason: 'inherits'); + expect(merged.borderWidth, 2); + expect(merged.ringOffset, 4); + expect(merged.segment, BeamSegment.bottomHalf); + expect(merged.superellipse, isTrue, reason: 'argument wins'); + expect(merged.dashes, 8); + expect(identical(base.merge(null), base), isTrue); + }); + + test('copyWith keeps unnamed fields and carries a uniform radius', () { + const base = BeamShape.all(24, segment: BeamSegment.topEdge); + final copy = base.copyWith(borderWidth: 3); + expect(copy.radius, BorderRadius.circular(24)); + expect(copy.segment, BeamSegment.topEdge); + expect(copy.borderWidth, 3); expect( base.copyWith(radius: BorderRadius.zero).radius, BorderRadius.zero, reason: 'an explicit radius replaces the uniform one', ); expect( - const BeamShape( - radius: BorderRadius.zero, - ).merge(const BeamShape.all(8)), + const BeamShape(radius: BorderRadius.zero) + .merge(const BeamShape.all(8)), const BeamShape.all(8), ); }); - test('the geometry fields follow the inherit contract', () { - final contour = BeamPathContour( - (rect) => Path()..addRect(rect), - key: 'rect', - ); - final base = BeamShape( - edge: BeamEdge.top, - ringOffset: 4, - contour: contour, - segment: BeamSegment.bottomHalf, - wrapCorners: true, - ); - final merged = base.merge(const BeamShape(edge: BeamEdge.left)); - expect(merged.edge, BeamEdge.left, reason: 'argument wins'); - expect(merged.ringOffset, 4, reason: 'null inherits'); - expect(merged.contour, contour); - expect(merged.segment, BeamSegment.bottomHalf); - expect(merged.wrapCorners, isTrue); - expect(base.copyWith(ringOffset: -2).edge, BeamEdge.top); - expect(base.copyWith(ringOffset: -2).ringOffset, -2); - }); - - test('every geometry field is part of the value', () { - const base = BeamShape(); - final variants = [ - const BeamShape(edge: BeamEdge.top), - const BeamShape(ringOffset: 3), - const BeamShape(segment: BeamSegment.bottomHalf), - const BeamShape(wrapCorners: true), - BeamShape( - contour: BeamPathContour( - (rect) => Path()..addOval(rect), - key: 'oval', - ), - ), - ]; - for (final variant in variants) { - expect(variant, isNot(base), reason: '$variant'); - expect(variant.hashCode, isNot(base.hashCode), reason: '$variant'); - } + test('every field is part of the value', () { + expectEveryFieldCounts(const BeamShape(), const [ + BeamShape(radius: BorderRadius.zero), + BeamShape(superellipse: true), + BeamShape(borderWidth: 2), + BeamShape(ringOffset: 3), + BeamShape(segment: BeamSegment.bottomHalf), + BeamShape(dashes: 4), + ]); }); test('toString lists only the fields that are set', () { + expect(const BeamShape().toString(), 'BeamShape()'); expect( - const BeamShape( - edge: BeamEdge.right, - ringOffset: 2, - segment: BeamSegment.bottomHalf, - wrapCorners: true, - ).toString(), - 'BeamShape(edge: BeamEdge.right, ringOffset: 2.0, segment: ' - 'BeamSegment(start: BeamAnchor.edge(BeamEdge.right, 0.5), end: ' - 'BeamAnchor.edge(BeamEdge.left, 0.5), feather: 32.0), ' - 'wrapCorners: true)', + const BeamShape(borderWidth: 2, dashes: 3).toString(), + 'BeamShape(borderWidth: 2.0, dashes: 3)', ); - expect(const BeamShape().toString(), 'BeamShape()'); - }); - }); - - group('BeamTiming', () { - test('rejects values that would make phase arithmetic invalid', () { - final zero = double.parse('0'); - final nan = double.parse('NaN'); - - expect(() => BeamTiming(speed: zero), throwsAssertionError); - expect(() => BeamTiming(speed: nan), throwsAssertionError); - expect(() => BeamTiming(phaseOffset: -0.01), throwsAssertionError); - expect(() => BeamTiming(phaseOffset: 1.01), throwsAssertionError); - expect(() => BeamTiming(beamCount: 0), throwsAssertionError); - expect(() => BeamTiming(breatheFactor: zero), throwsAssertionError); - expect(() => BeamTiming(spikeFactor: nan), throwsAssertionError); - expect(() => BeamTiming(spike2Factor: -1), throwsAssertionError); - }); - - test('merge lets the argument win field by field', () { - const base = BeamTiming(cycle: Duration(seconds: 2), speed: 2); - const over = BeamTiming(cycleGap: Duration(seconds: 1)); - final merged = base.merge(over); - expect(merged.cycle, const Duration(seconds: 2)); - expect(merged.speed, 2); - expect(merged.cycleGap, const Duration(seconds: 1)); - expect(merged.huePeriod, isNull); - }); - - test('copyWith keeps unnamed fields', () { - const base = BeamTiming(breatheFactor: 1.5, spikeFactor: 2); - final copy = base.copyWith(spikeFactor: 3); - expect(copy.breatheFactor, 1.5); - expect(copy.spikeFactor, 3); }); - test('equality is by value', () { + test('every constructor rejects negative dashes', () { + final negative = int.parse('-1'); + expect(() => BeamShape(dashes: negative), throwsAssertionError); + expect(() => BeamShape.all(8, dashes: negative), throwsAssertionError); expect( - const BeamTiming(cycle: Duration(seconds: 1)), - const BeamTiming(cycle: Duration(seconds: 1)), - ); - expect( - const BeamTiming(cycle: Duration(seconds: 1)).hashCode, - const BeamTiming(cycle: Duration(seconds: 1)).hashCode, - ); - expect( - const BeamTiming(cycle: Duration(seconds: 1)), - isNot(const BeamTiming(cycle: Duration(seconds: 2))), + () => BeamShape.circular(8, dashes: negative), + throwsAssertionError, ); + expect(() => BeamShape.stadium(dashes: negative), throwsAssertionError); }); + }); - test('the travel fields follow the inherit contract', () { - const base = BeamTiming( - direction: BeamDirection.reverse, - phaseOffset: 0.25, - beamCount: 3, + group('BeamTiming', () { + const full = BeamTiming( + cycle: Duration(seconds: 2), + cycleGap: Duration(milliseconds: 500), + speed: 1.5, + direction: BeamDirection.reverse, + phaseOffset: 0.25, + huePeriod: Duration(seconds: 6), + ); + + test('merge lets the argument win field by field', () { + final merged = full.merge( + const BeamTiming(speed: 3, direction: BeamDirection.bounce), ); - final merged = base.merge(const BeamTiming(beamCount: 5)); - expect(merged.direction, BeamDirection.reverse); + expect(merged.speed, 3, reason: 'argument wins'); + expect(merged.direction, BeamDirection.bounce); + expect(merged.cycle, const Duration(seconds: 2), reason: 'inherits'); + expect(merged.cycleGap, const Duration(milliseconds: 500)); expect(merged.phaseOffset, 0.25); - expect(merged.beamCount, 5); + expect(merged.huePeriod, const Duration(seconds: 6)); + expect(const BeamTiming().merge(full), full); + expect(identical(full.merge(null), full), isTrue); + }); - final copy = base.copyWith(phaseOffset: 0.75); + test('copyWith keeps unnamed fields', () { + final copy = full.copyWith(phaseOffset: 0.75); expect(copy.phaseOffset, 0.75); - expect(copy.direction, BeamDirection.reverse); - expect(copy.beamCount, 3); + expect(copy.cycle, full.cycle); + expect(copy.huePeriod, full.huePeriod); + expect(full.copyWith(), full); }); - test('every travel field is part of the value', () { - const base = BeamTiming(); - const variants = [ + test('every field is part of the value', () { + expectEveryFieldCounts(const BeamTiming(), const [ + BeamTiming(cycle: Duration(seconds: 1)), + BeamTiming(cycleGap: Duration(seconds: 1)), + BeamTiming(speed: 2), BeamTiming(direction: BeamDirection.bounce), BeamTiming(phaseOffset: 0.5), - BeamTiming(beamCount: 2), - ]; - for (final variant in variants) { - expect(variant, isNot(base), reason: '$variant'); - expect(variant.hashCode, isNot(base.hashCode), reason: '$variant'); - } - expect( - const BeamTiming(direction: BeamDirection.bounce, beamCount: 2), - const BeamTiming(direction: BeamDirection.bounce, beamCount: 2), + BeamTiming(huePeriod: Duration(seconds: 3)), + ]); + final same = BeamTiming( + cycle: Duration(seconds: int.parse('1')), + speed: double.parse('2'), ); + const timing = BeamTiming(cycle: Duration(seconds: 1), speed: 2); + expect(same, timing); + expect(same.hashCode, timing.hashCode); }); test('toString lists only the fields that are set', () { + expect(const BeamTiming().toString(), 'BeamTiming()'); expect( const BeamTiming( direction: BeamDirection.reverse, phaseOffset: 0.5, - beamCount: 2, ).toString(), - 'BeamTiming(direction: BeamDirection.reverse, phaseOffset: 0.5, ' - 'beamCount: 2)', + 'BeamTiming(direction: BeamDirection.reverse, phaseOffset: 0.5)', ); - expect(const BeamTiming().toString(), 'BeamTiming()'); + }); + + test('rejects a rate or phase that would break the arithmetic', () { + double v(String s) => double.parse(s); + expect(() => BeamTiming(speed: v('0')), throwsAssertionError); + expect(() => BeamTiming(speed: v('-1')), throwsAssertionError); + expect(() => BeamTiming(speed: v('NaN')), throwsAssertionError); + expect(() => BeamTiming(speed: v('Infinity')), throwsAssertionError); + expect(() => BeamTiming(phaseOffset: v('-0.01')), throwsAssertionError); + expect(() => BeamTiming(phaseOffset: v('1.01')), throwsAssertionError); + expect(() => BeamTiming(phaseOffset: v('NaN')), throwsAssertionError); + expect(BeamTiming(phaseOffset: v('0')).phaseOffset, 0); + expect(BeamTiming(phaseOffset: v('1')).phaseOffset, 1); }); }); - group('BeamPlayback', () { - test('merge lets the argument win field by field', () { - const base = BeamPlayback(active: false, autoPlay: false); - const over = BeamPlayback(active: true, duration: Duration(seconds: 3)); - final merged = base.merge(over); - expect(merged.active, isTrue); - expect(merged.autoPlay, isFalse); - expect(merged.duration, const Duration(seconds: 3)); - expect(merged.startAfter, isNull); + group('validateBeamTiming', () { + test('accepts an empty and a fully valid timing', () { + expect(() => validateBeamTiming(const BeamTiming()), returnsNormally); + expect( + () => validateBeamTiming( + const BeamTiming( + cycle: Duration(seconds: 2), + cycleGap: Duration.zero, + speed: 0.5, + phaseOffset: 1, + huePeriod: Duration(milliseconds: 1), + ), + ), + returnsNormally, + ); }); - test('copyWith keeps unnamed fields', () { - const base = BeamPlayback( - active: false, - reducedMotion: BeamReducedMotion.animate, + // The constructor asserts catch speed and phaseOffset in debug builds, + // so only the durations — which carry no assert — reach the runtime + // check in a test run. + test('rejects a non-positive cycle', () { + expect( + () => validateBeamTiming(const BeamTiming(cycle: Duration.zero)), + throwsArgumentError, ); expect( - base.copyWith(active: true).reducedMotion, - BeamReducedMotion.animate, + () => validateBeamTiming( + const BeamTiming(cycle: Duration(milliseconds: -5)), + ), + throwsArgumentError, + ); + }); + + test('rejects a negative cycle gap', () { + expect( + () => validateBeamTiming( + const BeamTiming(cycleGap: Duration(microseconds: -1)), + ), + throwsArgumentError, ); }); - test('repeat and reducedMotion follow the inherit contract', () { - const base = BeamPlayback( - repeat: BeamRepeat.count(3), - reducedMotion: BeamReducedMotion.hide, + test('rejects a non-positive hue period', () { + expect( + () => validateBeamTiming(const BeamTiming(huePeriod: Duration.zero)), + throwsArgumentError, + ); + expect( + () => validateBeamTiming( + const BeamTiming(huePeriod: Duration(seconds: -1)), + ), + throwsArgumentError, ); - final merged = base.merge( - const BeamPlayback(reducedMotion: BeamReducedMotion.slow), + }); + }); + + group('BeamPlayback', () { + const full = BeamPlayback( + active: false, + autoPlay: false, + startAfter: Duration(milliseconds: 200), + duration: Duration(seconds: 3), + repeat: BeamRepeat.count(2), + reducedMotion: BeamReducedMotion.hide, + pauseWhenOffscreen: false, + fadeCurve: BeamPlayback.cssEase, + debugFrozenAt: Duration(milliseconds: 1300), + ); + + test('merge lets the argument win field by field', () { + final merged = full.merge( + const BeamPlayback(active: true, reducedMotion: BeamReducedMotion.slow), ); - expect(merged.repeat, const BeamRepeat.count(3), reason: 'null inherits'); + expect(merged.active, isTrue, reason: 'argument wins'); expect(merged.reducedMotion, BeamReducedMotion.slow); - expect(base.copyWith(active: false).repeat, const BeamRepeat.count(3)); + expect(merged.autoPlay, isFalse, reason: 'inherits'); + expect(merged.startAfter, const Duration(milliseconds: 200)); + expect(merged.duration, const Duration(seconds: 3)); + expect(merged.repeat, const BeamRepeat.count(2)); + expect(merged.pauseWhenOffscreen, isFalse); + expect(merged.fadeCurve, BeamPlayback.cssEase); + expect(merged.debugFrozenAt, const Duration(milliseconds: 1300)); + expect(const BeamPlayback().merge(full), full); + expect(identical(full.merge(null), full), isTrue); }); - test('repeat and reducedMotion are part of the value', () { - const base = BeamPlayback(); - const variants = [ + test('copyWith keeps unnamed fields', () { + final copy = full.copyWith(repeat: const BeamRepeat.once()); + expect(copy.repeat, const BeamRepeat.once()); + expect(copy.reducedMotion, BeamReducedMotion.hide); + expect(copy.debugFrozenAt, full.debugFrozenAt); + expect(full.copyWith(), full); + }); + + test('every field is part of the value', () { + expectEveryFieldCounts(const BeamPlayback(), const [ + BeamPlayback(active: false), + BeamPlayback(autoPlay: false), + BeamPlayback(startAfter: Duration(seconds: 1)), + BeamPlayback(duration: Duration(seconds: 1)), BeamPlayback(repeat: BeamRepeat.once()), BeamPlayback(reducedMotion: BeamReducedMotion.staticFrame), - ]; - for (final variant in variants) { - expect(variant, isNot(base), reason: '$variant'); - expect(variant.hashCode, isNot(base.hashCode), reason: '$variant'); - } + BeamPlayback(pauseWhenOffscreen: false), + BeamPlayback(fadeCurve: BeamPlayback.cssEase), + BeamPlayback(debugFrozenAt: Duration(seconds: 1)), + ]); expect( const BeamPlayback(repeat: BeamRepeat.count(2)), isNot(const BeamPlayback(repeat: BeamRepeat.count(3))), ); - expect( - const BeamPlayback(repeat: BeamRepeat.once()), - const BeamPlayback(repeat: BeamRepeat.once()), - ); + }); + + test('equality and hashCode are by value', () { + final same = BeamPlayback( + active: bool.parse('false'), + autoPlay: bool.parse('false'), + startAfter: Duration(milliseconds: int.parse('200')), + duration: Duration(seconds: int.parse('3')), + repeat: BeamRepeat.count(int.parse('2')), + reducedMotion: BeamReducedMotion.values.byName('hide'), + pauseWhenOffscreen: bool.parse('false'), + fadeCurve: BeamPlayback.cssEase, + debugFrozenAt: Duration(milliseconds: int.parse('1300')), + ); + expect(identical(same, full), isFalse); + expect(same, full); + expect(same.hashCode, full.hashCode); }); test('toString lists only the fields that are set', () { + expect(const BeamPlayback().toString(), 'BeamPlayback()'); expect( const BeamPlayback( repeat: BeamRepeat.count(2), @@ -498,201 +461,78 @@ void main() { 'BeamPlayback(repeat: BeamRepeat.count(2), ' 'reducedMotion: BeamReducedMotion.hide)', ); - expect(const BeamPlayback().toString(), 'BeamPlayback()'); }); - test('equality is by value', () { - expect( - const BeamPlayback(active: false), - const BeamPlayback(active: false), - ); - expect( - const BeamPlayback(active: false).hashCode, - const BeamPlayback(active: false).hashCode, - ); - expect( - const BeamPlayback(active: false), - isNot(const BeamPlayback(active: true)), - ); + test('cssEase is the web ease curve', () { + expect(BeamPlayback.cssEase, const Cubic(0.25, 0.1, 0.25, 1)); + expect(BeamPlayback.cssEase.transform(0), 0); + expect(BeamPlayback.cssEase.transform(1), 1); }); }); - test('the playback-only fields follow the inherit contract', () { - const base = BeamPlayback( - pauseWhenOffscreen: false, - fadeCurve: BeamPlayback.cssEase, - debugFrozenAt: Duration(milliseconds: 1300), - ); - final merged = base.merge( - const BeamPlayback(debugFrozenAt: Duration(seconds: 2)), - ); - expect(merged.pauseWhenOffscreen, isFalse, reason: 'null inherits'); - expect(merged.fadeCurve, BeamPlayback.cssEase); - expect(merged.debugFrozenAt, const Duration(seconds: 2)); - - final copy = base.copyWith(active: true); - expect(copy.pauseWhenOffscreen, isFalse); - expect(copy.fadeCurve, BeamPlayback.cssEase); - expect(copy.debugFrozenAt, const Duration(milliseconds: 1300)); - }); - - test('every playback-only field is part of the value', () { - const base = BeamPlayback(); - const variants = [ - BeamPlayback(pauseWhenOffscreen: false), - BeamPlayback(fadeCurve: BeamPlayback.cssEase), - BeamPlayback(debugFrozenAt: Duration(seconds: 1)), - ]; - for (final variant in variants) { - expect(variant, isNot(base), reason: '$variant'); - expect(variant.hashCode, isNot(base.hashCode), reason: '$variant'); - } - expect( - const BeamPlayback(debugFrozenAt: Duration(seconds: 1)), - const BeamPlayback(debugFrozenAt: Duration(seconds: 1)), - ); - expect( - const BeamPlayback(debugFrozenAt: Duration(seconds: 1)), - isNot(const BeamPlayback(debugFrozenAt: Duration(seconds: 2))), - ); - }); - - test('toString lists the playback-only fields', () { - expect( - const BeamPlayback( - pauseWhenOffscreen: false, - debugFrozenAt: Duration(milliseconds: 1300), - ).toString(), - 'BeamPlayback(pauseWhenOffscreen: false, ' - 'debugFrozenAt: 0:00:01.300000)', - ); - }); - - test('cssEase is the web easing, and compares by value', () { - expect(BeamPlayback.cssEase, const Cubic(0.25, 0.1, 0.25, 1)); - expect(BeamPlayback.cssEase.transform(0), 0); - expect(BeamPlayback.cssEase.transform(1), 1); - }); - group('BeamRepeat', () { test('forever carries no cycle count', () { expect(const BeamRepeat.forever().cycles, isNull); expect(const BeamRepeat.forever().toString(), 'BeamRepeat.forever()'); }); - test('once is one cycle', () { + test('once is a count of one', () { expect(const BeamRepeat.once().cycles, 1); - expect(const BeamRepeat.once(), const BeamRepeat.count(1)); + final one = BeamRepeat.count(int.parse('1')); + expect(const BeamRepeat.once(), one); + expect(const BeamRepeat.once().hashCode, one.hashCode); }); - test('count keeps its cycle count and rejects zero', () { + test('count keeps its cycles and rejects fewer than one', () { expect(const BeamRepeat.count(4).cycles, 4); expect(const BeamRepeat.count(4).toString(), 'BeamRepeat.count(4)'); - expect(() => BeamRepeat.count(0), throwsAssertionError); - expect(() => BeamRepeat.count(-1), throwsAssertionError); + expect(() => BeamRepeat.count(int.parse('0')), throwsAssertionError); + expect(() => BeamRepeat.count(int.parse('-1')), throwsAssertionError); }); test('equality is by cycle count', () { - expect(const BeamRepeat.count(2), const BeamRepeat.count(2)); + expect(const BeamRepeat.count(2), BeamRepeat.count(int.parse('2'))); expect( const BeamRepeat.count(2).hashCode, - const BeamRepeat.count(2).hashCode, + BeamRepeat.count(int.parse('2')).hashCode, ); expect(const BeamRepeat.count(2), isNot(const BeamRepeat.count(3))); expect(const BeamRepeat.count(2), isNot(const BeamRepeat.forever())); - expect(const BeamRepeat.forever(), const BeamRepeat.forever()); + expect(const BeamRepeat.forever(), BeamRepeat.forever()); }); }); - group('BeamPathContour', () { - Path rectBuilder(Rect rect) => Path()..addRect(rect); - - test('build delegates to the builder', () { - const rect = Rect.fromLTWH(0, 0, 10, 20); - final contour = BeamPathContour(rectBuilder, key: 'rect'); - expect(contour.build(rect).getBounds(), rect); - }); - - test('equality is by key, not by builder identity', () { - expect( - BeamPathContour((rect) => Path()..addRect(rect), key: 'rect'), - BeamPathContour((rect) => Path()..addOval(rect), key: 'rect'), - reason: 'two closures are never equal; the key is the value', - ); - expect( - BeamPathContour(rectBuilder, key: 'rect').hashCode, - BeamPathContour(rectBuilder, key: 'rect').hashCode, - ); - expect( - BeamPathContour(rectBuilder, key: 'rect'), - isNot(BeamPathContour(rectBuilder, key: 'oval')), - ); - }); - - test('a record key compares by its fields', () { - expect( - BeamPathContour(rectBuilder, key: ('notch', 12.0)), - BeamPathContour(rectBuilder, key: ('notch', 12.0)), - ); - expect( - BeamPathContour(rectBuilder, key: ('notch', 12.0)), - isNot(BeamPathContour(rectBuilder, key: ('notch', 13.0))), - ); - }); - - test('toString names the key', () { - expect( - BeamPathContour(rectBuilder, key: 'oval').toString(), - 'BeamPathContour(oval)', - ); + group('validateSpeed', () { + test('passes a finite positive rate through', () { + expect(validateSpeed(1, 'speed'), 1); + expect(validateSpeed(0.25, 'speed'), 0.25); + }); + + test('rejects zero, negative, NaN, and infinite rates', () { + for (final bad in [ + 0.0, + -1.0, + double.nan, + double.infinity, + double.negativeInfinity, + ]) { + expect( + () => validateSpeed(bad, 'speed'), + throwsArgumentError, + reason: '$bad', + ); + } }); }); - group('BorderBeamThemeData', () { - test('merge composes each slot field by field', () { - const outer = BorderBeamThemeData( - style: BeamStyle(colors: BeamColors.ocean, strength: 0.5), - timing: BeamTiming(cycle: Duration(seconds: 4)), - ); - const inner = BorderBeamThemeData( - style: BeamStyle(strength: 0.9), - shape: BeamShape(superellipse: true), - ); - final merged = outer.merge(inner); - expect(merged.style?.colors, BeamColors.ocean, reason: 'outer survives'); - expect(merged.style?.strength, 0.9, reason: 'inner wins'); - expect(merged.shape?.superellipse, isTrue); - expect(merged.timing?.cycle, const Duration(seconds: 4)); - expect(merged.playback, isNull); - }); - - test('merge takes the argument slot when the receiver has none', () { - const inner = BorderBeamThemeData(playback: BeamPlayback(active: false)); - expect( - const BorderBeamThemeData().merge(inner).playback, - const BeamPlayback(active: false), - ); - }); - - test('merge(null) returns the receiver unchanged', () { - const data = BorderBeamThemeData(shape: BeamShape(borderWidth: 3)); - expect(data.merge(null), data); - }); - - test('copyWith and equality are by value', () { - const data = BorderBeamThemeData(style: BeamStyle(hueBase: 5)); - expect( - data.copyWith(shape: const BeamShape(borderWidth: 2)), - const BorderBeamThemeData( - style: BeamStyle(hueBase: 5), - shape: BeamShape(borderWidth: 2), - ), - ); - expect( - data.hashCode, - const BorderBeamThemeData(style: BeamStyle(hueBase: 5)).hashCode, - ); - expect(data, isNot(const BorderBeamThemeData())); + group('validateRepeat', () { + // A count below one cannot be built in a debug run (the constructor + // asserts first), so only the passing paths are reachable here. + test('passes the budget through', () { + expect(validateRepeat(null), isNull); + expect(validateRepeat(const BeamRepeat.forever()), isNull); + expect(validateRepeat(const BeamRepeat.once()), 1); + expect(validateRepeat(const BeamRepeat.count(5)), 5); }); }); } diff --git a/test/painting/beam_perimeter_test.dart b/test/painting/beam_perimeter_test.dart deleted file mode 100644 index 22e2f63..0000000 --- a/test/painting/beam_perimeter_test.dart +++ /dev/null @@ -1,132 +0,0 @@ -import 'dart:math' as math; - -import 'package:flutter/painting.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam/src/painting/ring_geometry.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - const rect = Rect.fromLTWH(0, 0, 200, 100); - const radii = BorderRadius.all(Radius.circular(20)); - - BeamPerimeter rounded({bool superellipse = false}) { - final geometry = BeamRingGeometry( - rect: rect, - radius: radii, - borderWidth: 1, - useSuperellipse: superellipse, - ); - return geometry.perimeter; - } - - test('measures and aligns a rounded rectangle clockwise', () { - final perimeter = rounded(); - final analytic = 2 * (160 + 60) + 2 * math.pi * 20; - expect(perimeter.length, closeTo(analytic, analytic * 0.01)); - expect(perimeter.pointAt(0), within(distance: 0.5, from: rect.topCenter)); - expect( - perimeter.pointAt(0.5), - within(distance: 0.5, from: rect.bottomCenter), - ); - expect(perimeter.pointAt(0.25).dx, closeTo(rect.right, 1)); - expect(perimeter.pointAt(0.25).dy, inInclusiveRange(20, 80)); - expect(perimeter.pointAt(0.75).dx, closeTo(rect.left, 1)); - expect(perimeter.tangentAt(0).dx, closeTo(1, 0.02)); - expect(perimeter.normalAt(0).dy, closeTo(-1, 0.02)); - expect(perimeter.offsetPointAt(0, 5).dy, closeTo(5, 0.5)); - }); - - test('resolves straight edges and corner arcs', () { - final perimeter = rounded(); - expect(perimeter.fractionOfEdge(BeamEdge.right, 0.5), closeTo(0.25, 0.01)); - expect(perimeter.fractionOfEdge(BeamEdge.bottom, 0.5), closeTo(0.5, 0.01)); - expect(perimeter.fractionOfEdge(BeamEdge.left, 0.5), closeTo(0.75, 0.01)); - final corner = perimeter.fractionOfCorner(BeamCorner.topRight, 0.5); - final topEnd = perimeter.fractionOfEdge(BeamEdge.top, 1); - final rightStart = perimeter.fractionOfEdge(BeamEdge.right, 0); - expect(corner, greaterThan(topEnd)); - expect(corner, lessThan(rightStart)); - }); - - test('nearestFraction recovers sampled points', () { - final perimeter = rounded(); - for (final fraction in [0.03, 0.2, 0.49, 0.72, 0.94]) { - expect( - perimeter.nearestFraction(perimeter.pointAt(fraction)), - closeTo(fraction, 0.002), - ); - } - }); - - test('alignment works for square, wide, and superellipse contours', () { - final squareRect = const Rect.fromLTWH(10, 20, 100, 100); - final square = BeamPerimeter( - Path()..addRRect( - RRect.fromRectAndRadius(squareRect, const Radius.circular(12)), - ), - squareRect, - radii: const BorderRadius.all(Radius.circular(12)), - ); - expect( - square.pointAt(0), - within(distance: 0.5, from: squareRect.topCenter), - ); - expect(rounded().pointAt(0.25).dx, closeTo(rect.right, 1)); - expect( - rounded(superellipse: true).pointAt(0), - within(distance: 0.7, from: rect.topCenter), - ); - }); - - test('counter-clockwise source paths are flipped', () { - final path = Path() - ..moveTo(rect.topCenter.dx, rect.topCenter.dy) - ..lineTo(rect.left, rect.top) - ..lineTo(rect.left, rect.bottom) - ..lineTo(rect.right, rect.bottom) - ..lineTo(rect.right, rect.top) - ..close(); - final perimeter = BeamPerimeter(path, rect, radii: BorderRadius.zero); - expect(perimeter.pointAt(0), within(distance: 0.5, from: rect.topCenter)); - expect(perimeter.tangentAt(0).dx, closeTo(1, 0.01)); - expect(perimeter.pointAt(0.25).dx, closeTo(rect.right, 1)); - }); - - test('bands select lower and wrapping upper halves', () { - final perimeter = rounded(); - final lower = perimeter.band(from: 0.25, to: 0.75, inward: 4, outward: 4); - final upper = perimeter.band(from: 0.75, to: 0.25, inward: 4, outward: 4); - expect(lower.getBounds().top, greaterThan(40)); - expect(lower.getBounds().bottom, greaterThan(rect.bottom)); - expect(upper.getBounds().top, lessThan(rect.top)); - expect(upper.getBounds().bottom, lessThan(60)); - }); - - test('weightAt feathers, wraps, and clamps overlapping ramps', () { - final perimeter = rounded(); - double weight(double f) => - perimeter.weightAt(f, from: 0.25, to: 0.75, featherFraction: 0.1); - expect(weight(0.1), 0); - expect(weight(0.5), 1); - expect(weight(0.3), closeTo(0.5, 1e-9)); - expect(perimeter.weightAt(0, from: 0.75, to: 0.25, featherFraction: 0), 1); - expect( - perimeter.weightAt(0.225, from: 0.2, to: 0.3, featherFraction: 0.2), - closeTo(0.5, 1e-9), - ); - }); - - test('zero-length paths are safe', () { - final perimeter = BeamPerimeter(Path(), rect); - expect(perimeter.length, 0); - expect(perimeter.pointAt(0.5), rect.topCenter); - expect(perimeter.tangentAt(0.5), Offset.zero); - expect(perimeter.normalAt(0.5), Offset.zero); - expect(perimeter.nearestFraction(const Offset(20, 20)), 0); - expect(perimeter.featherFractionFor(20), 0); - expect( - perimeter.band(from: 0, to: 1, inward: 1, outward: 1).getBounds().isEmpty, - isTrue, - ); - }); -} diff --git a/test/painting/boundary_test.dart b/test/painting/boundary_test.dart deleted file mode 100644 index dee5333..0000000 --- a/test/painting/boundary_test.dart +++ /dev/null @@ -1,220 +0,0 @@ -import 'dart:ui' as ui; - -import 'package:flutter/material.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; -import 'package:flutter_test/flutter_test.dart'; - -/// Degenerate geometry and out-of-range parameters. Everything here is a -/// value a consumer can legitimately pass (or a layout can legitimately -/// produce), so no combination may throw — and `strength: 0` must paint -/// literally nothing. -void main() { - const normal = ui.Size(350, 140); - // Post fade-in samples spread over the cycle; the line variant paints - // nothing at the cycle edges, so pixel checks aggregate over all of them. - const samples = [0.0, 0.5, 1.3, 7.9]; - - BeamConfig configFor( - BeamVariant variant, { - double? borderRadius, - double? borderWidth, - double strength = 1, - double hueRange = 30, - bool staticColors = false, - Duration? cycleDuration, - ui.Brightness brightness = ui.Brightness.dark, - }) => BeamConfig.resolve( - variant: variant, - palette: BeamColors.colorful.resolve(), - brightness: brightness, - style: BeamStyle( - strength: strength, - hueRange: hueRange, - staticColors: staticColors, - ), - shape: BeamShape( - radius: borderRadius == null ? null : BorderRadius.circular(borderRadius), - borderWidth: borderWidth, - ), - timing: BeamTiming(cycle: cycleDuration), - ); - - /// Runs both passes across the samples, letting any exception escape. - void paintFrames(BeamVariant variant, BeamConfig config, ui.Size size) { - final resolver = BeamPhaseResolver(config); - final strategy = strategyFor(variant); - for (final t in samples) { - final recorder = ui.PictureRecorder(); - final canvas = ui.Canvas(recorder); - final phases = resolver.sample(t, 1); - strategy.paintBehind(canvas, size, config, phases); - strategy.paintAbove(canvas, size, config, phases); - recorder.endRecording().dispose(); - } - } - - /// Whether any sample of the requested pass leaves a non-transparent pixel - /// inside [size]. - Future paintsPixels( - BeamVariant variant, - BeamConfig config, { - ui.Size size = normal, - bool behind = true, - bool above = true, - }) async { - final resolver = BeamPhaseResolver(config); - final strategy = strategyFor(variant); - for (final t in samples) { - final recorder = ui.PictureRecorder(); - final canvas = ui.Canvas(recorder); - final phases = resolver.sample(t, 1); - if (behind) strategy.paintBehind(canvas, size, config, phases); - if (above) strategy.paintAbove(canvas, size, config, phases); - final picture = recorder.endRecording(); - final image = await picture.toImage( - size.width.toInt(), - size.height.toInt(), - ); - final bytes = await image.toByteData(format: ui.ImageByteFormat.rawRgba); - picture.dispose(); - image.dispose(); - for (var i = 3; i < bytes!.lengthInBytes; i += 4) { - if (bytes.getUint8(i) != 0) return true; - } - } - return false; - } - - group('degenerate sizes', () { - const sizes = { - 'zero': ui.Size.zero, - '1x1': ui.Size(1, 1), - 'wide sliver': ui.Size(2000, 2), - 'tall sliver': ui.Size(2, 2000), - }; - for (final variant in BeamVariant.values) { - for (final MapEntry(key: name, value: size) in sizes.entries) { - test('$variant paints a $name box', () { - paintFrames(variant, configFor(variant), size); - }); - } - } - }); - - group('geometry parameters', () { - for (final variant in BeamVariant.values) { - test('$variant: radius larger than the shortest side', () async { - // 400 > 140: the ring geometry clamps it to half the short side. - final config = configFor(variant, borderRadius: 400); - paintFrames(variant, config, normal); - expect(await paintsPixels(variant, config), isTrue); - }); - - test('$variant: border wider than the radius', () async { - final config = configFor(variant, borderRadius: 4, borderWidth: 40); - paintFrames(variant, config, normal); - expect(await paintsPixels(variant, config), isTrue); - }); - - test('$variant: zero border width', () async { - // The ring collapses to an empty path — stroke layers paint nothing, - // but the inner/glow layers still do. - final config = configFor(variant, borderWidth: 0); - paintFrames(variant, config, normal); - expect(await paintsPixels(variant, config), isTrue); - }); - } - }); - - group('animation parameters', () { - for (final variant in BeamVariant.values) { - test('$variant: a 1ms cycle', () { - paintFrames( - variant, - configFor(variant, cycleDuration: const Duration(milliseconds: 1)), - normal, - ); - }); - - test('$variant: a one-hour cycle', () { - paintFrames( - variant, - configFor(variant, cycleDuration: const Duration(hours: 1)), - normal, - ); - }); - - test('$variant: hueRange 0', () async { - final config = configFor(variant, hueRange: 0); - paintFrames(variant, config, normal); - expect(await paintsPixels(variant, config), isTrue); - }); - - test('$variant: staticColors', () async { - final config = configFor(variant, staticColors: true); - paintFrames(variant, config, normal); - expect(await paintsPixels(variant, config), isTrue); - }); - } - }); - - group('strength 0', () { - for (final variant in BeamVariant.values) { - test('$variant paints nothing at all', () async { - final config = configFor(variant, strength: 0); - paintFrames(variant, config, normal); - expect( - await paintsPixels(variant, config, above: false), - isFalse, - reason: 'the behind-child pass must be fully suppressed', - ); - expect( - await paintsPixels(variant, config, behind: false), - isFalse, - reason: 'the above-child pass must be fully suppressed', - ); - }); - } - }); - - group('degenerate layouts', () { - Widget host(Widget child) => MaterialApp( - theme: ThemeData(brightness: Brightness.dark), - home: Scaffold(body: Center(child: child)), - ); - - testWidgets('a beam collapsed to zero size renders', (tester) async { - await tester.pumpWidget( - host( - const SizedBox.shrink( - child: BorderBeam.rotate(child: SizedBox.shrink()), - ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - expect(tester.takeException(), isNull); - }); - - testWidgets('a beam around a zero-height child in a Column renders', ( - tester, - ) async { - await tester.pumpWidget( - host( - Column( - mainAxisSize: MainAxisSize.min, - children: const [ - BorderBeam.rotate(child: SizedBox(width: 120, height: 0)), - ], - ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - expect(tester.takeException(), isNull); - }); - }); -} diff --git a/test/painting/color_matrix_test.dart b/test/painting/color_matrix_test.dart deleted file mode 100644 index c3cf52a..0000000 --- a/test/painting/color_matrix_test.dart +++ /dev/null @@ -1,252 +0,0 @@ -import 'package:flutter/painting.dart'; -import 'package:flutter_border_beam/src/painting/color_matrix.dart'; -import 'package:flutter_border_beam/src/painting/ring_geometry.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('BeamColorMatrix', () { - test('identity is a no-op', () { - final m = BeamColorMatrix.identity(); - expect(m.isIdentity, isTrue); - const c = Color(0x80336699); - final out = m.transform(c); - expect(out.a, closeTo(c.a, 1e-6)); - expect(out.r, closeTo(c.r, 1e-6)); - expect(out.g, closeTo(c.g, 1e-6)); - expect(out.b, closeTo(c.b, 1e-6)); - }); - - test('hue-rotate(0) is identity, hue-rotate(360) round-trips', () { - final zero = BeamColorMatrix.beamFilter( - hueDegrees: 0, - brightness: 1, - saturation: 1, - ); - expect(zero.isIdentity, isTrue); - final full = BeamColorMatrix.beamFilter( - hueDegrees: 360, - brightness: 1, - saturation: 1, - ); - const c = Color(0xFFFF3264); - final out = full.transform(c); - expect(out.r, closeTo(c.r, 1e-4)); - expect(out.g, closeTo(c.g, 1e-4)); - expect(out.b, closeTo(c.b, 1e-4)); - }); - - test('hue-rotate(180) inverts hue but preserves luminance-ish gray', () { - final m = BeamColorMatrix.beamFilter( - hueDegrees: 180, - brightness: 1, - saturation: 1, - ); - // Pure gray is hue-invariant. - const gray = Color(0xFF808080); - final out = m.transform(gray); - expect(out.r, closeTo(gray.r, 1e-3)); - expect(out.g, closeTo(gray.g, 1e-3)); - expect(out.b, closeTo(gray.b, 1e-3)); - }); - - test('brightness scales channels, saturation(0) grays out', () { - final bright = BeamColorMatrix.beamFilter( - hueDegrees: 0, - brightness: 2, - saturation: 1, - ); - const c = Color.fromRGBO(50, 100, 20, 1.0); - final out = bright.transform(c); - expect(out.r, closeTo(c.r * 2, 1e-6)); - expect(out.g, closeTo(c.g * 2, 1e-6)); - - final gray = BeamColorMatrix.beamFilter( - hueDegrees: 0, - brightness: 1, - saturation: 0, - ); - final g = gray.transform(const Color(0xFFFF0000)); - expect(g.r, closeTo(g.g, 1e-6)); - expect(g.g, closeTo(g.b, 1e-6)); - // Red's luminance weight. - expect(g.r, closeTo(0.213, 1e-3)); - }); - - test('alpha passes through untouched', () { - final m = BeamColorMatrix.beamFilter( - hueDegrees: 90, - brightness: 1.5, - saturation: 1.2, - ); - const c = Color(0x40FF8040); - expect(m.transform(c).a, closeTo(c.a, 1e-6)); - }); - }); - - group('BeamRingGeometry', () { - test('ring excludes the content box for rounded rects', () { - final g = BeamRingGeometry( - rect: const Rect.fromLTWH(0, 0, 100, 60), - radius: BorderRadius.circular(16), - borderWidth: 1, - useSuperellipse: false, - ); - // Edge midpoint inside the 1px ring. - expect(g.ring.contains(const Offset(50, 0.5)), isTrue); - // Center is inside the content box, so excluded from the ring. - expect(g.ring.contains(const Offset(50, 30)), isFalse); - expect(g.ring.contains(const Offset(50, 2)), isFalse); - // Outside the shape entirely. - expect(g.ring.contains(const Offset(-1, -1)), isFalse); - }); - - test('superellipse ring behaves the same', () { - final g = BeamRingGeometry( - rect: const Rect.fromLTWH(0, 0, 100, 60), - radius: BorderRadius.circular(16), - borderWidth: 1, - useSuperellipse: true, - ); - expect(g.ring.contains(const Offset(50, 0.5)), isTrue); - expect(g.ring.contains(const Offset(50, 30)), isFalse); - // Corner exterior stays outside; interior near the edge stays in the - // outer contour. (Sub-pixel squircle-vs-arc differences are covered by - // golden tests, not containment probing.) - expect(g.outer.contains(const Offset(1, 1)), isFalse); - expect(g.outer.contains(const Offset(8, 8)), isTrue); - }); - - test('a box thinner than twice the border has no content box', () { - for (final superellipse in [false, true]) { - final g = BeamRingGeometry( - rect: const Rect.fromLTWH(0, 0, 1, 1), - radius: BorderRadius.circular(16), - borderWidth: 1, - useSuperellipse: superellipse, - ); - expect(g.inner.getBounds().isEmpty, isTrue); - // Nothing is carved out: the ring is the whole box. The ring is - // `Path.combine`d rather than added directly, and combining - // re-flattens the contour — a superellipse corner comes back a few - // ten-thousandths of a pixel off the contour it was built from, by a - // margin that varies with the engine's flattening tolerance. Compare - // edge by edge with a tolerance instead of asking two Rects to be - // bit-identical. - final ring = g.ring.getBounds(); - final outer = g.outer.getBounds(); - expect(ring.left, closeTo(outer.left, 1e-3)); - expect(ring.top, closeTo(outer.top, 1e-3)); - expect(ring.right, closeTo(outer.right, 1e-3)); - expect(ring.bottom, closeTo(outer.bottom, 1e-3)); - expect(g.ring.contains(const Offset(0.5, 0.5)), isTrue); - } - }); - - test('an empty box has no contours at all', () { - for (final rect in const [ - Rect.zero, - Rect.fromLTWH(0, 0, 40, 0), - Rect.fromLTWH(0, 0, 0, 40), - ]) { - final g = BeamRingGeometry( - rect: rect, - radius: BorderRadius.circular(16), - borderWidth: 1, - useSuperellipse: false, - ); - expect(g.outer.getBounds().isEmpty, isTrue); - expect(g.inner.getBounds().isEmpty, isTrue); - expect(g.ring.getBounds().isEmpty, isTrue); - expect( - g.shapeContour(rect, BorderRadius.circular(16)).getBounds().isEmpty, - isTrue, - ); - } - }); - - test('radius clamps to half the shortest side', () { - final g = BeamRingGeometry( - rect: const Rect.fromLTWH(0, 0, 40, 10), - radius: BorderRadius.circular(32), - borderWidth: 1, - useSuperellipse: false, - ); - // Must not throw and must produce a valid ring. - expect(g.ring.getBounds().isEmpty, isFalse); - }); - - test('per-corner radii round only the corners they name', () { - final g = BeamRingGeometry( - rect: const Rect.fromLTWH(0, 0, 100, 60), - radius: const BorderRadius.only(topLeft: Radius.circular(20)), - borderWidth: 1, - useSuperellipse: false, - ); - // The rounded corner cuts its own square corner away… - expect(g.outer.contains(const Offset(1, 1)), isFalse); - // …while the other three stay right angles. - expect(g.outer.contains(const Offset(99, 1)), isTrue); - expect(g.outer.contains(const Offset(1, 59)), isTrue); - expect(g.outer.contains(const Offset(99, 59)), isTrue); - }); - - test('adjacent radii that overflow a side scale down together', () { - // 40 + 40 across a 60px-wide box: both top corners scale by 60/80. - final g = BeamRingGeometry( - rect: const Rect.fromLTWH(0, 0, 60, 200), - radius: const BorderRadius.vertical(top: Radius.circular(40)), - borderWidth: 1, - useSuperellipse: false, - ); - // At the scaled radius (30) the top edge is straight from x=30 on… - expect(g.outer.contains(const Offset(30, 0.5)), isTrue); - // …the corner is still cut away… - expect(g.outer.contains(const Offset(1, 1)), isFalse); - // …and the bottom corners were never rounded. - expect(g.outer.contains(const Offset(1, 199)), isTrue); - }); - - test('a stadium radius rounds to half the shortest side', () { - const rect = Rect.fromLTWH(0, 0, 120, 40); - final stadium = BeamRingGeometry( - rect: rect, - radius: const BorderRadius.all(Radius.circular(double.infinity)), - borderWidth: 1, - useSuperellipse: false, - ); - final pill = BeamRingGeometry( - rect: rect, - radius: BorderRadius.circular(20), - borderWidth: 1, - useSuperellipse: false, - ); - // The same shape as an explicit half-shortest-side radius. - expect(stadium.outer.getBounds(), pill.outer.getBounds()); - for (final probe in const [ - Offset(2, 2), - Offset(20, 0.5), - Offset(60, 0.5), - Offset(118, 38), - ]) { - expect( - stadium.outer.contains(probe), - pill.outer.contains(probe), - reason: 'probe $probe', - ); - } - }); - - test('a stadium square rounds to a circle', () { - final g = BeamRingGeometry( - rect: const Rect.fromLTWH(0, 0, 40, 40), - radius: const BorderRadius.all(Radius.circular(double.infinity)), - borderWidth: 1, - useSuperellipse: false, - ); - // Inside the inscribed circle, outside the square's corners. - expect(g.outer.contains(const Offset(20, 1)), isTrue); - expect(g.outer.contains(const Offset(2, 2)), isFalse); - expect(g.outer.contains(const Offset(38, 38)), isFalse); - }); - }); -} diff --git a/test/painting/paint_smoke_test.dart b/test/painting/paint_smoke_test.dart deleted file mode 100644 index ff75d52..0000000 --- a/test/painting/paint_smoke_test.dart +++ /dev/null @@ -1,72 +0,0 @@ -import 'dart:ui' as ui; - -import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/models/beam_colors.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/models/beam_shape.dart'; -import 'package:flutter_border_beam/src/models/beam_variant.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - // Every variant × brightness × palette × shape paints without throwing and - // produces pixels, sampled across the animation cycle. This catches shader - // stop mismatches, invalid opacities, and geometry regressions cheaply; - // exact appearance is covered by goldens. - const size = ui.Size(350, 140); - final palettes = { - 'colorful': BeamColors.colorful, - 'mono': BeamColors.mono, - 'ocean': BeamColors.ocean, - 'sunset': BeamColors.sunset, - 'custom': const BeamColors.custom([ui.Color(0xFFFF0080)]), - }; - - for (final variant in BeamVariant.values) { - for (final brightness in ui.Brightness.values) { - for (final MapEntry(key: name, value: colors) in palettes.entries) { - for (final superellipse in [false, true]) { - test('$variant/$brightness/$name' - '${superellipse ? '/squircle' : ''} paints', () async { - final config = BeamConfig.resolve( - variant: variant, - palette: colors.resolve(), - brightness: brightness, - shape: BeamShape(superellipse: superellipse), - ); - final resolver = BeamPhaseResolver(config); - final strategy = strategyFor(variant); - // The line variant paints nothing at cycle edges (edge-fade - // keyframe is 0 there), so pixels are required across the - // samples, not at each one. - var anyPixels = false; - for (final t in [0.0, 0.5, 1.3, 7.9]) { - final recorder = ui.PictureRecorder(); - final canvas = ui.Canvas(recorder); - final phases = resolver.sample(t, 1); - strategy.paintBehind(canvas, size, config, phases); - strategy.paintAbove(canvas, size, config, phases); - final picture = recorder.endRecording(); - final image = await picture.toImage( - size.width.toInt(), - size.height.toInt(), - ); - final bytes = await image.toByteData( - format: ui.ImageByteFormat.rawRgba, - ); - for (var i = 3; i < bytes!.lengthInBytes; i += 4) { - if (bytes.getUint8(i) != 0) { - anyPixels = true; - break; - } - } - } - // The beam must produce non-transparent pixels somewhere in the - // cycle. - expect(anyPixels, isTrue, reason: 'no pixels painted'); - }); - } - } - } - } -} diff --git a/test/painting/ring_geometry_test.dart b/test/painting/ring_geometry_test.dart deleted file mode 100644 index e8cba59..0000000 --- a/test/painting/ring_geometry_test.dart +++ /dev/null @@ -1,420 +0,0 @@ -import 'dart:math' as math; -import 'dart:ui' show Brightness; - -import 'package:flutter/painting.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/painting/ring_geometry.dart'; -import 'package:flutter_border_beam/src/painting/variant_strategy.dart'; -import 'package:flutter_test/flutter_test.dart'; - -/// Per-corner ring geometry: the beam contour takes a full [BorderRadius], -/// clamps it the way `RRect.scaleRadii` does, resolves an infinite radius -/// ([BeamShape.stadium]) to half the shortest side, and derives the inner -/// contour by shrinking every corner by the border width. -/// -/// Corner size is probed rather than read back: each test walks inward along -/// a corner's 45° diagonal and finds where the path starts containing -/// points. For a circular corner of radius r that entry sits at -/// `r * (sqrt2 - 1)` — the distance from the corner to the arc — which makes -/// the probe an exact measurement of the radius the geometry actually used. -void main() { - // Distance from the corner to the shape's boundary, along the inward 45° - // diagonal. - double diagonalEntry(Path path, Offset corner, Offset inward, double reach) { - expect( - path.contains(corner + inward * reach), - isTrue, - reason: 'the probe must end inside the shape', - ); - var outside = 0.0; - var inside = reach; - for (var i = 0; i < 60; i++) { - final mid = (outside + inside) / 2; - if (path.contains(corner + inward * mid)) { - inside = mid; - } else { - outside = mid; - } - } - return inside; - } - - // The four corners as (point, inward unit vector) pairs. - final diagonal = 1 / math.sqrt2; - Map cornersOf(Rect r) => { - 'topLeft': (r.topLeft, Offset(diagonal, diagonal)), - 'topRight': (r.topRight, Offset(-diagonal, diagonal)), - 'bottomLeft': (r.bottomLeft, Offset(diagonal, -diagonal)), - 'bottomRight': (r.bottomRight, Offset(-diagonal, -diagonal)), - }; - - // What `diagonalEntry` reads back for a circular corner of radius [r]. - double circularEntry(double r) => r * (math.sqrt2 - 1); - - BeamRingGeometry geometry( - Rect rect, - BorderRadius radius, { - double borderWidth = 1, - bool superellipse = false, - }) => BeamRingGeometry( - rect: rect, - radius: radius, - borderWidth: borderWidth, - useSuperellipse: superellipse, - ); - - // How far a flattened `RSuperellipse` contour may sit from the rect it was - // built on. The engine approximates the squircle with curves rather than - // tracing it exactly, and that approximation differs between Flutter 3.35 - // (this package's floor) and current stable by up to 0.12px. Two tenths - // covers that variation; the rrect family stays pinned to a hundredth. - const superellipseSlack = 0.2; - - void expectBounds(Path path, Rect rect, {double tolerance = 0.01}) { - final bounds = path.getBounds(); - expect(bounds.left, closeTo(rect.left, tolerance)); - expect(bounds.top, closeTo(rect.top, tolerance)); - expect(bounds.right, closeTo(rect.right, tolerance)); - expect(bounds.bottom, closeTo(rect.bottom, tolerance)); - } - - group('per-corner radii', () { - const rect = Rect.fromLTWH(0, 0, 200, 100); - const radius = BorderRadius.only( - topLeft: Radius.circular(40), - topRight: Radius.zero, - bottomLeft: Radius.circular(10), - bottomRight: Radius.circular(40), - ); - - for (final superellipse in [false, true]) { - final family = superellipse ? 'superellipse' : 'circular'; - - test('$family: the outer contour still spans the whole rect', () { - expectBounds( - geometry(rect, radius, superellipse: superellipse).outer, - rect, - tolerance: superellipse ? superellipseSlack : 0.01, - ); - }); - - test('$family: a rounded corner drops a point a square corner keeps', () { - final outer = geometry(rect, radius, superellipse: superellipse).outer; - // The same offset from each corner: cut away where the radius is - // large, kept where the corner is square. - expect( - outer.contains(const Offset(3, 3)), - isFalse, - reason: 'inside the 40px topLeft corner', - ); - expect( - outer.contains(const Offset(197, 3)), - isTrue, - reason: 'the topRight corner is square', - ); - expect( - outer.contains(const Offset(197, 97)), - isFalse, - reason: 'inside the 40px bottomRight corner', - ); - expect( - outer.contains(const Offset(100, 50)), - isTrue, - reason: 'the middle is always inside', - ); - }); - } - - test('circular: every corner measures the radius it was given', () { - final outer = geometry(rect, radius).outer; - final corners = cornersOf(rect); - double entryAt(String corner) { - final (point, inward) = corners[corner]!; - return diagonalEntry(outer, point, inward, 50); - } - - expect(entryAt('topLeft'), closeTo(circularEntry(40), 0.05)); - expect(entryAt('topRight'), lessThan(0.05), reason: 'a square corner'); - expect(entryAt('bottomLeft'), closeTo(circularEntry(10), 0.05)); - expect(entryAt('bottomRight'), closeTo(circularEntry(40), 0.05)); - }); - - test('superellipse: corner size still follows the per-corner radii', () { - final outer = geometry(rect, radius, superellipse: true).outer; - final corners = cornersOf(rect); - double entryAt(String corner) { - final (point, inward) = corners[corner]!; - return diagonalEntry(outer, point, inward, 50); - } - - expect(entryAt('topRight'), lessThan(0.05), reason: 'a square corner'); - expect(entryAt('topLeft'), closeTo(entryAt('bottomRight'), 0.05)); - expect( - entryAt('topLeft'), - greaterThan(entryAt('bottomLeft')), - reason: '40px cuts deeper than 10px', - ); - }); - }); - - group('scaleRadii clamping', () { - // 80 + 40 on a 100px top edge: both scale by 100/120, keeping their 2:1 - // proportion instead of one being clipped. - const rect = Rect.fromLTWH(0, 0, 100, 100); - const radius = BorderRadius.only( - topLeft: Radius.circular(80), - topRight: Radius.circular(40), - ); - const scale = 100 / 120; - - test('matches what RRect.scaleRadii would produce', () { - final reference = RRect.fromRectAndCorners( - rect, - topLeft: const Radius.circular(80), - topRight: const Radius.circular(40), - ).scaleRadii(); - expect(reference.tlRadiusX, closeTo(80 * scale, 1e-9)); - expect(reference.trRadiusX, closeTo(40 * scale, 1e-9)); - - final outer = geometry(rect, radius).outer; - final corners = cornersOf(rect); - final (tlPoint, tlInward) = corners['topLeft']!; - final (trPoint, trInward) = corners['topRight']!; - expect( - diagonalEntry(outer, tlPoint, tlInward, 50), - closeTo(circularEntry(80 * scale), 0.05), - ); - expect( - diagonalEntry(outer, trPoint, trInward, 50), - closeTo(circularEntry(40 * scale), 0.05), - ); - }); - - test('both radii shrink by the same ratio', () { - final outer = geometry(rect, radius).outer; - final corners = cornersOf(rect); - final (tlPoint, tlInward) = corners['topLeft']!; - final (trPoint, trInward) = corners['topRight']!; - final tl = diagonalEntry(outer, tlPoint, tlInward, 50); - final tr = diagonalEntry(outer, trPoint, trInward, 50); - expect(tl / tr, closeTo(2, 0.02), reason: 'the 2:1 proportion survives'); - }); - - test('superellipse clamps too and stays inside the rect', () { - final outer = geometry(rect, radius, superellipse: true).outer; - expectBounds(outer, rect, tolerance: superellipseSlack); - final corners = cornersOf(rect); - final (tlPoint, tlInward) = corners['topLeft']!; - final (trPoint, trInward) = corners['topRight']!; - final tl = diagonalEntry(outer, tlPoint, tlInward, 50); - final tr = diagonalEntry(outer, trPoint, trInward, 50); - expect(tl, greaterThan(tr)); - expect( - tl, - lessThan(circularEntry(80) * 1.6), - reason: 'an unclamped 80px corner would cut deeper', - ); - }); - }); - - group('stadium (infinite radius)', () { - const infinite = BorderRadius.all(Radius.circular(double.infinity)); - - test('a 200x40 rect resolves to a 20px radius on every corner', () { - const rect = Rect.fromLTWH(0, 0, 200, 40); - final outer = geometry(rect, infinite).outer; - expectBounds(outer, rect); - for (final MapEntry(key: name, value: (point, inward)) in cornersOf( - rect, - ).entries) { - expect( - diagonalEntry(outer, point, inward, 20), - closeTo(circularEntry(20), 0.05), - reason: name, - ); - } - expect(outer.contains(const Offset(1, 1)), isFalse, reason: 'pill end'); - expect( - outer.contains(const Offset(100, 1)), - isTrue, - reason: 'the straight top edge', - ); - }); - - test('the radius tracks the box as it resizes', () { - const tall = Rect.fromLTWH(0, 0, 200, 100); - final corners = cornersOf(tall); - final (point, inward) = corners['topLeft']!; - expect( - diagonalEntry(geometry(tall, infinite).outer, point, inward, 60), - closeTo(circularEntry(50), 0.05), - reason: 'half the 100px short side', - ); - }); - - test('a square box comes out a circle', () { - const square = Rect.fromLTWH(0, 0, 80, 80); - final outer = geometry(square, infinite).outer; - // Every point at radius 40 from the centre is on the boundary: just - // inside is contained, just outside is not. - for (final angle in [0.0, 0.7, 1.9, 3.4, 5.2]) { - final unit = Offset(math.cos(angle), math.sin(angle)); - expect(outer.contains(const Offset(40, 40) + unit * 39), isTrue); - expect(outer.contains(const Offset(40, 40) + unit * 41), isFalse); - } - }); - - test('superellipse stadium is symmetric across all four corners', () { - const rect = Rect.fromLTWH(0, 0, 200, 40); - final outer = geometry(rect, infinite, superellipse: true).outer; - expectBounds(outer, rect, tolerance: superellipseSlack); - final entries = [ - for (final (point, inward) in cornersOf(rect).values) - diagonalEntry(outer, point, inward, 20), - ]; - for (final entry in entries) { - expect(entry, closeTo(entries.first, 0.05)); - } - expect(entries.first, greaterThan(0)); - }); - }); - - group('inner contour', () { - const rect = Rect.fromLTWH(0, 0, 200, 100); - - test('every corner shrinks by the border width', () { - const radius = BorderRadius.only( - topLeft: Radius.circular(40), - bottomRight: Radius.circular(12), - ); - final ring = geometry(rect, radius, borderWidth: 5); - final inner = rect.deflate(5); - expectBounds(ring.inner, inner); - final corners = cornersOf(inner); - final (tlPoint, tlInward) = corners['topLeft']!; - final (brPoint, brInward) = corners['bottomRight']!; - expect( - diagonalEntry(ring.inner, tlPoint, tlInward, 50), - closeTo(circularEntry(35), 0.05), - ); - expect( - diagonalEntry(ring.inner, brPoint, brInward, 50), - closeTo(circularEntry(7), 0.05), - ); - }); - - test('a corner smaller than the border width floors at square', () { - const radius = BorderRadius.all(Radius.circular(3)); - final ring = geometry(rect, radius, borderWidth: 5); - final corners = cornersOf(rect.deflate(5)); - final (point, inward) = corners['topLeft']!; - expect(diagonalEntry(ring.inner, point, inward, 20), lessThan(0.05)); - }); - - test('a box thinner than twice the border has no inner contour', () { - const sliver = Rect.fromLTWH(0, 0, 200, 8); - final ring = geometry(sliver, BorderRadius.circular(4), borderWidth: 5); - expect(ring.inner.getBounds().isEmpty, isTrue); - expect( - ring.ring.contains(const Offset(100, 4)), - isTrue, - reason: 'the ring is then the whole shape', - ); - }); - - test('the ring is the band between the two contours', () { - final ring = geometry(rect, BorderRadius.circular(16), borderWidth: 4); - expect(ring.ring.contains(const Offset(100, 2)), isTrue); - expect(ring.ring.contains(const Offset(100, 50)), isFalse); - }); - - test('an empty rect has no ring at all', () { - final ring = geometry(Rect.zero, BorderRadius.circular(8)); - expect(ring.ring.getBounds().isEmpty, isTrue); - expect(ring.outer.getBounds().isEmpty, isTrue); - }); - }); - - group('contour', () { - test('builds an arbitrary rect in the same shape family', () { - const rect = Rect.fromLTWH(0, 0, 200, 100); - final ring = geometry(rect, BorderRadius.circular(16)); - const other = Rect.fromLTWH(10, 10, 100, 60); - final path = ring.shapeContour(other, BorderRadius.circular(20)); - expectBounds(path, other); - final corners = cornersOf(other); - final (point, inward) = corners['topLeft']!; - expect( - diagonalEntry(path, point, inward, 30), - closeTo(circularEntry(20), 0.05), - ); - }); - }); - - group('segment integration', () { - const rect = Rect.fromLTWH(0, 0, 200, 100); - - for (final superellipse in [false, true]) { - test('${superellipse ? 'superellipse' : 'rrect'} band and weight', () { - final geometry = BeamRingGeometry( - rect: rect, - radius: BorderRadius.circular(20), - borderWidth: 2, - useSuperellipse: superellipse, - segment: BeamSegment.bottomHalf, - ); - expect(geometry.segmentRange?.from, closeTo(0.25, 0.02)); - expect(geometry.segmentRange?.to, closeTo(0.75, 0.02)); - expect( - geometry.segmentBand(inward: 3, outward: 3).getBounds().top, - greaterThan(35), - ); - expect(geometry.segmentWeightAt(0.5), 1); - expect(geometry.segmentWeightAt(0), 0); - }); - } - - test('no segment leaves band and weight neutral', () { - final geometry = BeamRingGeometry( - rect: rect, - radius: BorderRadius.circular(20), - borderWidth: 2, - useSuperellipse: false, - ); - expect(geometry.segmentRange, isNull); - expect(geometry.segmentBand(inward: 2, outward: 2).getBounds(), rect); - expect(geometry.segmentWeightAt(0.9), 1); - }); - }); - - group('beamGeometry memo', () { - BeamConfig config({double radius = 12}) => BeamConfig.resolve( - variant: BeamVariant.rotate, - palette: BeamColors.colorful.resolve(), - brightness: Brightness.dark, - shape: BeamShape.circular(radius, segment: BeamSegment.bottomHalf), - ); - - test('equal rect and config return the identical geometry', () { - const rect = Rect.fromLTWH(0, 0, 180, 80); - final first = beamGeometry(rect, config()); - final second = beamGeometry(rect, config()); - expect(identical(first, second), isTrue); - }); - - test('a changed rect or config returns new geometry', () { - const rect = Rect.fromLTWH(0, 0, 180, 80); - final baseConfig = config(); - final first = beamGeometry(rect, baseConfig); - expect( - identical( - first, - beamGeometry(const Rect.fromLTWH(0, 0, 181, 80), baseConfig), - ), - isFalse, - ); - expect(identical(first, beamGeometry(rect, config(radius: 13))), isFalse); - }); - }); -} diff --git a/test/painting/save_layer_budget_test.dart b/test/painting/save_layer_budget_test.dart deleted file mode 100644 index b7472dc..0000000 --- a/test/painting/save_layer_budget_test.dart +++ /dev/null @@ -1,369 +0,0 @@ -import 'dart:math' as math; -import 'dart:typed_data'; -import 'dart:ui' as ui; - -import 'package:flutter/painting.dart'; -import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/models/beam_colors.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/models/beam_options.dart'; -import 'package:flutter_border_beam/src/models/beam_segment.dart'; -import 'package:flutter_border_beam/src/models/beam_shape.dart'; -import 'package:flutter_border_beam/src/models/beam_style.dart'; -import 'package:flutter_border_beam/src/models/beam_timing.dart'; -import 'package:flutter_border_beam/src/models/beam_variant.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; -import 'package:flutter_test/flutter_test.dart'; - -/// Enforces CLAUDE.md hard rule 2: the per-frame `saveLayer` budget. -/// -/// Every `saveLayer` is an offscreen render target, so the count is the -/// single cheapest proxy for the cost of a beam frame. The budget below is -/// the measured count for a full frame (`paintBehind` + `paintAbove`) of each -/// variant; it must only ever go down. -void main() { - // Measured maxima over every brightness × palette × time sample. Each entry - // is one layer composite: the layers a variant stacks over the child, plus - // the mask sub-layers that intersect two masks, plus (pulse-outside) the - // two behind-child glow layers. - // - // rotate 4 — inner + inner mask + stroke + blurred bloom - // small 3 — inner + stroke + blurred bloom (single-mask inner) - // line 4 — inner + inner mask + stroke + blurred bloom - // pulseInside 4 — inner + inner mask + stroke + blurred bloom - // pulseOutside 3 — behind: core glow + bloom halo; above: stroke - const budget = { - BeamVariant.rotate: 4, - BeamVariant.small: 3, - BeamVariant.line: 4, - BeamVariant.pulseInside: 4, - BeamVariant.pulseOutside: 3, - }; - - const size = ui.Size(350, 140); - final palettes = { - 'colorful': BeamColors.colorful, - 'mono': BeamColors.mono, - 'custom': const BeamColors.custom([ui.Color(0xFFFF0080)]), - }; - // Post fade-in samples spread over the cycle: mid-travel, the golden - // freeze, and a late frame several cycles in. - const samples = [0.5, 1.3, 7.9]; - - for (final variant in BeamVariant.values) { - test('$variant stays within its saveLayer budget', () { - var worst = 0; - var worstCase = ''; - for (final brightness in ui.Brightness.values) { - for (final MapEntry(key: name, value: colors) in palettes.entries) { - final config = BeamConfig.resolve( - variant: variant, - palette: colors.resolve(), - brightness: brightness, - ); - final resolver = BeamPhaseResolver(config); - final strategy = strategyFor(variant); - for (final t in samples) { - final recorder = ui.PictureRecorder(); - final canvas = _CountingCanvas(ui.Canvas(recorder)); - final phases = resolver.sample(t, 1); - strategy.paintBehind(canvas, size, config, phases); - strategy.paintAbove(canvas, size, config, phases); - recorder.endRecording().dispose(); - - expect( - canvas.unforwarded, - isEmpty, - reason: - 'the counting canvas does not forward ' - '${canvas.unforwarded.join(', ')} — add explicit ' - 'delegating overrides so painting is still exercised', - ); - // Every layer and every clip scope must be closed, or the - // painter would leak state into whatever draws next. - expect( - canvas.saves + canvas.saveLayers, - canvas.restores, - reason: - 'unbalanced save/restore for $variant/$brightness/$name ' - 'at t=$t: ${canvas.saves} save + ${canvas.saveLayers} ' - 'saveLayer vs ${canvas.restores} restore', - ); - if (canvas.saveLayers > worst) { - worst = canvas.saveLayers; - worstCase = '$brightness/$name at t=${t}s'; - } - } - } - } - // ignore: avoid_print - print('$variant: max $worst saveLayer/frame ($worstCase)'); - expect( - worst, - budget[variant], - reason: - 'the $variant frame now issues $worst saveLayer calls ' - '(worst case $worstCase). Fewer is a win — update the budget ' - 'table. More is a regression: fold the new work into an ' - 'existing layer.', - ); - }); - } - - // Every Phase 3 surface option, measured against the SAME table. None of - // them may buy its effect with a layer: the comet re-clips the bloom layer - // it already had, the sparkles and the dash mask ride inside layers that - // exist anyway, a wider glow only changes a blur sigma, extra beams and a - // turned edge change geometry, and a contour changes which path the ring - // is cut from. - final scenarios = - { - 'comet': ( - style: const BeamStyle(comet: true), - shape: const BeamShape(), - timing: const BeamTiming(), - ), - 'sparkle: 1': ( - style: const BeamStyle(sparkle: 1), - shape: const BeamShape(), - timing: const BeamTiming(), - ), - 'segments: 8': ( - style: const BeamStyle(segments: 8), - shape: const BeamShape(), - timing: const BeamTiming(), - ), - 'glowSpread: 2': ( - style: const BeamStyle(glowSpread: 2), - shape: const BeamShape(), - timing: const BeamTiming(), - ), - 'tailLength: 2': ( - style: const BeamStyle(tailLength: 2), - shape: const BeamShape(), - timing: const BeamTiming(), - ), - 'beamCount: 3': ( - style: const BeamStyle(), - shape: const BeamShape(), - timing: const BeamTiming(beamCount: 3), - ), - 'direction: reverse': ( - style: const BeamStyle(), - shape: const BeamShape(), - timing: const BeamTiming(direction: BeamDirection.reverse), - ), - 'edge: left': ( - style: const BeamStyle(), - shape: const BeamShape(edge: BeamEdge.left), - timing: const BeamTiming(), - ), - 'ringOffset: 8': ( - style: const BeamStyle(), - shape: const BeamShape(ringOffset: 8), - timing: const BeamTiming(), - ), - 'contour': ( - style: const BeamStyle(), - shape: BeamShape(contour: _blobContour), - timing: const BeamTiming(), - ), - 'segment: bottomHalf': ( - style: const BeamStyle(), - shape: const BeamShape(segment: BeamSegment.bottomHalf), - timing: const BeamTiming(), - ), - 'segment: bottomEdge': ( - style: const BeamStyle(), - shape: const BeamShape(segment: BeamSegment.bottomEdge), - timing: const BeamTiming(), - ), - 'segment feather: 0': ( - style: const BeamStyle(), - shape: const BeamShape( - segment: BeamSegment( - start: BeamAnchor.rightCenter, - end: BeamAnchor.leftCenter, - feather: 0, - ), - ), - timing: const BeamTiming(), - ), - 'line wrapCorners': ( - style: const BeamStyle(), - shape: const BeamShape(wrapCorners: true), - timing: const BeamTiming(), - ), - // renderScale is one canvas transform inside BeamPainter, so a - // strategy frame is the same frame; innerSizeScale only resizes - // blobs a layer already holds; and the stock pulse-outside table - // only moves insets and blur sigmas. - 'renderScale: 0.5': ( - style: const BeamStyle(renderScale: 0.5), - shape: const BeamShape(), - timing: const BeamTiming(), - ), - 'innerSizeScale: 0.6': ( - style: const BeamStyle(innerSizeScale: 0.6), - shape: const BeamShape(), - timing: const BeamTiming(), - ), - 'pulseOutsideStock': ( - style: BeamStyle.pulseOutsideStock, - shape: const BeamShape(), - timing: const BeamTiming(), - ), - }; - - for (final MapEntry(key: label, value: scenario) in scenarios.entries) { - for (final variant in BeamVariant.values) { - test('$variant with $label stays within its saveLayer budget', () { - var worst = 0; - var worstCase = ''; - for (final brightness in ui.Brightness.values) { - final config = BeamConfig.resolve( - variant: variant, - palette: BeamColors.colorful.resolve(), - brightness: brightness, - style: scenario.style, - shape: scenario.shape, - timing: scenario.timing, - ); - final resolver = BeamPhaseResolver(config); - final strategy = strategyFor(variant); - for (final t in samples) { - final recorder = ui.PictureRecorder(); - final canvas = _CountingCanvas(ui.Canvas(recorder)); - final phases = resolver.sample(t, 1); - strategy.paintBehind(canvas, size, config, phases); - strategy.paintAbove(canvas, size, config, phases); - recorder.endRecording().dispose(); - - expect(canvas.unforwarded, isEmpty); - expect( - canvas.saves + canvas.saveLayers, - canvas.restores, - reason: - 'unbalanced save/restore for $variant/$label/$brightness ' - 'at t=$t', - ); - if (canvas.saveLayers > worst) { - worst = canvas.saveLayers; - worstCase = '$brightness at t=${t}s'; - } - } - } - expect( - worst, - budget[variant], - reason: - '$label changed the $variant frame to $worst saveLayer calls ' - '(worst case $worstCase). A surface option must use exactly ' - 'the layers the variant already composites.', - ); - }); - } - } -} - -/// A lobed contour: enough of a departure from a rounded rect to exercise the -/// offset path, and value-equal so the config caches it. -final _blobContour = BeamPathContour((rect) { - final path = Path(); - final centre = rect.center; - for (var i = 0; i <= 48; i++) { - final a = i / 48 * 2 * math.pi; - final r = rect.shortestSide / 2 * (0.75 + 0.25 * (i % 8 < 4 ? 1 : 0)); - final p = Offset( - centre.dx + r * 1.6 * math.cos(a), - centre.dy + r * math.sin(a), - ); - if (i == 0) { - path.moveTo(p.dx, p.dy); - } else { - path.lineTo(p.dx, p.dy); - } - } - return path..close(); -}, key: 'budget-blob'); - -/// A [ui.Canvas] that counts layer and clip scopes while forwarding the draw -/// calls to a real canvas, so the painters run exactly as they do on screen. -/// -/// Everything the strategies call is delegated explicitly; anything else -/// lands in [unforwarded] via `noSuchMethod` so a new draw call fails the -/// test loudly instead of silently going unpainted. -class _CountingCanvas implements ui.Canvas { - _CountingCanvas(this._inner); - - final ui.Canvas _inner; - - int saves = 0; - int saveLayers = 0; - int restores = 0; - final Set unforwarded = {}; - - @override - void save() { - saves++; - _inner.save(); - } - - @override - void saveLayer(ui.Rect? bounds, ui.Paint paint) { - saveLayers++; - _inner.saveLayer(bounds, paint); - } - - @override - void restore() { - restores++; - _inner.restore(); - } - - @override - void clipPath(ui.Path path, {bool doAntiAlias = true}) => - _inner.clipPath(path, doAntiAlias: doAntiAlias); - - @override - void clipRect( - ui.Rect rect, { - ui.ClipOp clipOp = ui.ClipOp.intersect, - bool doAntiAlias = true, - }) => _inner.clipRect(rect, clipOp: clipOp, doAntiAlias: doAntiAlias); - - @override - void drawRect(ui.Rect rect, ui.Paint paint) => _inner.drawRect(rect, paint); - - @override - void drawPath(ui.Path path, ui.Paint paint) => _inner.drawPath(path, paint); - - @override - void drawCircle(ui.Offset c, double radius, ui.Paint paint) => - _inner.drawCircle(c, radius, paint); - - @override - void translate(double dx, double dy) => _inner.translate(dx, dy); - - @override - void scale(double sx, [double? sy]) => _inner.scale(sx, sy); - - @override - void rotate(double radians) => _inner.rotate(radians); - - @override - void transform(Float64List matrix4) => _inner.transform(matrix4); - - @override - dynamic noSuchMethod(Invocation invocation) { - unforwarded.add(_symbolName(invocation.memberName)); - return null; - } -} - -String _symbolName(Symbol symbol) { - final text = symbol.toString(); - final start = text.indexOf('"'); - final end = text.lastIndexOf('"'); - return start >= 0 && end > start ? text.substring(start + 1, end) : text; -} diff --git a/test/painting/segment_paint_test.dart b/test/painting/segment_paint_test.dart deleted file mode 100644 index a26eff4..0000000 --- a/test/painting/segment_paint_test.dart +++ /dev/null @@ -1,411 +0,0 @@ -import 'dart:math' as math; -import 'dart:ui' as ui; - -import 'package:flutter/painting.dart'; -import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/constants/line_keyframes.dart'; -import 'package:flutter_border_beam/src/models/beam_blob.dart'; -import 'package:flutter_border_beam/src/models/beam_colors.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/models/beam_options.dart'; -import 'package:flutter_border_beam/src/models/beam_segment.dart'; -import 'package:flutter_border_beam/src/models/beam_shape.dart'; -import 'package:flutter_border_beam/src/models/beam_style.dart'; -import 'package:flutter_border_beam/src/models/beam_variant.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; -import 'package:flutter_border_beam/src/painting/ring_geometry.dart'; -import 'package:flutter_test/flutter_test.dart'; - -const _size = ui.Size.square(300); - -void main() { - group('rotate segment mask', () { - test('bottomHalf paints only the lower half over a full cycle', () async { - final frames = await _cycleFrames( - _config(BeamVariant.rotate, segment: BeamSegment.bottomHalf), - ); - expect( - frames.totalAlpha(const ui.Rect.fromLTRB(0, 180, 300, 300)), - greaterThan(10), - ); - expect(frames.totalAlpha(const ui.Rect.fromLTRB(0, 0, 300, 120)), 0); - }); - - test('topHalf paints only the upper half over a full cycle', () async { - final frames = await _cycleFrames( - _config(BeamVariant.rotate, segment: BeamSegment.topHalf), - ); - expect( - frames.totalAlpha(const ui.Rect.fromLTRB(0, 0, 300, 120)), - greaterThan(10), - ); - expect(frames.totalAlpha(const ui.Rect.fromLTRB(0, 180, 300, 300)), 0); - }); - - test('feather zero cuts hard while feather 40 ramps', () async { - const hard = BeamSegment( - start: BeamAnchor.rightCenter, - end: BeamAnchor.leftCenter, - feather: 0, - ); - const soft = BeamSegment( - start: BeamAnchor.rightCenter, - end: BeamAnchor.leftCenter, - feather: 40, - ); - final hardPixels = await _cycleFrames( - _config(BeamVariant.rotate, segment: hard), - ); - final softPixels = await _cycleFrames( - _config(BeamVariant.rotate, segment: soft), - ); - final geometry = BeamRingGeometry( - rect: ui.Offset.zero & _size, - radius: BorderRadius.circular(16), - borderWidth: 1, - useSuperellipse: false, - segment: soft, - ); - final start = geometry.segmentRange!.from; - double sample(_Pixels pixels, double distance) { - final point = geometry.perimeter.offsetPointAt( - start + distance / geometry.perimeter.length, - 1, - ); - return pixels.alphaNear(point); - } - - // The bloom is clipped inside its blurred saveLayer, so it legitimately - // bleeds across even a hard segment edge. The unblurred layers still - // make the zero-feather transition much steeper than a feathered one. - // alphaNear reads a 5x5 neighborhood, so the two sides of the step are - // sampled 8px apart to keep their windows disjoint. - final hardStep = sample(hardPixels, 8) - sample(hardPixels, -8); - final softStep = sample(softPixels, 8) - sample(softPixels, -8); - expect(sample(hardPixels, 2), greaterThan(0.05)); - expect(hardStep, greaterThan(softStep + 0.02)); - final ramp = [ - for (final d in [2.0, 10.0, 20.0, 30.0, 42.0]) sample(softPixels, d), - ]; - for (var i = 1; i < ramp.length; i++) { - expect(ramp[i], greaterThanOrEqualTo(ramp[i - 1] - 0.02)); - } - expect(ramp.last, greaterThan(ramp.first)); - }); - }); - - group('line path travel', () { - test('traveller follows the bottom half perimeter', () async { - Future<_Pixels> at(double progress) => _paint( - _config(BeamVariant.line, segment: BeamSegment.bottomHalf), - phases: BeamFramePhases( - fadeOpacity: 1, - hueDegrees: 0, - travelProgress: progress, - travellers: [progress], - ), - ); - - final middle = await at(0.5); - // The stock edge-fade is fully transparent at 0.1/0.9, so probe just - // inside those ramps while the anchors are still on the side runs. - final early = await at(0.15); - final late = await at(0.85); - expect( - middle.totalAlpha(const ui.Rect.fromLTRB(110, 250, 190, 300)), - greaterThan(2), - ); - expect( - early.totalAlpha(const ui.Rect.fromLTRB(250, 150, 300, 250)), - greaterThan(1), - ); - expect( - late.totalAlpha(const ui.Rect.fromLTRB(0, 150, 50, 250)), - greaterThan(1), - ); - }); - - test('wrapCorners bends into the bottom-right corner arc', () async { - // A 60px radius on the 300px box gives 94px corner arcs — long enough - // for a bent traveller to sit well inside one while the temporal edge - // fade still carries it. Both runs travel left to right, so 0.82 puts - // the planar anchor 9px short of the bottom-right arc, where its run - // ends, and the wrapped anchor 28px into that same arc. - const progress = 0.82; - final planar = await _paint( - _config(BeamVariant.line, radius: 60), - phases: _linePhasesAt(progress), - ); - final wrapped = await _paint( - _config(BeamVariant.line, wrapCorners: true, radius: 60), - phases: _linePhasesAt(progress), - ); - // A 24px box straddling the bottom-right arc's 45° point — (282, 282), - // on the arc about (240, 240). - const arc = ui.Rect.fromLTRB(270, 270, 294, 294); - final bent = wrapped.totalAlpha(arc); - // The wrapped traveller rides the arc; the planar one never leaves the - // straight run, so the arc catches only what its glow spills into it. - expect(bent, greaterThan(1)); - expect(bent, greaterThan(planar.totalAlpha(arc) + 6)); - expect(bent, greaterThan(planar.totalAlpha(arc) * 3)); - }); - - // wrapCorners is a modifier on the ordinary line variant, so turning it on - // must never reverse the animation — only lengthen the run around the two - // corners. Planar travel is authored bottom-edge left to right and turned - // rigidly for the other edges, which leaves it counter-clockwise on all - // four. [forward] is travel toward growing x (horizontal) or y (vertical). - for (final (edge, axis, forward) in [ - (BeamEdge.bottom, Axis.horizontal, true), - (BeamEdge.top, Axis.horizontal, false), - (BeamEdge.left, Axis.vertical, true), - (BeamEdge.right, Axis.vertical, false), - ]) { - test('wrapCorners keeps the planar travel direction on $edge', () async { - Future centre(bool wrap, double progress) async { - final pixels = await _paint( - _config(BeamVariant.line, edge: edge, wrapCorners: wrap), - phases: _linePhasesAt(progress), - ); - final centroid = pixels.centroid(); - return axis == Axis.horizontal ? centroid.dx : centroid.dy; - } - - final planarEarly = await centre(false, 0.25); - final planarLate = await centre(false, 0.75); - final wrappedEarly = await centre(true, 0.25); - final wrappedLate = await centre(true, 0.75); - - // The planar run's direction, and the wrapped run agreeing with it - // rather than starting from the far end. - expect(planarLate > planarEarly, forward); - expect(wrappedLate > wrappedEarly, forward); - expect(wrappedEarly < 150, forward); - expect(wrappedLate > 150, forward); - // The two anchors coincide at mid-run and stay close at the quarter - // points: equal progress lands a little further along the wrapped run, - // which is 327px of perimeter against the planar run's 300px of edge. - expect(await centre(true, 0.5), closeTo(await centre(false, 0.5), 5)); - expect(wrappedEarly, closeTo(planarEarly, 25)); - expect(wrappedLate, closeTo(planarLate, 25)); - }); - } - }); - - for (final variant in [BeamVariant.pulseInside, BeamVariant.pulseOutside]) { - test('$variant paints no pixels above center with bottomHalf', () async { - final pixels = await _paint( - _config(variant, segment: BeamSegment.bottomHalf), - behindAndAbove: true, - ); - expect(pixels.totalAlpha(const ui.Rect.fromLTRB(0, 0, 300, 140)), 0); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(0, 160, 300, 300)), - greaterThan(1), - ); - }); - } - - test('segmented stroke bands retain visible ring pixels', () async { - for (final variant in BeamVariant.values) { - final pixels = await _cycleFrames( - _config(variant, segment: BeamSegment.bottomHalf), - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(0, 250, 300, 300)), - greaterThan(1), - reason: '$variant', - ); - } - }); - - test('rotate sparkles cannot spill beyond a segment band', () async { - final pixels = await _cycleFrames( - _config( - BeamVariant.rotate, - segment: BeamSegment.bottomHalf, - style: const BeamStyle(sparkle: 1), - ), - ); - expect(pixels.totalAlpha(const ui.Rect.fromLTRB(0, 0, 300, 120)), 0); - }); - - test('pulse variants cycle a short spec palette without throwing', () async { - const short = BeamColors.spec( - border: [ - BeamBlob( - color: ui.Color(0xFFFF0080), - position: ui.Offset(0.5, 0.5), - size: ui.Size(40, 24), - ), - ], - ); - for (final variant in [BeamVariant.pulseInside, BeamVariant.pulseOutside]) { - final pixels = await _paint( - _config(variant, colors: short), - behindAndAbove: true, - ); - expect( - pixels.totalAlpha(ui.Offset.zero & _size), - greaterThan(1), - reason: '$variant', - ); - } - }); - - test('an omitted segment and an explicit null paint identically', () async { - final omitted = BeamConfig.resolve( - variant: BeamVariant.rotate, - palette: BeamColors.colorful.resolve(), - brightness: ui.Brightness.dark, - ); - final explicit = BeamConfig.resolve( - variant: BeamVariant.rotate, - palette: BeamColors.colorful.resolve(), - brightness: ui.Brightness.dark, - shape: const BeamShape(segment: null, wrapCorners: false), - ); - final a = await _paint(omitted, t: 1.3, behindAndAbove: true); - final b = await _paint(explicit, t: 1.3, behindAndAbove: true); - expect(a.bytes, b.bytes); - }); -} - -BeamConfig _config( - BeamVariant variant, { - BeamSegment? segment, - bool wrapCorners = false, - double radius = 16, - BeamEdge edge = BeamEdge.bottom, - BeamColors colors = BeamColors.colorful, - BeamStyle style = const BeamStyle(), -}) => BeamConfig.resolve( - variant: variant, - palette: colors.resolve(), - brightness: ui.Brightness.dark, - style: style, - shape: BeamShape( - radius: BorderRadius.all(Radius.circular(radius)), - edge: edge, - segment: segment, - wrapCorners: wrapCorners, - ), -); - -/// A frame of the line variant's own tracks at [progress]. -/// -/// Only the planar branch reads `lineX`/`lineW`/`edge` off the phases; path -/// mode re-samples the same tracks per traveller. Sampling them here is what -/// puts a planar and a path-mode run at the same point of the same cycle — -/// the hand-built defaults would otherwise freeze the planar traveller. -BeamFramePhases _linePhasesAt(double progress) => BeamFramePhases( - fadeOpacity: 1, - hueDegrees: 0, - travelProgress: progress, - travellers: [progress], - lineX: sampleKeyframes(lineTravelX, progress), - lineW: sampleKeyframes(lineTravelW, progress), - edge: sampleKeyframes(lineEdgeFade, progress), -); - -Future<_Pixels> _cycleFrames(BeamConfig config) async { - final frames = <_Pixels>[]; - for (final progress in [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]) { - frames.add( - await _paint( - config, - phases: BeamFramePhases( - fadeOpacity: 1, - hueDegrees: 0, - angleRadians: progress * 2 * math.pi, - travelProgress: progress, - travellers: [progress], - ), - ), - ); - } - return _Pixels.max(frames); -} - -Future<_Pixels> _paint( - BeamConfig config, { - double t = 1.3, - BeamFramePhases? phases, - bool behindAndAbove = false, -}) async { - final recorder = ui.PictureRecorder(); - final canvas = ui.Canvas(recorder); - final frame = phases ?? BeamPhaseResolver(config).sample(t, 1); - final strategy = strategyFor(config.variant); - if (behindAndAbove) strategy.paintBehind(canvas, _size, config, frame); - strategy.paintAbove(canvas, _size, config, frame); - final image = await recorder.endRecording().toImage(300, 300); - final data = await image.toByteData(format: ui.ImageByteFormat.rawRgba); - return _Pixels(data!.buffer.asUint8List(), image.width, image.height); -} - -class _Pixels { - _Pixels(this.bytes, this.width, this.height); - - factory _Pixels.max(List<_Pixels> frames) { - final bytes = List.filled(frames.first.bytes.length, 0); - for (final frame in frames) { - for (var i = 0; i < bytes.length; i++) { - bytes[i] = math.max(bytes[i], frame.bytes[i]); - } - } - return _Pixels(bytes, frames.first.width, frames.first.height); - } - - final List bytes; - final int width; - final int height; - - double alphaAt(int x, int y) { - if (x < 0 || y < 0 || x >= width || y >= height) return 0; - return bytes[(y * width + x) * 4 + 3] / 255; - } - - double alphaNear(ui.Offset point) { - var best = 0.0; - for (var dy = -2; dy <= 2; dy++) { - for (var dx = -2; dx <= 2; dx++) { - best = math.max( - best, - alphaAt(point.dx.round() + dx, point.dy.round() + dy), - ); - } - } - return best; - } - - double totalAlpha(ui.Rect rect) { - var sum = 0.0; - for (var y = rect.top.round(); y < rect.bottom.round(); y++) { - for (var x = rect.left.round(); x < rect.right.round(); x++) { - sum += alphaAt(x, y); - } - } - return sum; - } - - /// The alpha-weighted centre of everything painted — where the traveller - /// sits, for a frame holding one beam. - ui.Offset centroid() { - var sumX = 0.0; - var sumY = 0.0; - var weight = 0.0; - for (var y = 0; y < height; y++) { - for (var x = 0; x < width; x++) { - final alpha = alphaAt(x, y); - sumX += x * alpha; - sumY += y * alpha; - weight += alpha; - } - } - return weight == 0 - ? ui.Offset.zero - : ui.Offset(sumX / weight, sumY / weight); - } -} diff --git a/test/painting/surface_features_test.dart b/test/painting/surface_features_test.dart deleted file mode 100644 index 9129d14..0000000 --- a/test/painting/surface_features_test.dart +++ /dev/null @@ -1,669 +0,0 @@ -import 'dart:math' as math; -import 'dart:ui' as ui; - -import 'package:flutter/painting.dart'; -import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/models/beam_colors.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/models/beam_options.dart'; -import 'package:flutter_border_beam/src/models/beam_shape.dart'; -import 'package:flutter_border_beam/src/models/beam_style.dart'; -import 'package:flutter_border_beam/src/models/beam_timing.dart'; -import 'package:flutter_border_beam/src/models/beam_variant.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; -import 'package:flutter_border_beam/src/painting/ring_geometry.dart'; -import 'package:flutter_test/flutter_test.dart'; - -/// Per-feature painting tests for the Phase 3 surface options: each one -/// asserts pixels appear where the feature promises them and stay away from -/// where it does not. -/// -/// The assertions are deliberately coarse — presence, absence, and ordering -/// of totals — so they pin behaviour without pinning the look, which the -/// goldens own. -void main() { - const beamSize = ui.Size(350, 140); - - group('direction', () { - test('reverse mirrors the rotate window about the beam angle', () async { - final config = _config(BeamVariant.rotate); - final forward = await _paint( - config, - phases: const BeamFramePhases(fadeOpacity: 1, hueDegrees: 0), - ); - final reverse = await _paint( - config, - phases: const BeamFramePhases( - fadeOpacity: 1, - hueDegrees: 0, - reversedNow: true, - ), - ); - final rect = ui.Offset.zero & beamSize; - final a = forward.ringProfile(rect); - final b = reverse.ringProfile(rect); - // Sample i sits at angle i·2π/n; its mirror about the beam angle (0) is - // sample n − i. - var mirrored = 0.0; - var same = 0.0; - for (var i = 1; i < a.length; i++) { - mirrored += (a[i] - b[a.length - i]).abs(); - same += (a[i] - b[i]).abs(); - } - expect( - mirrored, - lessThan(same * 0.5), - reason: 'the reversed window should be the forward one mirrored', - ); - }); - - test('reverse mirrors the line beam head across the edge', () async { - // Two thirds through the cycle, where the head is well off centre and - // a mirror is not the same picture. - const t = 2.0; - final forward = await _paint(_config(BeamVariant.line), t: t); - final reverse = await _paint( - _config( - BeamVariant.line, - timing: const BeamTiming(direction: BeamDirection.reverse), - ), - t: t, - ); - const band = ui.Rect.fromLTRB(0, 126, 350, 140); - final xf = forward.brightestColumn(band); - final xr = reverse.brightestColumn(band); - expect( - (xf - 175).abs(), - greaterThan(25), - reason: 'a head at mid-edge would mirror onto itself', - ); - expect(xr, closeTo(350 - xf, 12)); - }); - }); - - group('beamCount', () { - test('rotate paints two heads half a turn apart', () async { - final pixels = await _paint( - _config(BeamVariant.rotate, timing: const BeamTiming(beamCount: 2)), - phases: const BeamFramePhases(fadeOpacity: 1, hueDegrees: 0), - ); - final profile = pixels.ringProfile(ui.Offset.zero & beamSize); - final arcs = _litArcs(profile); - expect(arcs.length, 2, reason: 'two beams, two lit arcs'); - final gap = (arcs[1].centre - arcs[0].centre).abs() / profile.length; - expect(gap, closeTo(0.5, 0.08), reason: 'half a turn apart'); - }); - - test('one beam paints a single arc', () async { - final pixels = await _paint( - _config(BeamVariant.rotate), - phases: const BeamFramePhases(fadeOpacity: 1, hueDegrees: 0), - ); - expect(_litArcs(pixels.ringProfile(ui.Offset.zero & beamSize)).length, 1); - }); - - test('line paints a head per traveller', () async { - final pixels = await _paint( - _config(BeamVariant.line, timing: const BeamTiming(beamCount: 3)), - t: 1.3, - ); - final band = ui.Rect.fromLTRB(0, 120, 350, 140); - final columns = pixels.columnProfile(band); - expect( - _litArcs(columns, threshold: 0.35).length, - greaterThanOrEqualTo(2), - reason: 'three travellers, at least two inside the edge fade', - ); - }); - }); - - group('tailLength', () { - test('scales the lit arc about the head', () async { - Future litSamples(double tail) async { - final pixels = await _paint( - _config(BeamVariant.rotate, style: BeamStyle(tailLength: tail)), - phases: const BeamFramePhases(fadeOpacity: 1, hueDegrees: 0), - ); - final profile = pixels.ringProfile(ui.Offset.zero & beamSize); - final peak = profile.reduce(math.max); - return profile.where((v) => v > peak * 0.2).length; - } - - final short = await litSamples(0.5); - final normal = await litSamples(1); - final long = await litSamples(2); - expect(short, lessThan(normal)); - expect(long, greaterThan(normal)); - }); - }); - - group('glowSpread', () { - test('rotate reaches further in with a wider bloom', () async { - // The other two layers are switched off: the bloom is the only one - // glowSpread touches, and it is far the dimmest of the three. - Future bloomReach(double spread) async { - final pixels = await _paint( - _config( - BeamVariant.rotate, - style: BeamStyle( - glowSpread: spread, - innerOpacityFactor: 0, - strokeOpacityFactor: 0, - ), - ), - phases: const BeamFramePhases(fadeOpacity: 1, hueDegrees: 0), - ); - return pixels.inwardReach(); - } - - final normal = await bloomReach(1); - expect(normal, greaterThan(0)); - expect(await bloomReach(2), greaterThan(normal)); - }); - - test('pulse-outside pushes its halo further out', () async { - Future reach(double spread) async { - final pixels = await _paint( - _config( - BeamVariant.pulseOutside, - style: BeamStyle(glowSpread: spread), - ), - behind: true, - canvas: const ui.Size(550, 340), - origin: const ui.Offset(100, 100), - ); - return pixels.farthestLit( - const ui.Rect.fromLTWH(100, 100, 350, 140), - axis: Axis.vertical, - ); - } - - expect(await reach(2), greaterThan(await reach(1) + 2)); - }); - }); - - group('comet', () { - test('paints a halo outside the shape, unlike the plain bloom', () async { - Future outside(bool comet) async { - final pixels = await _paint( - _config(BeamVariant.rotate, style: BeamStyle(comet: comet)), - phases: const BeamFramePhases(fadeOpacity: 1, hueDegrees: 0), - canvas: const ui.Size(390, 180), - origin: const ui.Offset(20, 20), - ); - // A strip just outside the top edge, where the beam's head sits. - return pixels.totalAlpha(const ui.Rect.fromLTRB(20, 10, 390, 19)); - } - - expect(await outside(false), lessThan(0.5)); - expect(await outside(true), greaterThan(2)); - }); - }); - - group('sparkle', () { - test('adds pixels around the head and nowhere else', () async { - const phases = BeamFramePhases(fadeOpacity: 1, hueDegrees: 0); - final plain = await _paint(_config(BeamVariant.rotate), phases: phases); - final sparkly = await _paint( - _config(BeamVariant.rotate, style: const BeamStyle(sparkle: 1)), - phases: phases, - ); - // The head of the default window sits at 0.8 of a turn from the beam - // angle — the upper left of the box at angle 0. - const nearHead = ui.Rect.fromLTRB(0, 0, 120, 60); - const farSide = ui.Rect.fromLTRB(200, 100, 350, 140); - expect( - sparkly.totalAlpha(nearHead), - greaterThan(plain.totalAlpha(nearHead)), - ); - expect( - sparkly.totalAlpha(farSide), - closeTo(plain.totalAlpha(farSide), 0.5), - ); - }); - - test('is deterministic for a given frame', () async { - const phases = BeamFramePhases(fadeOpacity: 1, hueDegrees: 0); - final config = _config( - BeamVariant.rotate, - style: const BeamStyle(sparkle: 1), - ); - final first = await _paint(config, phases: phases); - final second = await _paint(config, phases: phases); - expect(first.bytes, second.bytes); - }); - }); - - group('segments', () { - test('cuts the ring into gaps the solid ring does not have', () async { - const phases = BeamFramePhases(fadeOpacity: 1, hueDegrees: 0); - final solid = await _paint(_config(BeamVariant.rotate), phases: phases); - final dashed = await _paint( - _config(BeamVariant.rotate, style: const BeamStyle(segments: 8)), - phases: phases, - ); - final rect = ui.Offset.zero & beamSize; - // Sampled right on the ring, where the stroke the mask cuts lives. - final solidProfile = solid.ringProfile(rect, depth: 1); - final dashedProfile = dashed.ringProfile(rect, depth: 1); - final gaps = _runs([ - for (var i = 0; i < solidProfile.length; i++) - solidProfile[i] > 0.05 && dashedProfile[i] < solidProfile[i] * 0.7, - ]); - expect( - gaps, - greaterThanOrEqualTo(3), - reason: 'eight dashes leave several dark gaps across the lit arc', - ); - expect( - dashedProfile.reduce((a, b) => a + b), - lessThan(solidProfile.reduce((a, b) => a + b)), - ); - }); - - test('a solid ring is left alone', () async { - const phases = BeamFramePhases(fadeOpacity: 1, hueDegrees: 0); - final solid = await _paint(_config(BeamVariant.rotate), phases: phases); - final one = await _paint( - _config(BeamVariant.rotate, style: const BeamStyle(segments: 1)), - phases: phases, - ); - expect( - one.bytes, - solid.bytes, - reason: 'a single segment is no ring at all, so it is ignored', - ); - }); - }); - - group('edge', () { - test('top paints the top band and leaves the bottom empty', () async { - final pixels = await _paint( - _config(BeamVariant.line, shape: const BeamShape(edge: BeamEdge.top)), - t: 1.3, - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(0, 0, 350, 20)), - greaterThan(5), - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(0, 120, 350, 140)), - lessThan(0.5), - ); - }); - - test('left paints the left band and leaves the right empty', () async { - final pixels = await _paint( - _config(BeamVariant.line, shape: const BeamShape(edge: BeamEdge.left)), - t: 1.3, - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(0, 0, 20, 140)), - greaterThan(5), - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(330, 0, 350, 140)), - lessThan(0.5), - ); - }); - - test('right paints the right band', () async { - final pixels = await _paint( - _config(BeamVariant.line, shape: const BeamShape(edge: BeamEdge.right)), - t: 1.3, - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(330, 0, 350, 140)), - greaterThan(5), - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(0, 0, 20, 140)), - lessThan(0.5), - ); - }); - - test('bottom is unchanged by the transform', () async { - final pixels = await _paint( - _config( - BeamVariant.line, - shape: const BeamShape(edge: BeamEdge.bottom), - ), - t: 1.3, - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(0, 120, 350, 140)), - greaterThan(5), - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(0, 0, 350, 20)), - lessThan(0.5), - ); - }); - }); - - group('ringOffset', () { - test('a positive offset paints outside the child bounds', () async { - final pixels = await _paint( - _config(BeamVariant.rotate, shape: const BeamShape(ringOffset: 10)), - phases: const BeamFramePhases(fadeOpacity: 1, hueDegrees: 0), - canvas: const ui.Size(390, 180), - origin: const ui.Offset(20, 20), - ); - // The ring now sits 10px out; the band just outside the child's bounds - // carries it. - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(20, 12, 370, 19)), - greaterThan(2), - ); - }); - - test('a negative offset pulls the ring inside them', () async { - final pixels = await _paint( - _config(BeamVariant.rotate, shape: const BeamShape(ringOffset: -12)), - phases: const BeamFramePhases(fadeOpacity: 1, hueDegrees: 0), - ); - // Nothing is left in the outermost band the ring used to occupy. - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(0, 0, 350, 3)), - lessThan(0.5), - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(0, 12, 350, 20)), - greaterThan(1), - ); - }); - }); - - group('contour', () { - test('a star contour paints along the star, not the rect', () async { - final pixels = await _paint( - _config(BeamVariant.rotate, shape: BeamShape(contour: _star)), - phases: const BeamFramePhases(fadeOpacity: 1, hueDegrees: 0), - ); - // The beam rides the star's arms; the box's own corners and the gaps - // between the arms — where a rounded rect would have painted — stay - // empty. - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(124, 112, 148, 134)), - greaterThan(1), - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(0, 0, 24, 24)), - lessThan(0.05), - ); - expect( - pixels.totalAlpha(const ui.Rect.fromLTRB(40, 90, 80, 130)), - lessThan(0.05), - ); - }); - - test('the ring keeps an even width around a lobed contour', () { - final path = _star.build(const ui.Rect.fromLTWH(0, 0, 200, 200)); - final widths = _insetWidths(path, 6); - final even = widths.where((w) => (w - 6).abs() < 1.5).length; - expect( - even, - greaterThan(widths.length * 3 ~/ 4), - reason: - 'a true normal offset holds the width everywhere but the folded ' - 'concave vertices, unlike a scale about the centre', - ); - }); - }); -} - -// ─── Fixtures ───────────────────────────────────────────────────────────── - -BeamConfig _config( - BeamVariant variant, { - BeamStyle style = const BeamStyle(), - BeamShape shape = const BeamShape(), - BeamTiming timing = const BeamTiming(), - ui.Brightness brightness = ui.Brightness.dark, -}) => BeamConfig.resolve( - variant: variant, - palette: BeamColors.colorful.resolve(), - brightness: brightness, - style: style, - shape: shape, - timing: timing, -); - -final _star = BeamPathContour((rect) { - final path = Path(); - final centre = rect.center; - final outer = rect.shortestSide / 2; - final inner = outer * 0.5; - for (var i = 0; i < 10; i++) { - final r = i.isEven ? outer : inner; - final a = -math.pi / 2 + i * math.pi / 5; - final p = centre + ui.Offset(math.cos(a) * r, math.sin(a) * r); - if (i == 0) { - path.moveTo(p.dx, p.dy); - } else { - path.lineTo(p.dx, p.dy); - } - } - return path..close(); -}, key: 'test-star'); - -/// Renders one frame of [config] and returns its pixels. -/// -/// [canvas]/[origin] make room for anything painted outside the beam's own -/// bounds — a comet halo or a pushed-out ring — which the widget's -/// `CustomPaint` does not clip either. -Future<_Pixels> _paint( - BeamConfig config, { - double t = 0.9, - BeamFramePhases? phases, - ui.Size size = const ui.Size(350, 140), - ui.Size? canvas, - ui.Offset origin = ui.Offset.zero, - bool behind = false, -}) async { - final target = canvas ?? size; - final recorder = ui.PictureRecorder(); - final c = ui.Canvas(recorder); - c.translate(origin.dx, origin.dy); - final frame = phases ?? BeamPhaseResolver(config).sample(t, 1); - final strategy = strategyFor(config.variant); - if (behind) { - strategy.paintBehind(c, size, config, frame); - } else { - strategy.paintAbove(c, size, config, frame); - } - final image = await recorder.endRecording().toImage( - target.width.toInt(), - target.height.toInt(), - ); - final bytes = await image.toByteData(format: ui.ImageByteFormat.rawRgba); - return _Pixels(bytes!.buffer.asUint8List(), image.width, image.height); -} - -/// The alpha channel of a rendered frame, with the sampling helpers the -/// feature assertions are phrased in. -class _Pixels { - _Pixels(this.bytes, this.width, this.height); - - final List bytes; - final int width; - final int height; - - double alphaAt(double x, double y) { - final px = x.round(); - final py = y.round(); - if (px < 0 || py < 0 || px >= width || py >= height) return 0; - return bytes[(py * width + px) * 4 + 3] / 255; - } - - /// Total alpha inside [rect], in whole-pixel units. - double totalAlpha(ui.Rect rect) { - var sum = 0.0; - for (var y = rect.top.round(); y < rect.bottom.round(); y++) { - for (var x = rect.left.round(); x < rect.right.round(); x++) { - sum += alphaAt(x.toDouble(), y.toDouble()); - } - } - return sum; - } - - /// Alpha sampled just inside the border of [rect], once per angle around - /// it — the ring as the rotating beam sees it. - /// - /// [depth] is how far in the sample looks: 1 reads the stroke alone, while - /// a deeper probe also reaches the rounded corners, where the contour sits - /// several px inside the box. - List ringProfile(ui.Rect rect, {int samples = 144, int depth = 10}) => - [ - for (var i = 0; i < samples; i++) - _ringSample(rect, i * 2 * math.pi / samples, depth), - ]; - - double _ringSample(ui.Rect rect, double angle, int depth) { - final dx = math.sin(angle); - final dy = -math.cos(angle); - final tx = dx.abs() < 1e-6 ? double.infinity : (rect.width / 2) / dx.abs(); - final ty = dy.abs() < 1e-6 ? double.infinity : (rect.height / 2) / dy.abs(); - final t = math.min(tx, ty); - if (!t.isFinite) return 0; - final edge = rect.center + ui.Offset(dx * t, dy * t); - var best = 0.0; - for (var inward = 1; inward <= depth; inward++) { - final p = edge - ui.Offset(dx, dy) * inward.toDouble(); - best = math.max(best, alphaAt(p.dx, p.dy)); - } - return best; - } - - /// Column-by-column alpha totals inside [rect], normalised to 0–1. - List columnProfile(ui.Rect rect) { - final columns = []; - for (var x = rect.left.round(); x < rect.right.round(); x++) { - var sum = 0.0; - for (var y = rect.top.round(); y < rect.bottom.round(); y++) { - sum += alphaAt(x.toDouble(), y.toDouble()); - } - columns.add(sum); - } - final peak = columns.fold(0.0, math.max); - return peak <= 0 ? columns : [for (final v in columns) v / peak]; - } - - /// The x of the brightest column inside [rect]. - double brightestColumn(ui.Rect rect) { - final columns = columnProfile(rect); - var best = 0; - for (var i = 1; i < columns.length; i++) { - if (columns[i] > columns[best]) best = i; - } - return rect.left + best; - } - - /// How far in from the nearest image edge the farthest lit pixel sits. - double inwardReach() { - var reach = 0.0; - for (var y = 0; y < height; y++) { - for (var x = 0; x < width; x++) { - if (alphaAt(x.toDouble(), y.toDouble()) <= 0) continue; - final d = math - .min(math.min(x, width - 1 - x), math.min(y, height - 1 - y)) - .toDouble(); - reach = math.max(reach, d); - } - } - return reach; - } - - /// How far past [rect] the farthest lit pixel sits on the given axis. - double farthestLit(ui.Rect rect, {required Axis axis}) { - var reach = 0.0; - for (var y = 0; y < height; y++) { - for (var x = 0; x < width; x++) { - if (alphaAt(x.toDouble(), y.toDouble()) <= 0.02) continue; - final d = axis == Axis.vertical - ? math.max(rect.top - y, y - rect.bottom) - : math.max(rect.left - x, x - rect.right); - reach = math.max(reach, d); - } - } - return reach; - } -} - -/// How many runs of `true` [flags] holds. -int _runs(List flags) { - var n = 0; - for (var i = 0; i < flags.length; i++) { - if (flags[i] && (i == 0 || !flags[i - 1])) n++; - } - return n; -} - -/// The runs of a profile that are lit above [threshold] of its peak, as -/// (centre index, length) pairs — the arcs a beam leaves on the ring. -List<({double centre, int length})> _litArcs( - List profile, { - double threshold = 0.25, -}) { - // Smoothed first: a sample sitting right on the threshold would otherwise - // split one arc into several, and an arc count is the whole assertion. - final smooth = [ - for (var i = 0; i < profile.length; i++) - [ - for (var k = -2; k <= 2; k++) - profile[(i + k + profile.length) % profile.length], - ].reduce((a, b) => a + b) / - 5, - ]; - final peak = smooth.fold(0.0, math.max); - if (peak <= 0) return const []; - final lit = [for (final v in smooth) v > peak * threshold]; - final arcs = <({double centre, int length})>[]; - var start = -1; - for (var i = 0; i < lit.length; i++) { - if (lit[i] && start < 0) start = i; - if (!lit[i] && start >= 0) { - arcs.add((centre: (start + i - 1) / 2, length: i - start)); - start = -1; - } - } - if (start >= 0) { - arcs.add(( - centre: (start + lit.length - 1) / 2, - length: lit.length - start, - )); - // A run that wraps the end joins the one at the start. - if (arcs.length > 1 && lit.first) { - final first = arcs.removeAt(0); - final last = arcs.removeLast(); - arcs.insert(0, (centre: last.centre, length: first.length + last.length)); - } - } - return arcs; -} - -/// Distances from a sample of points on [path] to the nearest point of the -/// path inset by [inset] — the realised border width around a contour. -List _insetWidths(Path path, double inset) { - final inner = BeamRingGeometry.insetPath(path, inset); - final innerPoints = []; - for (final metric in inner.computeMetrics()) { - for (var i = 0; i < 200; i++) { - final tangent = metric.getTangentForOffset(metric.length * i / 200); - if (tangent != null) innerPoints.add(tangent.position); - } - } - final widths = []; - for (final metric in path.computeMetrics()) { - for (var i = 0; i < 40; i++) { - final tangent = metric.getTangentForOffset(metric.length * i / 40); - if (tangent == null) continue; - var nearest = double.infinity; - for (final p in innerPoints) { - nearest = math.min(nearest, (p - tangent.position).distance); - } - widths.add(nearest); - } - } - return widths; -} diff --git a/test/render/beam_frame_test.dart b/test/render/beam_frame_test.dart new file mode 100644 index 0000000..f7e019e --- /dev/null +++ b/test/render/beam_frame_test.dart @@ -0,0 +1,571 @@ +import 'dart:ui' show Brightness; + +import 'package:flutter/painting.dart'; +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/animation/beam_phases.dart'; +import 'package:flutter_border_beam/src/effects/effect_emitters.dart'; +import 'package:flutter_border_beam/src/look/beam_look.dart'; +import 'package:flutter_border_beam/src/look/palette_tables.dart'; +import 'package:flutter_border_beam/src/look/rotate_look.dart'; +import 'package:flutter_border_beam/src/render/beam_frame.dart'; +import 'package:flutter_border_beam/src/render/beam_outline.dart'; +import 'package:flutter_border_beam/src/render/beam_renderer.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'render_utils.dart'; + +/// What each effect writes for the shader, frame by frame: finite and in +/// range, its layers built the way the design builds them, its windows where +/// the travel says, and its track inside the user's segment. +void main() { + setUpAll(BorderBeam.precache); + + // Evenly spread across two cycles of every effect, plus the golden + // instant. + final instants = [for (var i = 0; i < 24; i++) 0.05 + i * 0.29, 1.3]; + final box = const Offset(renderMargin, renderMargin) & cardSize; + + BeamRenderer renderer() { + final r = BeamRenderer(); + addTearDown(r.dispose); + return r; + } + + int litLayers(BeamFrameData d) => [ + for (var k = 0; k < beamLayerCount; k++) + if (d.geometryOf(k) != BeamGeometry.none && d.opacityOf(k) > 0) k, + ].length; + + group('every frame is sane', () { + for (final MapEntry(key: name, value: effect) in effectsByName.entries) { + test(name, () { + final r = renderer(); + var painted = 0; + for (final brightness in Brightness.values) { + for (final MapEntry(key: shapeName, value: shape) + in shapeVariety.entries) { + final config = configFor( + effect, + brightness: brightness, + shape: shape, + ); + for (final t in instants) { + final canvas = recordFrame(r, config, phasesAt(config, t)); + final label = '$name/${brightness.name}/$shapeName at ${t}s'; + // The golden instant is mid-sweep for every effect: any shape + // but a segment, which may hide all of the light, draws there. + // (Elsewhere a frame can be dark — the line fades its streak in + // and out of each sweep.) + if (t == 1.3 && shape.segment == null) { + expect(canvas.draws, hasLength(1), reason: '$label: no draw'); + } + if (canvas.draws.isEmpty) continue; + painted++; + expectSaneFrame( + r.debugFrame, + label, + drawBounds: canvas.drawBounds.single, + ); + } + } + } + expect(painted, greaterThan(0)); + }); + } + + test('effect options, palettes, and glow extremes', () { + final options = { + 'rotate comet': const BeamEffect.rotate(comet: true), + 'rotate count 4': const BeamEffect.rotate(count: 4), + 'rotate short tail': const BeamEffect.rotate(length: 0.25), + 'rotate long tail': const BeamEffect.rotate(length: 2), + for (final edge in BeamEdge.values) + 'line ${edge.name}': BeamEffect.line(edge: edge), + }; + final r = renderer(); + for (final MapEntry(key: label, value: effect) in options.entries) { + for (final glow in [0.0, 1.0, 4.0]) { + for (final MapEntry(key: palette, value: colors) + in paletteSubset.entries) { + final config = configFor( + effect, + colors: colors, + style: BeamStyle(glow: glow), + ); + for (final t in [0.4, 1.3, 2.9]) { + final canvas = recordFrame(r, config, phasesAt(config, t)); + final where = '$label, $palette, glow $glow at ${t}s'; + if (t == 1.3) { + expect(canvas.draws, hasLength(1), reason: '$where: no draw'); + } + if (canvas.draws.isEmpty) continue; + expectSaneFrame( + r.debugFrame, + where, + drawBounds: canvas.drawBounds.single, + ); + } + } + } + } + }); + + test('driven sweeps, from empty to full', () { + final r = renderer(); + for (final effect in BeamEffect.values.where((e) => e.travels)) { + final config = configFor(effect); + for (var i = 0; i <= 20; i++) { + final progress = i / 20; + final canvas = recordFrame( + r, + config, + phasesAt(config, 1.3, progress: progress), + ); + expect(canvas.draws, hasLength(1)); + expectSaneFrame( + r.debugFrame, + '${effect.name} at progress $progress', + drawBounds: canvas.drawBounds.single, + ); + } + } + }); + }); + + group('rotate', () { + test('paints an inner glow, a hairline, and a blurred bloom', () { + final r = renderer(); + final config = configFor(const BeamEffect.rotate()); + recordFrame(r, config, phasesAt(config, 1.3)); + final d = r.debugFrame; + expect(d.geometryOf(0), BeamGeometry.fill); + expect(d.edgeFadeOf(0), innerEdgeFade); + expect(d.hasShadow(0), isTrue); + expect(d.windowOf(0), BeamWindow.conicA); + expect(d.blobCount(0), colorfulTables.border.length); + expect(d.geometryOf(1), BeamGeometry.ring); + expect(d.windowOf(1), BeamWindow.conicA); + expect(d.overlayOf(1), BeamTable.overlayA); + expect(d.blobCount(1), colorfulTables.border.length); + expect(d.geometryOf(2), BeamGeometry.blurredRing); + expect(d.sigmaOf(2), rotateBloomBlur); + expect(d.overlayOf(2), BeamTable.overlayB); + expect(d.blobCount(2), 0); + }); + + test('a compact chip takes the chip tables', () { + final r = renderer(); + final config = configFor( + const BeamEffect.rotate(), + shape: const BeamShape.stadium(), + ); + recordFrame(r, config, phasesAt(config, 1.3), size: const Size(120, 36)); + final d = r.debugFrame; + expect(d.windowOf(0), BeamWindow.conicB, reason: 'the wider window'); + expect(d.edgeFadeOf(0), 0, reason: 'no edge fade on a chip'); + expect(d.blobCount(0), colorfulTables.smallInner.length); + expect(d.blobCount(1), colorfulTables.smallBorder.length); + }); + + test('the head rides the travel around the turn', () { + final r = renderer(); + final config = configFor(const BeamEffect.rotate()); + for (final p in [0.0, 0.2, 0.55, 0.9]) { + recordFrame(r, config, phasesAt(config, 1.3, progress: p)); + final head = r.debugFrame.conicStart + rotateHeadStop; + expect(BeamOutline.wrapFraction(head - p), closeTo(0, 1e-6)); + } + }); + + test('count beams repeat the tables around the turn', () { + final r = renderer(); + for (final count in [1, 2, 3, 4]) { + final config = configFor(BeamEffect.rotate(count: count)); + recordFrame(r, config, phasesAt(config, 1.3)); + expect(r.debugFrame.conicRepeats, count); + } + }); + + test('length stretches the tail; reverse mirrors the tables', () { + final r = renderer(); + double lit(BeamFrameData d) { + var n = 0; + for (var i = 0; i < 400; i++) { + if (d.tableAt(BeamTable.windowA, i / 400) > 0.05) n++; + } + return n / 400; + } + + final short = configFor(const BeamEffect.rotate(length: 0.5)); + recordFrame(r, short, phasesAt(short, 1.3)); + final shortWidth = lit(r.debugFrame); + final long = configFor(const BeamEffect.rotate(length: 1.3)); + recordFrame(r, long, phasesAt(long, 1.3)); + expect(lit(r.debugFrame), greaterThan(shortWidth)); + + final forward = configFor(const BeamEffect.rotate()); + recordFrame(r, forward, phasesAt(forward, 1.3)); + final f = [ + for (var i = 1; i < 20; i++) + r.debugFrame.tableAt(BeamTable.overlayA, i / 20), + ]; + final reverse = configFor( + const BeamEffect.rotate(), + timing: const BeamTiming(direction: BeamDirection.reverse), + ); + recordFrame(r, reverse, phasesAt(reverse, 1.3)); + for (var i = 1; i < 20; i++) { + expect( + r.debugFrame.tableAt(BeamTable.overlayA, 1 - i / 20), + closeTo(f[i - 1], 1e-6), + ); + } + }); + + test('reverse mirrors the windows on screen', () { + // Where the light sits, and which way its tail runs: every table read + // at a screen angle (clockwise from 12 o'clock) through the conic + // start and repeats, as the shader reads it, is the forward one + // reflected left to right, at every instant and beam count. + final r = renderer(); + double seen(BeamTable table, double angle) { + final d = r.debugFrame; + var t = (angle - d.conicStart) % 1.0; + if (d.conicRepeats > 1) t = (t * d.conicRepeats) % 1.0; + return d.tableAt(table, t); + } + + const steps = 360; + for (final count in [1, 2]) { + for (final turn in [0.1, 0.25, 0.4, 0.6, 0.9]) { + final forward = configFor(BeamEffect.rotate(count: count)); + recordFrame( + r, + forward, + phasesAt(forward, forward.cycleSeconds * turn), + ); + final expected = { + for (final t in BeamTable.values) + t: [for (var i = 0; i < steps; i++) seen(t, i / steps)], + }; + final reverse = configFor( + BeamEffect.rotate(count: count), + timing: const BeamTiming(direction: BeamDirection.reverse), + ); + recordFrame( + r, + reverse, + phasesAt(reverse, reverse.cycleSeconds * turn), + ); + for (final t in BeamTable.values) { + for (var i = 0; i < steps; i++) { + expect( + seen(t, (steps - i) % steps / steps), + closeTo(expected[t]![i], 1e-4), + reason: '×$count, $turn of a turn: ${t.name} at $i/$steps', + ); + } + } + } + } + }); + + test('a comet glows outside the border; a plain beam stays in', () { + final r = renderer(); + final plain = configFor(const BeamEffect.rotate()); + recordFrame(r, plain, phasesAt(plain, 1.3)); + expect(r.debugFrame.geometryOf(2), BeamGeometry.blurredRing); + expect(r.debugFrame.reachOutside, 0); + final comet = configFor(const BeamEffect.rotate(comet: true)); + recordFrame(r, comet, phasesAt(comet, 1.3)); + expect(r.debugFrame.geometryOf(2), BeamGeometry.glow); + expect(r.debugFrame.reachOutside, greaterThan(cometReach)); + }); + + test('mono paints its layers at half strength', () { + final r = renderer(); + final colorful = configFor(const BeamEffect.rotate()); + recordFrame(r, colorful, phasesAt(colorful, 1.3)); + final full = [for (var k = 0; k < 3; k++) r.debugFrame.opacityOf(k)]; + final mono = configFor( + const BeamEffect.rotate(), + colors: BeamColors.mono, + ); + recordFrame(r, mono, phasesAt(mono, 1.3)); + for (var k = 0; k < 3; k++) { + expect(r.debugFrame.opacityOf(k), closeTo(full[k] / 2, 1e-6)); + } + }); + }); + + group('line', () { + // A fixed hue (the gold preset, or hueMode: none) once dropped the + // bloom's blur, leaving the spikes as hard needles. + test('the bloom stays blurred when the hue is fixed', () { + final r = renderer(); + double bloomBlur(BeamColors colors, {BeamHueMode? hueMode}) { + final config = configFor( + const BeamEffect.line(), + colors: colors, + style: BeamStyle(hueMode: hueMode), + ); + recordFrame(r, config, phasesAt(config, 1.3)); + return r.debugFrame.blobBlurOf(2); + } + + final drifting = bloomBlur(BeamColors.ember); + expect(drifting, greaterThan(0)); + expect(bloomBlur(BeamColors.gold), drifting); + expect(bloomBlur(BeamColors.ember, hueMode: BeamHueMode.none), drifting); + }); + + // The line runs two hue tracks of its own beside the beam's; a static + // frame promises the palette's own colours, so neither may swing. + test('a static frame paints the palette as given, whatever the drift', () { + final r = renderer(); + List still(BeamHueMode hueMode) { + final config = configFor( + const BeamEffect.line(), + style: BeamStyle(hueMode: hueMode), + ); + recordFrame(r, config, BeamPhaseResolver(config).staticFrame()); + return List.of(r.debugFrame.data); + } + + // Continuous drift has no track of the line's own: its static frame + // is the palette at hue 0, which ping-pong's must match. + expect(still(BeamHueMode.pingPong), still(BeamHueMode.continuous)); + }); + + test('the windows ride the edge with the streak', () { + final r = renderer(); + for (final edge in BeamEdge.values) { + final config = configFor(BeamEffect.line(edge: edge)); + for (final p in [0.2, 0.5, 0.8]) { + recordFrame(r, config, phasesAt(config, 1.3, progress: p)); + final d = r.debugFrame; + for (final k in [0, 1, 2]) { + expect(d.windowOf(k), BeamWindow.radial); + final w = d.windowParamsOf(k); + final at = Offset(w[0], w[1]); + final onEdge = switch (edge) { + BeamEdge.top => (at.dy - box.top).abs(), + BeamEdge.bottom => (at.dy - box.bottom).abs(), + BeamEdge.left => (at.dx - box.left).abs(), + BeamEdge.right => (at.dx - box.right).abs(), + }; + expect(onEdge, lessThan(1e-3), reason: '${edge.name} $k'); + } + } + } + }); + + test('a driven streak reads left to right and top to bottom', () { + final r = renderer(); + for (final edge in BeamEdge.values) { + final config = configFor(BeamEffect.line(edge: edge)); + Offset centre(double p) { + recordFrame(r, config, phasesAt(config, 1.3, progress: p)); + final w = r.debugFrame.windowParamsOf(1); + return Offset(w[0], w[1]); + } + + final start = centre(0.1); + final end = centre(0.9); + if (edge == BeamEdge.top || edge == BeamEdge.bottom) { + expect(end.dx, greaterThan(start.dx), reason: edge.name); + } else { + expect(end.dy, greaterThan(start.dy), reason: edge.name); + } + } + }); + + test('fades in and out at the ends of a timed sweep', () { + final r = renderer(); + final config = configFor(const BeamEffect.line()); + double strokeAt(double t) { + recordFrame(r, config, phasesAt(config, t)); + return r.debugFrame.opacityOf(1); + } + + final cycle = config.cycleSeconds; + expect(strokeAt(cycle * 0.5), greaterThan(0.9)); + expect(strokeAt(cycle * 0.2), lessThan(strokeAt(cycle * 0.5))); + expect(strokeAt(cycle * 0.8), lessThan(strokeAt(cycle * 0.5))); + }); + + // Mono tones the line down through its spikes (shorter, fainter), which + // the `line_*_mono` goldens pin; what this pins is the other half — it + // does not do it by halving whole layers, as rotate's mono does. + test("mono leaves the line's layer opacities alone", () { + final r = renderer(); + final colorful = configFor(const BeamEffect.line()); + recordFrame(r, colorful, phasesAt(colorful, 1.5)); + final full = [for (var k = 0; k < 3; k++) r.debugFrame.opacityOf(k)]; + final mono = configFor(const BeamEffect.line(), colors: BeamColors.mono); + recordFrame(r, mono, phasesAt(mono, 1.5)); + for (var k = 0; k < 3; k++) { + expect(r.debugFrame.opacityOf(k), closeTo(full[k], 1e-6)); + } + }); + }); + + group('ambient effects', () { + test('light the whole border, so a segment is the only mask', () { + final r = renderer(); + for (final effect in BeamEffect.values.where((e) => !e.travels)) { + final config = configFor(effect); + recordFrame(r, config, phasesAt(config, 1.3)); + expect(litLayers(r.debugFrame), 3, reason: effect.name); + expect(r.debugFrame.trackSpan, 0, reason: '${effect.name}: own mask'); + } + }); + }); + + group('palettes', () { + test('the originals draw with their own tables', () { + for (final colors in [ + BeamColors.colorful, + BeamColors.mono, + BeamColors.ocean, + BeamColors.sunset, + ]) { + final palette = colors.resolve(); + expect(identical(BeamLook.tablesFor(palette), palette.tables), isTrue); + } + }); + + test("the extras cycle their colours over colorful's tables", () { + final tables = BeamLook.tablesFor(BeamColors.aurora.resolve()); + for (final (i, b) in tables.border.indexed) { + expect(b.position, colorfulTables.border[i].position); + expect(b.size, colorfulTables.border[i].size); + } + expect(tables.border.first.color, isNot(colorfulTables.border[0].color)); + }); + + test("custom palettes sample their stops into colorful's geometry", () { + const red = Color(0xFFFF0000); + final tables = BeamLook.tablesFor(const BeamColors.solid(red).resolve()); + for (final (i, b) in tables.border.indexed) { + expect(b.position, colorfulTables.border[i].position); + expect(b.color.r, closeTo(1, 1e-6)); + expect(b.color.g, closeTo(0, 1e-6)); + } + for (final s in tables.lineBloomDark) { + expect(s.color1.r, closeTo(1, 1e-6)); + } + // Resolved once per palette. + final palette = const BeamColors.solid(red).resolve(); + expect( + identical(BeamLook.tablesFor(palette), BeamLook.tablesFor(palette)), + isTrue, + ); + }); + + test('custom palettes spread each line table across its own streak', () { + // Black to white once round the ring: a blob's grey level says where + // across the streak it sampled the palette. + final tables = BeamLook.tablesFor( + const BeamColors( + [Color(0xFF000000), Color(0xFFFFFFFF)], + stops: [0, 0.999], + ).resolve(), + ); + for (final (name, blobs) in [ + ('lineDark', tables.lineDark), + ('lineLight', tables.lineLight), + ('lineInner', tables.lineInner), + ]) { + final across = [...blobs] + ..sort((a, b) => a.offsetX.compareTo(b.offsetX)); + expect(across.first.color.r, closeTo(0, 1e-3), reason: '$name: start'); + expect(across.last.color.r, greaterThan(0.99), reason: '$name: end'); + for (var i = 1; i < across.length; i++) { + expect( + across[i].color.r, + greaterThan(across[i - 1].color.r), + reason: + '$name: the blobs at ${across[i - 1].offsetX} and ' + '${across[i].offsetX} px sampled the same point', + ); + } + } + }); + + test('scaleAlpha keeps a preset tables, scaled', () { + final half = BeamLook.tablesFor( + BeamColors.ocean.scaleAlpha(0.5).resolve(), + ); + for (final (i, b) in half.border.indexed) { + expect(b.position, oceanTables.border[i].position); + expect(b.color.a, closeTo(oceanTables.border[i].color.a * 0.5, 1e-6)); + } + }); + }); + + group('segments', () { + final segments = { + 'bottomHalf': BeamSegment.bottomHalf, + 'topEdge': BeamSegment.topEdge, + 'wrapping': const BeamSegment( + start: BeamAnchor.fraction(0.85), + end: BeamAnchor.fraction(0.2), + ), + }; + + for (final MapEntry(key: name, value: effect) in effectsByName.entries) { + test('$name keeps its track inside the segment', () { + final r = renderer(); + for (final MapEntry(key: label, value: segment) in segments.entries) { + final config = configFor(effect, shape: BeamShape(segment: segment)); + final outline = BeamOutline(box, config.borderRadius); + final range = segment.resolve(outline); + final userStart = range.from; + final userSpan = BeamOutline.wrapFraction(range.to - range.from); + for (final t in instants) { + final canvas = recordFrame(r, config, phasesAt(config, t)); + if (canvas.draws.isEmpty) continue; + final d = r.debugFrame; + expect(d.trackSpan, greaterThan(0), reason: '$name/$label'); + var from = BeamOutline.wrapFraction(d.trackStart - userStart); + if (from > 1 - 1e-6) from = 0; + expect( + from + d.trackSpan, + lessThanOrEqualTo(userSpan + 1e-6), + reason: '$name/$label at ${t}s', + ); + } + } + }); + } + }); + + test('applyTrack writes the user segment, or the whole border', () { + final outline = BeamOutline( + box, + const BorderRadius.all(Radius.circular(16)), + ); + final d = BeamFrameData()..reset(); + applyTrack(d, null, outline, 0); + expect(d.trackSpan, 0); + applyTrack(d, BeamSegment.bottomHalf, outline, 6); + expect(d.trackSpan, closeTo(0.5, 1e-6)); + expect(d.trackFeather, greaterThan(0)); + expect(segmentTrack(d).span, closeTo(0.5, 1e-6)); + }); + + test('a lit frame is written for the box it paints', () { + final r = renderer(); + for (final effect in BeamEffect.values) { + final config = configFor(effect); + final canvas = recordFrame( + r, + config, + phasesAt(config, litSeconds(effect)), + ); + expect(canvas.draws, hasLength(1), reason: effect.name); + expect(r.debugFrame.outlineRect, box, reason: effect.name); + } + }); +} diff --git a/test/render/beam_outline_test.dart b/test/render/beam_outline_test.dart new file mode 100644 index 0000000..7f72ce1 --- /dev/null +++ b/test/render/beam_outline_test.dart @@ -0,0 +1,464 @@ +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flutter/painting.dart'; +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/render/beam_frame.dart'; +import 'package:flutter_border_beam/src/render/beam_outline.dart'; +import 'package:flutter_border_beam/src/render/beam_program.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + for (final squircle in [false, true]) { + for (final radius in [0.0, 6.0, 16.0, 40.0, 70.0]) { + test('round trip, squircle: $squircle, r: $radius', () { + final o = BeamOutline( + const Rect.fromLTWH(10, 20, 350, 140), + BorderRadius.circular(radius), + superellipse: squircle, + ); + for (var i = 0; i < 400; i++) { + final u = i / 400; + final p = o.pointAt(u); + final hit = o.locate(p); + expect(hit.distance.abs(), lessThan(0.05), reason: 'u=$u d'); + final du = (hit.u - u + 0.5) % 1 - 0.5; + expect(du.abs(), lessThan(1e-3), reason: 'u=$u got ${hit.u}'); + // A point pushed out along the normal stays at that u. + final out = o.locate(p + o.normalAt(u) * 7); + expect(out.distance, closeTo(7, 0.35), reason: 'u=$u out'); + final duo = (out.u - u + 0.5) % 1 - 0.5; + expect(duo.abs(), lessThan(0.02), reason: 'u=$u out u'); + } + }); + } + } + + test('edges run clockwise from top-centre', () { + final o = BeamOutline( + const Rect.fromLTWH(0, 0, 300, 100), + BorderRadius.circular(10), + ); + expect(o.fractionOfEdge(BeamEdge.top, 0.5), closeTo(0, 1e-6)); + final right = o.fractionOfEdge(BeamEdge.right, 0.5); + final bottom = o.fractionOfEdge(BeamEdge.bottom, 0.5); + final left = o.fractionOfEdge(BeamEdge.left, 0.5); + expect(bottom, closeTo(0.5, 1e-6)); + expect(right, lessThan(bottom)); + expect(left, greaterThan(bottom)); + expect(o.pointAt(bottom).dy, closeTo(100, 1e-6)); + expect(o.length, closeTo(2 * (280 + 80) + 2 * math.pi * 10, 1e-6)); + }); + + const rect = Rect.fromLTWH(0, 0, 300, 100); + + group('radii', () { + test('per-corner radii stay on the corners they name', () { + final o = BeamOutline( + rect, + const BorderRadius.only( + topLeft: Radius.circular(30), + bottomRight: Radius.circular(10), + ), + ); + expect(o.radii, [30, 0, 10, 0]); + // A square corner keeps the box corner on the outline; a rounded one + // pulls the outline away from it. + expect(o.locate(rect.topRight).distance.abs(), lessThan(0.01)); + expect(o.locate(rect.topLeft).distance, greaterThan(5)); + expect(o.locate(rect.bottomRight).distance, greaterThan(1)); + }); + + test('overflowing radii scale down the way RRect.scaleRadii does', () { + const radius = BorderRadius.only( + topLeft: Radius.circular(200), + topRight: Radius.circular(200), + bottomLeft: Radius.circular(40), + ); + final o = BeamOutline(rect, radius); + final scaled = radius.toRRect(rect).scaleRadii(); + expect(o.radii[0], closeTo(scaled.tlRadiusX, 1e-9)); + expect(o.radii[1], closeTo(scaled.trRadiusX, 1e-9)); + expect(o.radii[3], closeTo(scaled.blRadiusX, 1e-9)); + // Both overflowing radii shrink by the same ratio. + expect(o.radii[0], o.radii[1]); + }); + + test('an infinite radius rounds to half the short side', () { + final pill = BeamOutline( + rect, + const BorderRadius.all(Radius.circular(double.infinity)), + ); + expect(pill.radii, everyElement(closeTo(50, 1e-9))); + final circle = BeamOutline( + const Rect.fromLTWH(0, 0, 80, 80), + const BorderRadius.all(Radius.circular(double.infinity)), + ); + expect(circle.length, closeTo(math.pi * 80, 1e-6)); + for (var i = 0; i < 64; i++) { + final p = circle.pointAt(i / 64); + expect((p - const Offset(40, 40)).distance, closeTo(40, 1e-6)); + } + }); + + test('superellipse corners reach radius × squircleReach along each ' + 'edge, capped at half that side', () { + final o = BeamOutline( + rect, + BorderRadius.circular(16), + superellipse: true, + ); + expect(o.cornerSizes, everyElement(closeTo(16 * squircleReach, 1e-9))); + // A pill's corners take the full height but still ease into the long + // edges: each side caps the reach separately. + final pill = BeamOutline( + const Rect.fromLTWH(0, 0, 270, 56), + BorderRadius.circular(28), + superellipse: true, + ); + expect(pill.cornerSizes, everyElement(closeTo(28 * squircleReach, 1e-9))); + final top = pill.edgeRange(BeamEdge.top); + expect(pill.pointAt(top.to).dx, closeTo(270 - 28 * squircleReach, 1e-6)); + expect(pill.pointAt(top.to).dy, closeTo(0, 1e-9)); + final right = pill.edgeRange(BeamEdge.right); + expect(BeamOutline.wrapFraction(right.to - right.from), lessThan(1e-9)); + }); + }); + + group("the superellipse is Flutter's RSuperellipse", () { + // The beam's stroke must sit on the edge of a child clipped or decorated + // by RoundedSuperellipseBorder with the same radii, at every aspect + // ratio: Flutter's corner changes shape as the radius nears half the + // side, so one fixed corner curve parts from it on pills and circles. + final shapes = { + 'card r8': (const Rect.fromLTWH(10, 10, 300, 200), _r(8)), + 'card r24': (const Rect.fromLTWH(10, 10, 300, 200), _r(24)), + 'wide card r16': (const Rect.fromLTWH(0, 0, 350, 140), _r(16)), + 'large card r4': (const Rect.fromLTWH(0, 0, 1000, 600), _r(4)), + 'square r16': (const Rect.fromLTWH(0, 0, 100, 100), _r(16)), + 'r = 0.3 short side': (const Rect.fromLTWH(0, 0, 300, 200), _r(60)), + 'r = 0.4 short side': (const Rect.fromLTWH(0, 0, 300, 200), _r(80)), + 'square, r = 0.4 side': (const Rect.fromLTWH(0, 0, 200, 200), _r(80)), + 'chip, r = 0.4 short side': (const Rect.fromLTWH(0, 0, 120, 60), _r(24)), + 'pill 270×56': (const Rect.fromLTWH(0, 0, 270, 56), _r(28)), + // BeamShape.stadium: Flutter spells the same pill with half the + // short side (it reads an infinite radius as no radius at all). + 'stadium pill': (const Rect.fromLTWH(0, 0, 270, 56), _stadium), + 'stadium circle': (const Rect.fromLTWH(0, 0, 120, 120), _stadium), + 'thin pill 300×40': (const Rect.fromLTWH(0, 0, 300, 40), _r(20)), + 'short pill 70×56': (const Rect.fromLTWH(0, 0, 70, 56), _r(28)), + 'tall pill 56×270': (const Rect.fromLTWH(0, 0, 56, 270), _r(28)), + 'stadium 200×100': (const Rect.fromLTWH(0, 0, 200, 100), _r(50)), + 'circle 56': (const Rect.fromLTWH(0, 0, 56, 56), _r(28)), + 'circle 200': (const Rect.fromLTWH(0, 0, 200, 200), _r(100)), + 'uneven radii': ( + const Rect.fromLTWH(0, 0, 300, 180), + const BorderRadius.only( + topLeft: Radius.circular(40), + topRight: Radius.circular(12), + bottomRight: Radius.circular(8), + bottomLeft: Radius.circular(20), + ), + ), + 'chat bubble': ( + const Rect.fromLTWH(0, 0, 200, 60), + const BorderRadius.only( + topLeft: Radius.circular(16), + topRight: Radius.circular(16), + bottomRight: Radius.circular(4), + bottomLeft: Radius.circular(16), + ), + ), + }; + + for (final MapEntry(key: name, value: (box, radius)) in shapes.entries) { + test("$name: the outline lies on Flutter's path", () { + final o = BeamOutline(box, radius, superellipse: true); + final flutter = _flutterOutline(box, radius); + // Flutter's points are on the outline... + var worst = 0.0; + for (final p in flutter) { + worst = math.max(worst, o.locate(p).distance.abs()); + } + // ...and the outline's points are on Flutter's path. Flutter's own + // path approximates its curve with conics to within ~0.06 px here. + for (var i = 0; i < 1500; i++) { + worst = math.max(worst, _distanceTo(flutter, o.pointAt(i / 1500))); + } + expect(worst, lessThan(0.1), reason: name); + }); + } + + test('inside and outside agree with RSuperellipse.contains', () { + for (final MapEntry(key: name, value: (box, radius)) in shapes.entries) { + final o = BeamOutline(box, radius, superellipse: true); + final rse = _flutterRadius(box, radius).toRSuperellipse(box); + for (var y = box.top - 3; y <= box.bottom + 3; y += 1.5) { + for (var x = box.left - 3; x <= box.right + 3; x += 1.5) { + final p = Offset(x, y); + final d = o.locate(p).distance; + if (d.abs() < 0.1) continue; + expect(d < 0, rse.contains(p), reason: '$name at $p (d = $d)'); + } + } + } + }); + + test('distance is continuous near the border, inside and out', () { + // A soft glow or inset shadow shades by the distance tens of px from + // the stroke; a step where the curve's pieces meet would show as a + // seam. Neighbouring samples may differ by at most their spacing. + for (final name in ['card r24', 'r = 0.4 short side', 'pill 270×56']) { + final (box, radius) = shapes[name]!; + final o = BeamOutline(box, radius, superellipse: true); + const step = 0.5; + final corner = box.topRight; + double at(double x, double y) => o.locate(Offset(x, y)).distance; + for (var y = corner.dy - 30; y <= corner.dy + 60; y += step) { + for (var x = corner.dx - 160; x <= corner.dx + 30; x += step) { + final d = at(x, y); + if (d < -20 || d > 30) continue; + expect( + (at(x + step, y) - d).abs(), + lessThan(step + 0.02), + reason: '$name at ($x, $y)', + ); + expect( + (at(x, y + step) - d).abs(), + lessThan(step + 0.02), + reason: '$name at ($x, $y)', + ); + } + } + } + }); + + test('distance off the border matches the nearest point of the path', () { + for (final name in ['card r24', 'pill 270×56', 'circle 56']) { + final (box, radius) = shapes[name]!; + final o = BeamOutline(box, radius, superellipse: true); + final flutter = _flutterOutline(box, radius); + for (var i = 0; i < 200; i++) { + final u = i / 200; + for (final offset in [-12.0, -4.0, 4.0, 12.0, 24.0]) { + final p = o.pointAt(u) + o.normalAt(u) * offset; + expect( + o.locate(p).distance, + closeTo(offset.sign * _distanceTo(flutter, p), 0.2), + reason: '$name u=$u offset $offset', + ); + } + } + } + }); + }); + + group("the shader's outline() is BeamOutline", () { + // Rule 3: the GPU and the CPU must agree on where the outline is, or + // lights placed along it on the CPU drift off the stroke the GPU draws. + // A filled layer's anti-aliased edge encodes the shader's distance: + // alpha = 0.5 − d / px. + setUpAll(BorderBeam.precache); + + final shapes = { + 'pill': (const Size(270, 56), _r(28)), + 'card': (const Size(300, 200), _r(24)), + 'r = 0.4 short side': (const Size(300, 200), _r(80)), + 'circle': (const Size(120, 120), _r(60)), + 'uneven radii': ( + const Size(300, 180), + const BorderRadius.only( + topLeft: Radius.circular(40), + topRight: Radius.circular(12), + bottomRight: Radius.circular(8), + bottomLeft: Radius.circular(20), + ), + ), + }; + + for (final superellipse in [false, true]) { + for (final MapEntry(key: name, value: (size, radius)) in shapes.entries) { + test('$name, superellipse: $superellipse', () async { + // An iPhone's 3x, where a few device px of gap show. + const scale = 3.0; + const margin = 6.0; + final box = const Offset(margin, margin) & size; + final o = BeamOutline(box, radius, superellipse: superellipse); + final frame = BeamFrameData() + ..reset() + ..setOutline(o, 1, 1 / scale) + ..setLayer(0, BeamGeometry.fill, opacity: 1) + ..setTable(BeamTable.overlayA, const [0, 1], const [1, 1], 2) + ..setOverlay(0, BeamTable.overlayA, white: true) + ..finish(); + final shader = BeamProgram.program!.fragmentShader(); + for (var i = 0; i < beamUniformFloats; i++) { + shader.setFloat(i, frame.data[i]); + } + final recorder = ui.PictureRecorder(); + ui.Canvas(recorder) + ..scale(scale) + ..drawRect(box.inflate(margin), ui.Paint()..shader = shader); + final picture = recorder.endRecording(); + final w = (box.inflate(margin).width * scale).ceil(); + final h = (box.inflate(margin).height * scale).ceil(); + final image = await picture.toImage(w, h); + final bytes = (await image.toByteData())!.buffer.asUint8List(); + picture.dispose(); + image.dispose(); + shader.dispose(); + + var edge = 0; + for (var y = 0; y < h; y++) { + for (var x = 0; x < w; x++) { + final alpha = bytes[(y * w + x) * 4 + 3] / 255; + final p = Offset((x + 0.5) / scale, (y + 0.5) / scale); + final d = o.locate(p).distance; + if (alpha > 0.02 && alpha < 0.98) { + edge++; + expect( + (0.5 - alpha) / scale, + closeTo(d, 0.02), + reason: '$name at $p', + ); + } else if (d.abs() > 1 / scale) { + expect(alpha > 0.5, d < 0, reason: '$name at $p (d = $d)'); + } + } + } + expect(edge, greaterThan(300)); + }); + } + } + }); + + test('distance is negative inside and positive outside', () { + for (final squircle in [false, true]) { + final o = BeamOutline( + rect, + BorderRadius.circular(20), + superellipse: squircle, + ); + expect(o.locate(rect.center).distance, lessThan(0)); + expect(o.locate(const Offset(150, -10)).distance, closeTo(10, 1e-6)); + expect(o.locate(const Offset(150, 10)).distance, closeTo(-10, 1e-6)); + expect(o.locate(const Offset(-5, -5)).distance, greaterThan(5)); + } + }); + + test('u runs clockwise and covers the whole perimeter', () { + final o = BeamOutline(rect, BorderRadius.circular(24)); + var area = 0.0; + var travelled = 0.0; + var prev = o.pointAt(0); + for (var i = 1; i <= 1000; i++) { + final p = o.pointAt(i / 1000); + // Shoelace sum: positive for clockwise in a y-down frame. + area += prev.dx * p.dy - p.dx * prev.dy; + travelled += (p - prev).distance; + prev = p; + } + expect(area, greaterThan(0)); + expect(travelled, closeTo(o.length, 0.5)); + expect(o.pointAt(0).dx, closeTo(rect.topCenter.dx, 1e-6)); + expect(o.pointAt(0).dy, closeTo(rect.topCenter.dy, 1e-6)); + }); + + test('edge and corner ranges tile the perimeter in order', () { + final o = BeamOutline( + rect, + const BorderRadius.only( + topLeft: Radius.circular(10), + topRight: Radius.circular(30), + bottomRight: Radius.circular(5), + ), + ); + final pieces = [ + o.edgeRange(BeamEdge.top), + o.cornerRange(BeamCorner.topRight), + o.edgeRange(BeamEdge.right), + o.cornerRange(BeamCorner.bottomRight), + o.edgeRange(BeamEdge.bottom), + o.cornerRange(BeamCorner.bottomLeft), + o.edgeRange(BeamEdge.left), + o.cornerRange(BeamCorner.topLeft), + ]; + var total = 0.0; + for (var i = 0; i < pieces.length; i++) { + final next = pieces[(i + 1) % pieces.length]; + final gap = (next.from - pieces[i].to + 0.5) % 1 - 0.5; + expect(gap.abs(), lessThan(1e-6), reason: 'piece $i meets piece $i+1'); + total += BeamOutline.wrapFraction(pieces[i].to - pieces[i].from); + } + expect(total, closeTo(1, 1e-6)); + // A square corner has (next to) no curve at all. + final bl = o.cornerRange(BeamCorner.bottomLeft); + expect(BeamOutline.wrapFraction(bl.to - bl.from), lessThan(1e-4)); + }); + + test('wrapFraction wraps into [0, 1)', () { + expect(BeamOutline.wrapFraction(0), 0); + expect(BeamOutline.wrapFraction(1), 0); + expect(BeamOutline.wrapFraction(-0.25), closeTo(0.75, 1e-12)); + expect(BeamOutline.wrapFraction(3.5), closeTo(0.5, 1e-12)); + }); + + test('an empty box is safe', () { + final o = BeamOutline(Rect.zero, BorderRadius.circular(16)); + expect(o.length.isFinite, isTrue); + expect(o.pointAt(0.3).dx.isFinite, isTrue); + expect(o.normalAt(0.3).dx.isFinite, isTrue); + expect(o.nearestFraction(const Offset(4, 4)).isFinite, isTrue); + }); + + test('outlines are values', () { + BeamOutline make({bool squircle = false}) => + BeamOutline(rect, BorderRadius.circular(12), superellipse: squircle); + expect(make(), make()); + expect(make().hashCode, make().hashCode); + expect(make(), isNot(make(squircle: true))); + expect( + make(), + isNot(BeamOutline(rect.inflate(1), BorderRadius.circular(12))), + ); + }); +} + +BorderRadius _r(double radius) => BorderRadius.circular(radius); + +const BorderRadius _stadium = BorderRadius.all( + Radius.circular(double.infinity), +); + +/// The radii Flutter needs for the shape the beam draws with [radius]: +/// the same, except a stadium's infinite radius is half the short side. +BorderRadius _flutterRadius(Rect box, BorderRadius radius) => + radius == _stadium ? _r(box.shortestSide / 2) : radius; + +/// Flutter's own superellipse for [box], sampled every quarter pixel. +List _flutterOutline(Rect box, BorderRadius radius) { + final path = RoundedSuperellipseBorder( + borderRadius: _flutterRadius(box, radius), + ).getOuterPath(box); + return [ + for (final metric in path.computeMetrics()) + for (var s = 0.0; s < metric.length; s += 0.25) + metric.getTangentForOffset(s)!.position, + ]; +} + +/// Distance from [p] to the closed polyline through [points]. +double _distanceTo(List points, Offset p) { + var best = double.infinity; + for (var i = 0; i < points.length; i++) { + final a = points[i]; + if ((a - p).distance > best + 1) continue; + final ab = points[(i + 1) % points.length] - a; + final t = ab.distanceSquared == 0 + ? 0.0 + : (((p - a).dx * ab.dx + (p - a).dy * ab.dy) / ab.distanceSquared) + .clamp(0.0, 1.0); + best = math.min(best, (p - (a + ab * t)).distance); + } + return best; +} diff --git a/test/render/beam_program_test.dart b/test/render/beam_program_test.dart new file mode 100644 index 0000000..628f2c8 --- /dev/null +++ b/test/render/beam_program_test.dart @@ -0,0 +1,26 @@ +import 'dart:async'; + +import 'package:flutter_border_beam/src/render/beam_program.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// `BeamProgram`: one shader load, shared by every caller that asks while it +/// is in flight. Nothing else in this file loads the program, so it starts +/// unloaded. +void main() { + test('calls while a load is in flight share it', () async { + expect(BeamProgram.program, isNull, reason: 'nothing has loaded it yet'); + final first = BeamProgram.load(); + expect(BeamProgram.load(), same(first)); + // A caller in another zone does not wait on this zone's load, which + // under a widget test's fake clock might never complete. + final elsewhere = runZoned(BeamProgram.load); + expect(elsewhere, isNot(same(first))); + await Future.wait([first, elsewhere]); + + final program = BeamProgram.program; + expect(program, isNotNull); + expect(BeamProgram.ready.value, isTrue); + await BeamProgram.load(); + expect(BeamProgram.program, same(program), reason: 'loaded only once'); + }); +} diff --git a/test/render/boundary_test.dart b/test/render/boundary_test.dart new file mode 100644 index 0000000..3eda335 --- /dev/null +++ b/test/render/boundary_test.dart @@ -0,0 +1,298 @@ +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/render/beam_renderer.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +import 'render_utils.dart'; + +/// Degenerate geometry and out-of-range parameters: nothing throws, nothing +/// the shader is handed is non-finite, and a beam at zero strength paints no +/// pixel at all. +void main() { + setUpAll(BorderBeam.precache); + + final boxes = { + 'zero': Size.zero, + '1px': const Size(1, 1), + '2px': const Size(2, 2), + 'vertical sliver': const Size(1, 120), + 'horizontal sliver': const Size(240, 1), + 'thin strip': const Size(300, 3), + 'tiny square': const Size(6, 6), + 'huge': const Size(4000, 3000), + }; + + // Mid-sweep, deep into a gap-carrying period, and many cycles in. + const instants = [0.7, 1.3, 2.2, 61.7]; + + /// Paints [effect] at every instant, in both brightnesses, at each of + /// [sizes], checking every frame that draws. Returns how many frames at + /// [cardSize] drew, so a case that should light the card can require it — + /// a renderer that bailed out on every frame would otherwise pass. + int paintEverywhere( + BeamEffect effect, + String label, { + BeamStyle style = const BeamStyle(), + BeamShape shape = const BeamShape(), + BeamTiming timing = const BeamTiming(), + Iterable? sizes, + }) { + final renderer = BeamRenderer(); + addTearDown(renderer.dispose); + var paintedCards = 0; + for (final brightness in Brightness.values) { + final config = configFor( + effect, + brightness: brightness, + style: style, + shape: shape, + timing: timing, + ); + for (final size in sizes ?? [cardSize]) { + for (final t in instants) { + final canvas = recordFrame( + renderer, + config, + phasesAt(config, t), + size: size, + ); + expect(canvas.draws.length, lessThanOrEqualTo(1)); + if (canvas.draws.isEmpty) continue; + if (size == cardSize) paintedCards++; + expectSaneFrame( + renderer.debugFrame, + '${effect.name}: $label, $size at ${t}s', + drawBounds: canvas.drawBounds.single, + ); + } + } + } + return paintedCards; + } + + for (final MapEntry(key: name, value: effect) in effectsByName.entries) { + group(name, () { + test('degenerate boxes', () { + paintEverywhere(effect, 'boxes', sizes: boxes.values); + paintEverywhere( + effect, + 'stadium boxes', + shape: const BeamShape.stadium(), + sizes: boxes.values, + ); + paintEverywhere( + effect, + 'superellipse boxes', + shape: const BeamShape.all(30, superellipse: true), + sizes: boxes.values, + ); + }); + + test('a radius past half the short side', () { + expect( + paintEverywhere( + effect, + 'radius 500', + shape: const BeamShape.all(500), + ), + greaterThan(0), + ); + paintEverywhere( + effect, + 'per-corner overflow', + shape: const BeamShape( + radius: BorderRadius.only( + topLeft: Radius.circular(300), + topRight: Radius.circular(300), + bottomLeft: Radius.elliptical(400, 10), + ), + ), + ); + }); + + test('border widths from zero to wider than the box', () { + for (final width in [0.0, 0.25, 70.0, 500.0]) { + paintEverywhere( + effect, + 'borderWidth $width', + shape: BeamShape(borderWidth: width), + sizes: [cardSize, const Size(4, 4)], + ); + } + }); + + test('ring offsets that grow or collapse the outline', () { + for (final offset in [-69.0, -70.0, -500.0, 40.0]) { + final painted = paintEverywhere( + effect, + 'ringOffset $offset', + shape: BeamShape(ringOffset: offset), + ); + if (offset > 0) expect(painted, greaterThan(0), reason: '$offset'); + } + }); + + test('segments, dashes, and feathers at their extremes', () { + final segments = [ + const BeamSegment( + start: BeamAnchor.fraction(0.3), + end: BeamAnchor.fraction(0.3), + ), + const BeamSegment( + start: BeamAnchor.fraction(0.3), + end: BeamAnchor.fraction(0.3001), + feather: 0, + ), + const BeamSegment( + start: BeamAnchor.fraction(-2.25), + end: BeamAnchor.fraction(7.5), + feather: 1e6, + ), + BeamSegment.bottomEdge, + ]; + for (final segment in segments) { + paintEverywhere( + effect, + '$segment', + shape: BeamShape(segment: segment), + sizes: [cardSize, const Size(1, 1)], + ); + } + for (final dashes in [1, 2, 1000]) { + expect( + paintEverywhere( + effect, + 'dashes $dashes', + shape: BeamShape(dashes: dashes), + ), + greaterThan(0), + reason: 'dashes $dashes', + ); + } + }); + + test('style and timing at their extremes', () { + for (final glow in [0.0, 25.0]) { + expect( + paintEverywhere(effect, 'glow $glow', style: BeamStyle(glow: glow)), + greaterThan(0), + reason: 'glow $glow', + ); + } + for (final strength in [-1.0, 1e-6, 7.0]) { + final painted = paintEverywhere( + effect, + 'strength $strength', + style: BeamStyle(strength: strength), + ); + if (strength > 0) { + expect(painted, greaterThan(0), reason: 'strength $strength'); + } + } + for (final bad in [double.nan, double.infinity]) { + // Each falls back to its default, and the strength to full: the + // beam still lights the card. + expect( + paintEverywhere( + effect, + 'non-finite $bad', + style: BeamStyle( + strength: bad, + // NaN fails the constructor's `glow >= 0` assertion. + glow: bad.isNaN ? null : bad, + hueShift: bad, + hueBase: bad, + hueMode: BeamHueMode.pingPong, + ), + shape: BeamShape(borderWidth: bad, ringOffset: bad), + ), + greaterThan(0), + reason: 'non-finite $bad', + ); + } + expect( + paintEverywhere( + effect, + 'hue extremes', + style: const BeamStyle( + hueShift: 3600, + hueBase: -720, + hueMode: BeamHueMode.pingPong, + ), + ), + greaterThan(0), + ); + for (final cycle in [ + const Duration(microseconds: 1), + const Duration(milliseconds: 1), + const Duration(hours: 1), + ]) { + paintEverywhere( + effect, + 'cycle $cycle', + timing: BeamTiming( + cycle: cycle, + cycleGap: const Duration(hours: 1), + huePeriod: const Duration(microseconds: 1), + ), + ); + } + }); + + test('zero strength paints no pixel at all', () async { + for (final brightness in Brightness.values) { + final config = configFor( + effect, + brightness: brightness, + style: const BeamStyle(strength: 0, glow: 3), + shape: const BeamShape(ringOffset: 12), + ); + final frame = await renderFrame(config, phasesAt(config, 1.3)); + expect(frame.lit(), 0, reason: '$name/${brightness.name}'); + } + }); + }); + } + + group('mounted', () { + testWidgets('a beam collapsed to zero size builds and paints', ( + tester, + ) async { + for (final effect in BeamEffect.values) { + await tester.pumpWidget( + Center( + child: BorderBeam(effect: effect, child: const SizedBox.shrink()), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 700)); + expect(tester.takeException(), isNull, reason: effect.name); + } + await tester.pumpWidget(const SizedBox()); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('a zero-height child in a Column', (tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Column( + children: [ + for (final effect in BeamEffect.values) + BorderBeam( + effect: effect, + shape: const BeamShape(ringOffset: 6), + child: const SizedBox(width: 200, height: 0), + ), + ], + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 700)); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + expect(tester.binding.transientCallbackCount, 0); + }); + }); +} diff --git a/test/render/frame_budget_test.dart b/test/render/frame_budget_test.dart new file mode 100644 index 0000000..2eff59a --- /dev/null +++ b/test/render/frame_budget_test.dart @@ -0,0 +1,271 @@ +import 'dart:ui' as ui; +import 'dart:ui' show Brightness; + +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/models/beam_config.dart'; +import 'package:flutter_border_beam/src/render/beam_frame.dart'; +import 'package:flutter_border_beam/src/render/beam_program.dart'; +import 'package:flutter_border_beam/src/render/beam_renderer.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'render_utils.dart'; + +/// The renderer's cost contract: a beam frame is ONE draw call with the beam +/// shader — no `saveLayer` (no offscreen target), no clip, no image or mask +/// filter (no blur pass) — and it leaves the canvas state as it found it. +/// +/// Every effect is measured across both themes, a palette subset, every shape +/// family, and several instants. A frame the fade or a cycle gap has blacked +/// out issues no draw at all; any other frame issues exactly one. +void main() { + setUpAll(() async { + await BorderBeam.precache(); + expect( + BeamProgram.program, + isNotNull, + reason: 'the budget is only meaningful with the shader loaded', + ); + }); + + // Early, the golden instant, late in a sweep, and several cycles in. + const goldenInstant = 1.3; + const instants = [0.3, goldenInstant, 2.05, 7.9]; + + // Whether the frame had light to draw: the fade and strength let some + // through, and the effect lit a layer. + bool litFrame(BeamRenderer renderer, BeamConfig config, double fade) { + if (fade * config.strength <= 0) return false; + final d = renderer.debugFrame; + for (var k = 0; k < beamLayerCount; k++) { + if (d.geometryOf(k) != BeamGeometry.none && d.opacityOf(k) > 0) { + return true; + } + } + return false; + } + + void expectBudget( + RecordingCanvas canvas, + BeamConfig config, + double fade, + String label, { + required bool lit, + }) { + expect( + canvas.unforwarded, + isEmpty, + reason: + '$label: the frame called ${canvas.unforwarded.join(', ')}, which ' + 'the recording canvas does not count — a new kind of call needs an ' + 'explicit override here', + ); + expect(canvas.saveLayers, 0, reason: '$label: saveLayer'); + expect(canvas.clips, 0, reason: '$label: clip'); + expect(canvas.saves, canvas.restores, reason: '$label: save/restore'); + expect( + canvas.draws, + lit ? hasLength(1) : isEmpty, + reason: '$label: ${canvas.draws}', + ); + for (final draw in canvas.draws) { + expect(draw, anyOf('drawRect', 'drawDRRect'), reason: label); + } + for (final paint in canvas.paints) { + expect(paint.shader, isA(), reason: label); + expect(paint.imageFilter, isNull, reason: '$label: imageFilter'); + expect(paint.maskFilter, isNull, reason: '$label: maskFilter'); + } + } + + for (final MapEntry(key: name, value: effect) in effectsByName.entries) { + test('$name: one draw, no layers, clips, or filters', () { + final renderer = BeamRenderer(); + addTearDown(renderer.dispose); + for (final brightness in Brightness.values) { + for (final MapEntry(key: palette, value: colors) + in paletteSubset.entries) { + final config = configFor( + effect, + brightness: brightness, + colors: colors, + ); + for (final t in instants) { + final phases = phasesAt(config, t); + final canvas = recordFrame(renderer, config, phases); + final label = '$name/${brightness.name}/$palette at ${t}s'; + final lit = litFrame(renderer, config, phases.fadeOpacity); + // The golden instant is mid-sweep for every effect, so it has + // light to draw; without this a renderer that drew nothing would + // pass the budget by issuing no calls at all. (Elsewhere a frame + // can be dark: the line fades its streak in and out each sweep.) + if (t == goldenInstant) { + expect(lit, isTrue, reason: '$label: an unlit running frame'); + } + expectBudget(canvas, config, phases.fadeOpacity, label, lit: lit); + } + } + } + }); + + test('$name: every shape family keeps the budget', () { + final renderer = BeamRenderer(); + addTearDown(renderer.dispose); + for (final MapEntry(key: label, value: shape) in shapeVariety.entries) { + final config = configFor(effect, shape: shape); + for (final t in instants) { + final phases = phasesAt(config, t); + final canvas = recordFrame(renderer, config, phases); + final lit = litFrame(renderer, config, phases.fadeOpacity); + // A segment may hide all of the light; every other shape keeps + // some of it at the golden instant. + if (t == goldenInstant && shape.segment == null) { + expect(lit, isTrue, reason: '$name/$label at ${t}s: unlit'); + } + expectBudget( + canvas, + config, + phases.fadeOpacity, + '$name/$label at ${t}s', + lit: lit, + ); + } + } + }); + } + + test('effect options keep the budget', () { + final options = { + 'rotate comet': const BeamEffect.rotate(comet: true), + 'rotate count 4': const BeamEffect.rotate(count: 4), + 'rotate long tail': const BeamEffect.rotate(length: 2), + 'line top': const BeamEffect.line(edge: BeamEdge.top), + 'line left': const BeamEffect.line(edge: BeamEdge.left), + }; + final renderer = BeamRenderer(); + addTearDown(renderer.dispose); + for (final MapEntry(key: label, value: effect) in options.entries) { + for (final glow in [0.0, 1.0, 2.5]) { + final config = configFor(effect, style: BeamStyle(glow: glow)); + for (final t in instants) { + final phases = phasesAt(config, t); + expectBudget( + recordFrame(renderer, config, phases), + config, + phases.fadeOpacity, + '$label, glow $glow at ${t}s', + lit: litFrame(renderer, config, phases.fadeOpacity), + ); + } + } + } + }); + + test('a cycle gap keeps the budget, and its rest draws nothing', () { + final renderer = BeamRenderer(); + addTearDown(renderer.dispose); + const gap = Duration(seconds: 1); + for (final effect in BeamEffect.values.where((e) => e.travels)) { + final config = configFor(effect, timing: const BeamTiming(cycleGap: gap)); + final cycle = config.cycleSeconds; + final rest = config.gapSeconds; + // Mid-sweep, easing out, mid-rest, and easing back in. + for (final t in [ + cycle / 2, + cycle + rest * 0.1, + cycle + rest / 2, + cycle + rest * 0.9, + ]) { + final phases = phasesAt(config, t); + final canvas = recordFrame(renderer, config, phases); + expectBudget( + canvas, + config, + phases.fadeOpacity, + '${effect.name} with a gap at ${t}s', + lit: litFrame(renderer, config, phases.fadeOpacity), + ); + } + final resting = phasesAt(config, cycle + rest / 2); + expect( + recordFrame(renderer, config, resting).draws, + isEmpty, + reason: '${effect.name}: mid-rest', + ); + } + }); + + test('a driven sweep keeps the budget at every progress', () { + final renderer = BeamRenderer(); + addTearDown(renderer.dispose); + for (final effect in BeamEffect.values.where((e) => e.travels)) { + final config = configFor(effect); + for (final progress in [0.0, 0.001, 0.25, 0.5, 0.999, 1.0]) { + final phases = phasesAt(config, 1.3, progress: progress); + expectBudget( + recordFrame(renderer, config, phases), + config, + phases.fadeOpacity, + '${effect.name} at progress $progress', + lit: litFrame(renderer, config, phases.fadeOpacity), + ); + } + } + }); + + test('a zero-strength or fully faded frame draws nothing', () { + final renderer = BeamRenderer(); + addTearDown(renderer.dispose); + for (final effect in BeamEffect.values) { + final dim = configFor(effect, style: const BeamStyle(strength: 0)); + expect(recordFrame(renderer, dim, phasesAt(dim, 1.3)).draws, isEmpty); + final config = configFor(effect); + expect( + recordFrame(renderer, config, phasesAt(config, 1.3, fade: 0)).draws, + isEmpty, + ); + } + }); + + test('frames reuse one Paint and one FragmentShader', () { + // The renderer rewrites the shader's uniforms in place: steady-state + // frames allocate neither a Paint nor a shader. + final renderer = BeamRenderer(); + addTearDown(renderer.dispose); + final config = configFor(const BeamEffect.rotate()); + final first = recordFrame(renderer, config, phasesAt(config, 1.0)); + final second = recordFrame(renderer, config, phasesAt(config, 1.5)); + expect(identical(first.paints.single, second.paints.single), isTrue); + expect( + identical(first.paints.single.shader, second.paints.single.shader), + isTrue, + ); + }); + + test('the draw covers the box, and hugs it when no light reaches out', () { + // The single draw is the region light can reach: it must contain the + // whole outline, and a frame whose light all stays inside the border + // must not shade the space around the box. + final renderer = BeamRenderer(); + addTearDown(renderer.dispose); + final box = const Offset(renderMargin, renderMargin) & cardSize; + for (final effect in BeamEffect.values) { + final config = configFor(effect); + final canvas = recordFrame(renderer, config, phasesAt(config, 1.3)); + final bounds = canvas.drawBounds.single; + expect( + bounds.contains(box.topLeft) && bounds.contains(box.bottomRight), + isTrue, + reason: '${effect.name}: $bounds must contain $box', + ); + final reachesOut = renderer.debugFrame.reachOutside > 0; + if (!reachesOut) { + expect( + box.inflate(4).contains(bounds.topLeft) && + box.inflate(4).contains(bounds.bottomRight), + isTrue, + reason: '${effect.name}: inward-only light drew $bounds', + ); + } + } + }); +} diff --git a/test/render/paint_smoke_test.dart b/test/render/paint_smoke_test.dart new file mode 100644 index 0000000..7d9e237 --- /dev/null +++ b/test/render/paint_smoke_test.dart @@ -0,0 +1,67 @@ +import 'dart:ui' show Brightness; + +import 'package:flutter/painting.dart'; +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/render/beam_renderer.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'render_utils.dart'; + +/// Every effect × theme × palette subset × shape family paints visible light +/// through the real shader. A path the renderer cannot handle — a uniform +/// packed wrong, a shape the outline collapses, a palette the colour map +/// chokes on — shows up here as a blank frame. +void main() { + setUpAll(BorderBeam.precache); + + for (final MapEntry(key: name, value: effect) in effectsByName.entries) { + group(name, () { + for (final brightness in Brightness.values) { + for (final MapEntry(key: palette, value: colors) + in paletteSubset.entries) { + test('${brightness.name} $palette on every shape', () async { + final renderer = BeamRenderer(); + addTearDown(renderer.dispose); + for (final MapEntry(key: shapeName, value: shape) + in shapeVariety.entries) { + final config = configFor( + effect, + brightness: brightness, + colors: colors, + shape: shape, + ); + final frame = await renderFrame( + config, + phasesAt(config, litSeconds(effect)), + renderer: renderer, + ); + expect( + frame.lit(threshold: 8), + greaterThan(0), + reason: '$name/${brightness.name}/$palette/$shapeName is blank', + ); + } + }); + } + } + }); + } + + test('a superellipse and a stadium paint the small chip size too', () async { + const chip = Size(70, 36); + for (final effect in BeamEffect.values) { + for (final shape in [ + const BeamShape.all(18, superellipse: true), + const BeamShape.stadium(), + ]) { + final config = configFor(effect, shape: shape); + final frame = await renderFrame( + config, + phasesAt(config, litSeconds(effect)), + size: chip, + ); + expect(frame.lit(threshold: 8), greaterThan(0), reason: '$effect'); + } + } + }); +} diff --git a/test/render/paint_structure_test.dart b/test/render/paint_structure_test.dart new file mode 100644 index 0000000..051aa72 --- /dev/null +++ b/test/render/paint_structure_test.dart @@ -0,0 +1,356 @@ +import 'dart:ui' show Brightness; + +import 'package:flutter/painting.dart'; +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'render_utils.dart'; + +/// Where light lands, read back from real shader frames: the shape options +/// put it where they say and nowhere else. These compare regions of one +/// frame (or two frames) against each other rather than pinning pixel +/// values, so retuning the look leaves them standing. +void main() { + setUpAll(BorderBeam.precache); + + final box = const Offset(renderMargin, renderMargin) & cardSize; + + // Two cycles of every effect, sampled densely enough to catch a sweep in + // any part of the border. + final sweep = [for (var i = 0; i < 16; i++) 0.7 + i * 0.37]; + + group('a segment', () { + // The straight run of the top edge and the space above it — border + // light only. Inward glow from the visible lower half may legitimately + // reach up through the box, so the band stops at the stroke. + final topRun = Rect.fromLTRB( + box.left + 24, + box.top - 40, + box.right - 24, + box.top + 2, + ); + + for (final effect in BeamEffect.values) { + // A line rides its user segment rather than its edge; start it on the + // top edge so the unsegmented reference lights the band. + final subject = effect is LineEffect + ? const BeamEffect.line(edge: BeamEdge.top) + : effect; + test('${effect.name}: bottomHalf hides the top of the border', () async { + var segmented = 0; + var whole = 0; + var visible = 0; + for (final t in sweep) { + final masked = configFor( + subject, + shape: const BeamShape(segment: BeamSegment.bottomHalf), + ); + final frame = await renderFrame(masked, phasesAt(masked, t)); + segmented += frame.energyIn(topRun); + visible += frame.energyIn( + Rect.fromLTRB( + 0, + box.center.dy, + frame.width * 1.0, + frame.height * 1.0, + ), + ); + final full = configFor(subject); + whole += (await renderFrame( + full, + phasesAt(full, t), + )).energyIn(topRun); + } + expect(visible, greaterThan(0), reason: 'the lower half is lit'); + expect(whole, greaterThan(0), reason: 'the reference lights the top'); + expect( + segmented, + lessThan(whole * 0.05), + reason: 'the top run kept $segmented of $whole', + ); + }); + } + + // Ends that meet run the whole way round: there is no end to fade, so + // the join is lit like the rest of the border. (The line rides a + // segment instead of its edge, so it has no unsegmented twin here.) + for (final effect in [ + const BeamEffect.rotate(), + const BeamEffect.pulse(), + ]) { + test('${effect.name}: ends that meet leave no gap at the join', () async { + const closed = BeamShape( + segment: BeamSegment( + start: BeamAnchor.topCenter, + end: BeamAnchor.topCenter, + ), + ); + // The stroke, the bloom, and the inner glow around top-centre. + final join = Rect.fromLTRB( + box.center.dx - 48, + box.top - 8, + box.center.dx + 48, + box.top + 24, + ); + var looped = 0; + var whole = 0; + for (final t in sweep) { + final masked = configFor(effect, shape: closed); + looped += (await renderFrame( + masked, + phasesAt(masked, t), + )).energyIn(join); + final full = configFor(effect); + whole += (await renderFrame(full, phasesAt(full, t))).energyIn(join); + } + expect(whole, greaterThan(0), reason: 'the reference lights the join'); + expect( + looped, + greaterThanOrEqualTo(whole * 0.98), + reason: 'the join kept $looped of $whole', + ); + }); + } + }); + + group('line', () { + for (final edge in BeamEdge.values) { + test('rides the ${edge.name} edge', () async { + final near = switch (edge) { + BeamEdge.top => Rect.fromLTRB( + box.left, + box.top - 4, + box.right, + box.top + 6, + ), + BeamEdge.bottom => Rect.fromLTRB( + box.left, + box.bottom - 6, + box.right, + box.bottom + 4, + ), + BeamEdge.left => Rect.fromLTRB( + box.left - 4, + box.top, + box.left + 6, + box.bottom, + ), + BeamEdge.right => Rect.fromLTRB( + box.right - 6, + box.top, + box.right + 4, + box.bottom, + ), + }; + // The band along the opposite edge. + final far = switch (edge) { + BeamEdge.top => near.shift(Offset(0, box.height - 10)), + BeamEdge.bottom => near.shift(Offset(0, -(box.height - 10))), + BeamEdge.left => near.shift(Offset(box.width - 10, 0)), + BeamEdge.right => near.shift(Offset(-(box.width - 10), 0)), + }; + final config = configFor(BeamEffect.line(edge: edge)); + var onEdge = 0; + var opposite = 0; + for (final progress in [0.2, 0.5, 0.8]) { + final frame = await renderFrame( + config, + phasesAt(config, 1.3, progress: progress), + ); + onEdge += frame.energyIn(near); + opposite += frame.energyIn(far); + } + expect(onEdge, greaterThan(0)); + expect( + opposite, + lessThan(onEdge * 0.05), + reason: 'the ${edge.name} streak lit the opposite edge', + ); + }); + } + }); + + group('ringOffset', () { + // A ring this far from the box, in either direction. + const shift = 12.0; + + Future rotateWith(double offset) { + final config = configFor( + const BeamEffect.rotate(), + brightness: Brightness.light, + shape: BeamShape(ringOffset: offset), + ); + return renderFrame(config, phasesAt(config, 1.3)); + } + + // Light strictly outside the box, past anti-aliasing. + int outside(RenderedFrame f) => + f.lit(threshold: 2) - f.litIn(box.inflate(3), threshold: 2); + + test('0 keeps an inward beam within the bounds', () async { + expect(outside(await rotateWith(0)), 0); + }); + + test('a positive offset moves the ring outside the bounds', () async { + final frame = await rotateWith(shift); + expect(outside(frame), greaterThan(0)); + }); + + test('a negative offset pulls the ring inside them', () async { + final frame = await rotateWith(-shift); + expect(outside(frame), 0); + // The band between the box edge and the pulled-in ring stays dark. + final band = + frame.litIn(box, threshold: 2) - + frame.litIn(box.deflate(shift - 3), threshold: 2); + expect(band, 0); + }); + }); + + group('outward light', () { + test('a rotate comet paints past the bounds', () async { + final config = configFor(const BeamEffect.rotate(comet: true)); + final frame = await renderFrame(config, phasesAt(config, 1.3)); + expect( + frame.lit(threshold: 8) - frame.litIn(box.inflate(4), threshold: 8), + greaterThan(0), + ); + }); + + test('without a comet the light stays inside the bounds', () async { + final config = configFor(const BeamEffect.rotate()); + final frame = await renderFrame(config, phasesAt(config, 1.3)); + expect( + frame.lit(threshold: 8) - frame.litIn(box.inflate(4), threshold: 8), + 0, + ); + }); + }); + + group('dashes', () { + // The straight run of the top edge, one pixel row inside the stroke, + // under a pulse with the glows off — the hairline alone, lit along long + // stretches of the edge, so dashes have light to cut. + Future> topRow(BeamShape shape) async { + final config = configFor( + const BeamEffect.pulse(), + shape: shape, + style: const BeamStyle(glow: 0), + ); + final frame = await renderFrame(config, phasesAt(config, 1.3)); + final y = box.top.toInt(); + return [ + for (var x = box.left.toInt() + 24; x < box.right.toInt() - 24; x++) + frame.levelAt(x, y), + ]; + } + + test('dashes only take light away', () async { + final solid = await topRow(const BeamShape()); + final dashed = await topRow(const BeamShape(dashes: 12)); + for (var i = 0; i < solid.length; i++) { + expect(dashed[i], lessThanOrEqualTo(solid[i] + 1), reason: 'x+$i'); + } + }); + + test('dashes cut gaps into a lit ring', () async { + final solid = await topRow(const BeamShape()); + final dashed = await topRow(const BeamShape(dashes: 12)); + // A gap is a run the solid ring lights and the dashes leave dark. + var gaps = 0; + var inGap = false; + for (var i = 0; i < solid.length; i++) { + final cut = solid[i] > 16 && dashed[i] <= 2; + if (cut && !inGap) gaps++; + inGap = cut; + } + expect(gaps, greaterThan(1), reason: 'no gaps between dashes'); + expect( + dashed.where((level) => level > 16), + isNotEmpty, + reason: 'no dash', + ); + }); + }); + + group('direction', () { + test('reverse sweeps the mirror image of forward', () async { + // The colour field is fixed to the box, so the pixels themselves do + // not mirror; where the light sits does. Compare the centre of its + // coverage in both axes, off the quarter turns: there a sweep that + // runs the wrong way round, or trails its tail the wrong way, lands + // well away from the mirror image, while on a quarter turn the two + // can nearly coincide. The windows' exact mirror is checked in + // beam_frame_test.dart. + Future centre(BeamDirection direction, double turn) async { + final config = configFor( + const BeamEffect.rotate(), + brightness: Brightness.light, + timing: BeamTiming(direction: direction), + ); + final frame = await renderFrame( + config, + phasesAt(config, config.cycleSeconds * turn), + ); + var sumX = 0.0; + var sumY = 0.0; + var weight = 0.0; + for (var y = 0; y < frame.height; y++) { + for (var x = 0; x < frame.width; x++) { + final a = frame.rgba[(y * frame.width + x) * 4 + 3]; + sumX += a * x; + sumY += a * y; + weight += a; + } + } + expect(weight, greaterThan(0)); + return Offset(sumX / weight, sumY / weight); + } + + // The image is the box with an even margin, so its centre line is + // the box's. + final width = renderMargin * 2 + cardSize.width; + for (final turn in [0.1, 0.4, 0.6]) { + final forward = await centre(BeamDirection.forward, turn); + final reverse = await centre(BeamDirection.reverse, turn); + final mirrored = Offset(width - 1 - reverse.dx, reverse.dy); + expect( + (forward - mirrored).distance, + lessThan(cardSize.width * 0.08), + reason: '$turn of a turn: forward $forward, reverse $mirrored', + ); + } + }); + }); + + group('glow', () { + // Light deep inside the box, well past the stroke and the bloom that + // hugs it. + Future deepInside(double glow) async { + final config = configFor( + const BeamEffect.rotate(), + style: BeamStyle(glow: glow), + ); + final frame = await renderFrame(config, phasesAt(config, 1.3)); + return frame.litIn(box.deflate(24), threshold: 4); + } + + test('a bigger glow reaches further in', () async { + expect(await deepInside(2), greaterThan(await deepInside(1))); + }); + + // BeamStyle.glow documents "0 leaves only the stroke". + test('0 leaves only the stroke', () async { + final config = configFor( + const BeamEffect.rotate(), + style: const BeamStyle(glow: 0), + shape: const BeamShape(borderWidth: 1), + ); + final frame = await renderFrame(config, phasesAt(config, 1.3)); + // The stroke is 1px wide, but a 16px corner bows it up to 4.7px in from + // each edge; 6px clears it with room for anti-aliasing. + expect(frame.litIn(box.deflate(6), threshold: 2), 0); + expect(frame.lit(threshold: 2), greaterThan(0)); + }); + }); +} diff --git a/test/render/render_utils.dart b/test/render/render_utils.dart new file mode 100644 index 0000000..76a1927 --- /dev/null +++ b/test/render/render_utils.dart @@ -0,0 +1,440 @@ +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter/painting.dart'; +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/animation/beam_phases.dart'; +import 'package:flutter_border_beam/src/models/beam_config.dart'; +import 'package:flutter_border_beam/src/render/beam_frame.dart'; +import 'package:flutter_border_beam/src/render/beam_renderer.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// The box most render tests light: the card proportions the goldens use. +const Size cardSize = Size(350, 140); + +/// Room left around the box in rendered images, enough for the widest outward +/// light (a rotate comet's trail). [renderFrame] fails a frame that draws +/// past it rather than reading back a cropped one. +const double renderMargin = 80; + +/// Every effect, by name, with its default parameters. +final Map effectsByName = { + for (final effect in BeamEffect.values) effect.name: effect, +}; + +/// A palette subset that covers the stop-count extremes — the default, a +/// fixed-hue preset, one stop, and the full eight — and every way +/// `BeamLook.tablesFor` finds a palette's tables: its own (`colorful`, +/// `mono`), an extra preset's colours cycled over colorful's (`aurora`), +/// tables sampled from the stops (`solid`, `eight`), and a preset's own +/// tables scaled (`ocean ×0.5`). +final Map paletteSubset = { + 'colorful': BeamColors.colorful, + 'mono': BeamColors.mono, + 'aurora': BeamColors.aurora, + 'ocean ×0.5': BeamColors.ocean.scaleAlpha(0.5), + 'solid': const BeamColors.solid(Color(0xFFFF0080)), + 'eight': const BeamColors([ + Color(0xFFFF0000), + Color(0xFFFF8000), + Color(0xFFFFFF00), + Color(0xFF00FF00), + Color(0xFF00FFFF), + Color(0xFF0000FF), + Color(0xFF8000FF), + Color(0xFFFF00FF), + ]), +}; + +/// The shape families every renderer path must handle. +final Map shapeVariety = { + 'rrect': const BeamShape(), + 'superellipse': const BeamShape.all(24, superellipse: true), + 'stadium': const BeamShape.stadium(), + 'per-corner': const BeamShape( + radius: BorderRadius.only( + topLeft: Radius.circular(40), + bottomRight: Radius.circular(8), + ), + ), + 'segment': const BeamShape(segment: BeamSegment.bottomHalf), + 'dashes': const BeamShape(dashes: 12), + 'ringOffset +8': const BeamShape(ringOffset: 8), + 'ringOffset -6': const BeamShape(ringOffset: -6), + 'thick border': const BeamShape(borderWidth: 4), +}; + +/// Resolves a config the way a mounted beam does, from the merged value +/// objects. +BeamConfig configFor( + BeamEffect effect, { + ui.Brightness brightness = ui.Brightness.dark, + BeamColors colors = BeamColors.colorful, + BeamStyle style = const BeamStyle(), + BeamShape shape = const BeamShape(), + BeamTiming timing = const BeamTiming(), +}) => BeamConfig.resolve( + effect: effect, + palette: (style.colors ?? colors).resolve(), + brightness: brightness, + style: style, + shape: shape, + timing: timing, +); + +/// An instant at which [effect] (with default timing) is fully faded in and +/// lit: halfway through its second sweep for a travelling effect, the golden +/// 1.3s for an ambient one. Measured from the effect's own cycle and gap, so +/// a travelling effect is never caught resting between sweeps. +double litSeconds(BeamEffect effect) { + if (!effect.travels) return 1.3; + double s(Duration d) => d.inMicroseconds / Duration.microsecondsPerSecond; + final cycle = s(effect.defaultCycle); + return cycle + s(effect.defaultCycleGap) + cycle / 2; +} + +/// The phases a running beam paints at [seconds], at full fade. +BeamFramePhases phasesAt( + BeamConfig config, + double seconds, { + double? progress, + double fade = 1, +}) => BeamPhaseResolver(config).sample(seconds, fade, progress: progress); + +/// Paints one frame into a [RecordingCanvas] and returns it. +RecordingCanvas recordFrame( + BeamRenderer renderer, + BeamConfig config, + BeamFramePhases phases, { + Size size = cardSize, + double devicePixelRatio = 1, +}) { + final recorder = ui.PictureRecorder(); + final canvas = RecordingCanvas(ui.Canvas(recorder)); + renderer.paint( + canvas, + Offset(renderMargin, renderMargin) & size, + config, + phases, + devicePixelRatio: devicePixelRatio, + ); + recorder.endRecording().dispose(); + return canvas; +} + +/// One rendered frame: the box sits [renderMargin] in from the image's +/// top-left corner. +class RenderedFrame { + RenderedFrame._(this.width, this.height, this.rgba); + + /// Image width in px. + final int width; + + /// Image height in px. + final int height; + + /// Premultiplied RGBA bytes, row-major. + final Uint8List rgba; + + /// The box's bounds within the image. + Rect boxIn(Size size) => Offset(renderMargin, renderMargin) & size; + + /// The strongest channel at ([x], [y]), 0–255. Light composited with an + /// additive share can carry colour above its alpha, so this reads both. + int levelAt(int x, int y) { + final i = (y * width + x) * 4; + var level = rgba[i + 3]; + for (var c = 0; c < 3; c++) { + if (rgba[i + c] > level) level = rgba[i + c]; + } + return level; + } + + /// How many pixels inside [region] (clamped to the image) are brighter + /// than [threshold]. + int litIn(Rect region, {int threshold = 0}) { + final r = region.intersect(Offset.zero & Size(width * 1.0, height * 1.0)); + if (r.isEmpty) return 0; + var count = 0; + for (var y = r.top.floor(); y < r.bottom.ceil(); y++) { + for (var x = r.left.floor(); x < r.right.ceil(); x++) { + if (levelAt(x, y) > threshold) count++; + } + } + return count; + } + + /// The summed level of every pixel inside [region]. + int energyIn(Rect region) { + final r = region.intersect(Offset.zero & Size(width * 1.0, height * 1.0)); + if (r.isEmpty) return 0; + var sum = 0; + for (var y = r.top.floor(); y < r.bottom.ceil(); y++) { + for (var x = r.left.floor(); x < r.right.ceil(); x++) { + sum += levelAt(x, y); + } + } + return sum; + } + + /// Pixels brighter than [threshold] anywhere in the image. + int lit({int threshold = 0}) => litIn( + Offset.zero & Size(width * 1.0, height * 1.0), + threshold: threshold, + ); +} + +/// Renders one frame of [config] at [phases] through a fresh renderer and +/// reads it back. The shader must be loaded (`BorderBeam.precache`). +Future renderFrame( + BeamConfig config, + BeamFramePhases phases, { + Size size = cardSize, + BeamRenderer? renderer, +}) async { + final r = renderer ?? BeamRenderer(); + final recorder = ui.PictureRecorder(); + final canvas = RecordingCanvas(ui.Canvas(recorder)); + r.paint( + canvas, + Offset(renderMargin, renderMargin) & size, + config, + phases, + devicePixelRatio: 1, + ); + final picture = recorder.endRecording(); + final width = (size.width + 2 * renderMargin).ceil(); + final height = (size.height + 2 * renderMargin).ceil(); + // The draw covers everywhere light can land, so it must fit the image: + // light past the margin would be cut off and every region read short. + for (final bounds in canvas.drawBounds) { + expect( + bounds.left >= 0 && + bounds.top >= 0 && + bounds.right <= width && + bounds.bottom <= height, + isTrue, + reason: 'the draw $bounds outgrows the ${renderMargin}px margin', + ); + } + final image = await picture.toImage(width, height); + picture.dispose(); + final bytes = await image.toByteData(); + image.dispose(); + if (renderer == null) r.dispose(); + return RenderedFrame._(width, height, bytes!.buffer.asUint8List()); +} + +/// A [ui.Canvas] that records every call the renderer makes while forwarding +/// it to a real canvas, so the frame is still painted exactly as on screen. +/// +/// The calls a beam frame may make are forwarded explicitly; anything else +/// lands in [unforwarded] through `noSuchMethod`, so a new kind of call fails +/// the budget test loudly instead of slipping through uncounted. +class RecordingCanvas implements ui.Canvas { + /// Wraps `inner`. + RecordingCanvas(this._inner); + + final ui.Canvas _inner; + + /// Draw calls, by name, in order. + final List draws = []; + + /// The paint of every draw call, in order. + final List paints = []; + + /// The outer bounds of every draw call, in order. + final List drawBounds = []; + + /// Plain `save` calls. + int saves = 0; + + /// `saveLayer` calls — offscreen render targets. + int saveLayers = 0; + + /// `restore` calls. + int restores = 0; + + /// `clip*` calls. + int clips = 0; + + /// Calls not forwarded explicitly. + final Set unforwarded = {}; + + @override + Float64List getTransform() => _inner.getTransform(); + + @override + void save() { + saves++; + _inner.save(); + } + + @override + void saveLayer(Rect? bounds, ui.Paint paint) { + saveLayers++; + _inner.saveLayer(bounds, paint); + } + + @override + void restore() { + restores++; + _inner.restore(); + } + + @override + void clipRect( + Rect rect, { + ui.ClipOp clipOp = ui.ClipOp.intersect, + bool doAntiAlias = true, + }) { + clips++; + _inner.clipRect(rect, clipOp: clipOp, doAntiAlias: doAntiAlias); + } + + @override + void clipRRect(RRect rrect, {bool doAntiAlias = true}) { + clips++; + _inner.clipRRect(rrect, doAntiAlias: doAntiAlias); + } + + @override + void clipPath(ui.Path path, {bool doAntiAlias = true}) { + clips++; + _inner.clipPath(path, doAntiAlias: doAntiAlias); + } + + @override + void drawRect(Rect rect, ui.Paint paint) { + _record('drawRect', rect, paint); + _inner.drawRect(rect, paint); + } + + @override + void drawDRRect(RRect outer, RRect inner, ui.Paint paint) { + _record('drawDRRect', outer.outerRect, paint); + _inner.drawDRRect(outer, inner, paint); + } + + @override + void drawRRect(RRect rrect, ui.Paint paint) { + _record('drawRRect', rrect.outerRect, paint); + _inner.drawRRect(rrect, paint); + } + + @override + void drawPath(ui.Path path, ui.Paint paint) { + _record('drawPath', path.getBounds(), paint); + _inner.drawPath(path, paint); + } + + @override + void drawPaint(ui.Paint paint) { + _record('drawPaint', Rect.largest, paint); + _inner.drawPaint(paint); + } + + @override + void translate(double dx, double dy) => _inner.translate(dx, dy); + + @override + void scale(double sx, [double? sy]) => _inner.scale(sx, sy); + + void _record(String name, Rect bounds, ui.Paint paint) { + draws.add(name); + drawBounds.add(bounds); + paints.add(paint); + } + + @override + dynamic noSuchMethod(Invocation invocation) { + unforwarded.add(_symbolName(invocation.memberName)); + return null; + } +} + +String _symbolName(Symbol symbol) { + final text = symbol.toString(); + final start = text.indexOf('"'); + final end = text.lastIndexOf('"'); + return start >= 0 && end > start ? text.substring(start + 1, end) : text; +} + +/// Checks the invariants every written frame must hold, whatever the +/// effect: every uniform finite, blob counts within their slots, opacities +/// and table alphas in range, table stops ascending and in 0–1 for every +/// table in use (and every table a lit layer reads), blob radii positive, +/// and — when [drawBounds] is given — the outline inside the draw. +void expectSaneFrame(BeamFrameData d, String label, {Rect? drawBounds}) { + for (var i = 0; i < beamUniformFloats; i++) { + expect(d.data[i].isFinite, isTrue, reason: '$label: uniform $i'); + } + const slots = [blobSlotsA, blobSlotsB, blobSlotsC]; + var lit = 0; + for (var k = 0; k < beamLayerCount; k++) { + expect(d.blobCount(k), inInclusiveRange(0, slots[k]), reason: label); + expect(d.opacityOf(k), inInclusiveRange(0, 1), reason: '$label: $k'); + expect(d.sigmaOf(k), greaterThanOrEqualTo(0), reason: '$label: $k'); + expect(d.edgeFadeOf(k), greaterThanOrEqualTo(0), reason: '$label: $k'); + if (d.geometryOf(k) != BeamGeometry.none && d.opacityOf(k) > 0) lit++; + if (d.geometryOf(k) == BeamGeometry.blurredRing) { + expect(d.sigmaOf(k), greaterThan(0), reason: '$label: $k sigma'); + } + } + expect(lit, greaterThan(0), reason: '$label: some layer is lit'); + // The tables a lit layer reads through, as its window or its overlay. + final read = { + for (var k = 0; k < beamLayerCount; k++) + if (d.geometryOf(k) != BeamGeometry.none && d.opacityOf(k) > 0) ...[ + if (d.windowOf(k) == BeamWindow.conicA) BeamTable.windowA, + if (d.windowOf(k) == BeamWindow.conicB) BeamTable.windowB, + ?d.overlayOf(k), + ], + }; + for (final t in BeamTable.values) { + for (var i = 0; i <= 64; i++) { + final a = d.tableAt(t, i / 64); + expect(a, inInclusiveRange(0, 1), reason: '$label: $t at ${i / 64}'); + } + // A table in use holds conic coordinates, its padding included; an + // unused one is all the 2 it is cleared to. A first stop past 1 reads + // as unused, so a table a layer reads must be in use. + final used = d.tableStop(t, 0) <= 1; + if (read.contains(t)) { + expect(used, isTrue, reason: '$label: $t is read but unused'); + } + var previous = -1.0; + for (var i = 0; i < tableStops; i++) { + final stop = d.tableStop(t, i); + expect( + stop, + used ? inInclusiveRange(0, 1) : 2, + reason: '$label: $t stop $i', + ); + expect(stop, greaterThanOrEqualTo(previous), reason: '$label: $t'); + previous = stop; + } + } + for (var k = 0; k < beamLayerCount; k++) { + for (var i = 0; i < d.blobCount(k); i++) { + final b = d.blob(k, i); + expect(b.rx, greaterThan(0), reason: '$label: layer $k blob $i'); + expect(b.ry, greaterThan(0), reason: '$label: layer $k blob $i'); + expect(b.alpha, inInclusiveRange(0, 1), reason: '$label: blob alpha'); + for (final c in [b.r, b.g, b.b]) { + expect(c, inInclusiveRange(0, 1), reason: '$label: blob colour'); + } + } + } + expect(d.trackSpan, inInclusiveRange(0, 1), reason: '$label: span'); + expect(d.trackFeather, greaterThanOrEqualTo(0), reason: '$label: feather'); + if (drawBounds != null) { + final box = d.outlineRect; + expect( + drawBounds.inflate(0.5).contains(box.topLeft) && + drawBounds.inflate(0.5).contains(box.bottomRight), + isTrue, + reason: '$label: $drawBounds must contain the outline $box', + ); + } +} diff --git a/test/render/uniform_layout_test.dart b/test/render/uniform_layout_test.dart new file mode 100644 index 0000000..aead69a --- /dev/null +++ b/test/render/uniform_layout_test.dart @@ -0,0 +1,265 @@ +import 'dart:io'; + +import 'package:flutter/painting.dart'; +import 'package:flutter_border_beam/src/render/beam_frame.dart'; +import 'package:flutter_border_beam/src/render/beam_outline.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// The Dart packer writes uniforms by float index, so the shader's declared +/// layout and `beamUniformFloats` must agree float for float — a uniform +/// added on one side only shifts every value after it, and the frame is +/// garbage rather than an error. +void main() { + final source = File('shaders/beam.frag').readAsStringSync(); + final declaration = RegExp( + r'^\s*uniform\s+(\w+)\s+(\w+)\s*(?:\[\s*(\d+)\s*\])?\s*;', + multiLine: true, + ); + final uniforms = [ + for (final m in declaration.allMatches(source)) + (type: m[1]!, name: m[2]!, count: int.parse(m[3] ?? '1')), + ]; + + const floatsPerType = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + }; + + test('the shader declares its uniforms', () { + expect(uniforms, isNotEmpty); + expect( + uniforms.map((u) => u.name).toSet(), + hasLength(uniforms.length), + reason: 'uniform names must be unique', + ); + }); + + test('every uniform is a float type the packer can write', () { + // A sampler would need `setImageSampler`, which the renderer never calls. + for (final u in uniforms) { + expect( + floatsPerType, + contains(u.type), + reason: '${u.name} has type ${u.type}', + ); + } + }); + + test('every uniform is a vec4 or a vec4 array', () { + // The shader header promises this: a vec4-only layout packs identically + // on every backend, with no std140 padding surprises. + for (final u in uniforms) { + expect(u.type, 'vec4', reason: u.name); + } + }); + + test('the declared float count equals beamUniformFloats', () { + final floats = uniforms.fold( + 0, + (sum, u) => sum + floatsPerType[u.type]! * u.count, + ); + expect(floats, beamUniformFloats); + }); + + test('the arrays hold what the frame data packs into them', () { + // Layers, tables, and blob stacks are sized on the Dart side by these + // constants; an array of another length would desynchronise the packer. + final arrays = { + for (final u in uniforms.where((u) => u.count > 1)) u.name: u.count, + }; + expect(arrays, { + 'uLayer': beamLayerCount * 9, + 'uWinA': tableStops ~/ 2, + 'uWinB': tableStops ~/ 2, + 'uOverA': tableStops ~/ 2, + 'uOverB': tableStops ~/ 2, + 'uBlobA': blobSlotsA * 3, + 'uBlobB': blobSlotsB * 3, + 'uBlobC': blobSlotsC * 3, + }); + }); + + test('each writer lands in the uniform the shader declares for it', () { + // Where the shader reads each uniform, in floats: its declaration order + // and sizes. The packer writes by fixed offsets, so a declaration moved + // on either side alone puts values in the wrong uniform. + final offsets = {}; + var at = 0; + for (final u in uniforms) { + offsets[u.name] = at; + at += floatsPerType[u.type]! * u.count; + } + String owner(int float) => + offsets.entries.lastWhere((e) => e.value <= float).key; + final layerFloats = + 4 * + uniforms.singleWhere((u) => u.name == 'uLayer').count ~/ + beamLayerCount; + + BeamFrameData frame() => BeamFrameData()..reset(); + final blank = frame().data; + final checked = {}; + + // [write] on a reset frame puts [expected] [from] floats into [name], + // and touches no uniform outside [touches]. + void expectWrite( + String name, + void Function(BeamFrameData d) write, + List expected, { + int from = 0, + Set? touches, + }) { + final d = frame(); + write(d); + final start = offsets[name]! + from; + for (var i = 0; i < expected.length; i++) { + expect( + d.data[start + i], + closeTo(expected[i], 1e-3), + reason: '$name float ${from + i}', + ); + } + expect( + { + for (var i = 0; i < beamUniformFloats; i++) + if (d.data[i] != blank[i]) owner(i), + }, + touches ?? {name}, + reason: 'what writing $name touched', + ); + checked.add(name); + } + + // Distinct values throughout, so a value read from a neighbour fails. + final outline = BeamOutline( + const Rect.fromLTWH(3, 5, 200, 100), + const BorderRadius.only( + topLeft: Radius.circular(7), + topRight: Radius.circular(9), + bottomRight: Radius.circular(11), + bottomLeft: Radius.circular(13), + ), + superellipse: true, + ); + void setOutline(BeamFrameData d) => d.setOutline(outline, 3, 0.5); + const header = {'uRect', 'uRadii', 'uShape', 'uPerim', 'uQuads'}; + expectWrite('uRect', setOutline, [3, 5, 200, 100], touches: header); + expectWrite('uRadii', setOutline, [7, 9, 11, 13], touches: header); + expectWrite('uShape', setOutline, [1, 0, 3, 0.5], touches: header); + expectWrite('uPerim', setOutline, [outline.length], touches: header); + expectWrite('uQuads', setOutline, outline.quadStarts, touches: header); + expectWrite('uMask', (d) => d.setTrack(0.25, 0.5, 0.125, 7), [ + 0.25, + 0.5, + 0.125, + 7, + ]); + expectWrite('uConic', (d) => d.setConic(const Offset(11, 13), 0.375, 3), [ + 11, + 13, + 0.375, + 3, + ]); + for (var k = 0; k < beamLayerCount; k++) { + expectWrite( + 'uLayer', + (d) => d.setLayer( + k, + BeamGeometry.glow, + opacity: 0.5, + sigma: 4.0 + k, + inflate: 6, + ), + [BeamGeometry.glow.index.toDouble(), 4.0 + k, 6, 0.5], + from: k * layerFloats, + ); + } + for (final (table, name) in [ + (BeamTable.windowA, 'uWinA'), + (BeamTable.windowB, 'uWinB'), + (BeamTable.overlayA, 'uOverA'), + (BeamTable.overlayB, 'uOverB'), + ]) { + expectWrite( + name, + (d) => d.setTable(table, const [0.1, 0.6], const [0.3, 0.9], 2), + [0.1, 0.3, 0.6, 0.9], + ); + } + for (final (k, name) in [(0, 'uBlobA'), (1, 'uBlobB'), (2, 'uBlobC')]) { + expectWrite( + name, + (d) => d.addBlob( + k, + cx: 17, + cy: 19, + rx: 5, + ry: 7, + rgb: const Color(0xFF336699), + a0: 0.8, + p1: 0.25, + a1: 0.5, + p2: 0.75, + a2: 0.25, + ), + [17, 19, 5, 7, 0.2, 0.4, 0.6, 0.8, 0.25, 0.5, 0.75, 0.25], + // The blob count goes in the blob's layer header. + touches: {name, 'uLayer'}, + ); + } + + expect(checked, { + for (final u in uniforms) u.name, + }, reason: 'a new uniform needs its writer checked here'); + }); + + test('the uniforms stay inside the GLES budget', () { + // OpenGL ES 3.0 guarantees a fragment shader 224 vec4s of uniforms + // (MAX_FRAGMENT_UNIFORM_VECTORS), all a GLES device is bound to offer. + expect(beamUniformFloats, lessThanOrEqualTo(224 * 4)); + }); + + test("the shader's loop bounds match the slot counts", () { + // A macro's parameters, and the bounds of the loops in its body (its + // continuation lines). + ({List params, List bounds}) macro(String name) { + final m = RegExp( + r'#define\s+' + name + r'\(([^)]*)\)((?:[^\n]*\\\n)*[^\n]*)', + ).firstMatch(source); + expect(m, isNotNull, reason: 'no $name macro'); + return ( + params: [for (final p in m![1]!.split(',')) p.trim()], + bounds: [ + for (final loop in RegExp( + r'for\s*\(\s*int\s+i\s*=\s*0\s*;\s*i\s*<\s*(\w+)\s*;', + ).allMatches(m[2]!)) + loop[1]!, + ], + ); + } + + // A blob stack visits every slot it is handed... + final blobStack = macro('BLOB_STACK'); + expect(blobStack.params[1], 'SLOTS'); + expect(blobStack.bounds, ['SLOTS']); + // ...and each layer hands it its slot count. + expect(source, contains('BLOB_STACK(uBlobA, $blobSlotsA,')); + expect(source, contains('BLOB_STACK(uBlobB, $blobSlotsB,')); + expect(source, contains('BLOB_STACK(uBlobC, $blobSlotsC,')); + + // A table lookup visits every stop, two to a vec4, and reads the last + // one past the end. + final lookup = macro('TABLE_LOOKUP'); + expect(lookup.bounds, ['${tableStops ~/ 2}']); + expect( + source, + contains('TABLE[${tableStops ~/ 2 - 1}].w'), + reason: 'the padding stop', + ); + }); +} diff --git a/test/widget/beam_follow_test.dart b/test/widget/beam_follow_test.dart new file mode 100644 index 0000000..2adbb63 --- /dev/null +++ b/test/widget/beam_follow_test.dart @@ -0,0 +1,412 @@ +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/render/beam_painter.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +// A 350x140 box with equal corners: the right-edge centre is a quarter of +// the way round from top-centre, the left-edge centre three quarters. +Widget _host(Widget child) => MaterialApp( + theme: ThemeData(brightness: Brightness.dark), + home: Scaffold( + body: Center(child: SizedBox(width: 350, height: 140, child: child)), + ), +); + +BeamPainter _painter(WidgetTester tester) => tester + .widgetList( + find.descendant( + of: find.byType(BorderBeam), + matching: find.byType(CustomPaint), + ), + ) + .expand((paint) => [paint.painter, paint.foregroundPainter]) + .whereType() + .first; + +// The sweep the painter would draw right now: the driven value while one is +// set, else the clock's. +double _sweep(WidgetTester tester) { + final painter = _painter(tester); + return painter.resolver + .sample( + painter.clock.elapsedSeconds, + 1, + progress: painter.progress?.value, + ) + .travelProgress; +} + +// The clock's own sweep, ignoring any driven value. +double _timed(WidgetTester tester) { + final painter = _painter(tester); + return painter.resolver + .sample(painter.clock.elapsedSeconds, 1) + .travelProgress; +} + +double? _driven(WidgetTester tester) => _painter(tester).progress?.value; + +// The signed distance from [from] to [to] round the border, in (-0.5, 0.5]. +double _wrapDelta(double from, double to) => ((to - from) + 0.5) % 1.0 - 0.5; + +const _frame = Duration(milliseconds: 16); + +Future> _frames(WidgetTester tester, int count) async { + final seen = []; + for (var i = 0; i < count; i++) { + await tester.pump(_frame); + seen.add(_sweep(tester)); + } + return seen; +} + +/// `BorderBeam.follow`: the sweep of a travelling effect eases toward the +/// border point nearest a normalized pointer, critically damped, and is +/// handed back to the clock without a snap when the pointer leaves. +void main() { + Widget beam({ + BeamEffect? effect, + Offset? follow, + double? progress, + BeamTiming? timing, + BeamShape? shape, + bool? active, + }) => _host( + BorderBeam( + effect: effect, + follow: follow, + progress: progress, + timing: timing, + shape: shape, + active: active, + child: const SizedBox.expand(), + ), + ); + + // Starts the beam and lets it run [lead] before the pointer arrives. + Future start( + WidgetTester tester, { + BeamEffect? effect, + BeamTiming? timing, + BeamShape? shape, + Duration lead = const Duration(milliseconds: 100), + }) async { + await tester.pumpWidget(beam(effect: effect, timing: timing, shape: shape)); + await tester.pump(); + await tester.pump(lead); + } + + group('rotate', () { + testWidgets('eases to the border point nearest the pointer', ( + tester, + ) async { + await start(tester); + final origin = _timed(tester); + await tester.pumpWidget(beam(follow: const Offset(1, 0.5))); + + final early = await _frames(tester, 2); + expect(early.last, greaterThan(origin)); + expect( + early.last, + lessThan(0.24), + reason: 'the beam eases rather than snapping', + ); + + await _frames(tester, 29); + expect(_driven(tester), closeTo(0.25, 0.005), reason: 'within ~0.5s'); + expect(_sweep(tester), closeTo(0.25, 0.005)); + }); + + testWidgets('approaches without overshooting the target', (tester) async { + await start(tester); + await tester.pumpWidget(beam(follow: const Offset(1, 0.5))); + var previous = _timed(tester); + for (final now in await _frames(tester, 60)) { + expect(now, lessThanOrEqualTo(0.25 + 1e-9), reason: 'no overshoot'); + expect(now, greaterThanOrEqualTo(previous - 1e-9), reason: 'no ring'); + previous = now; + } + expect(previous, closeTo(0.25, 1e-3)); + }); + + testWidgets('takes the shortest way round', (tester) async { + // Just past top-centre, the left-edge centre (0.75) is a short hop + // backwards through 0, not three quarters of a lap forwards. + await start(tester); + await tester.pumpWidget(beam(follow: const Offset(0, 0.5))); + // The first eased frame starts from wherever the clock had the beam. + var previous = (await _frames(tester, 1)).single; + for (final now in await _frames(tester, 40)) { + expect( + _wrapDelta(previous, now), + lessThanOrEqualTo(1e-9), + reason: 'every step runs backwards toward the target', + ); + previous = now; + } + expect(previous, closeTo(0.75, 0.005)); + }); + + testWidgets('a moved pointer is followed from where the beam is', ( + tester, + ) async { + await start(tester); + await tester.pumpWidget(beam(follow: const Offset(1, 0.5))); + await _frames(tester, 40); + await tester.pumpWidget(beam(follow: const Offset(0.5, 1))); + final first = (await _frames(tester, 1)).single; + expect( + first, + closeTo(0.25, 0.02), + reason: 'no jump when the target moves', + ); + await _frames(tester, 40); + expect(_driven(tester), closeTo(0.5, 0.005), reason: 'bottom centre'); + }); + }); + + group('open sweeps: segments and the line', () { + testWidgets('rotate on a segment follows the fraction along it', ( + tester, + ) async { + // The right half runs top-centre → bottom-centre, so the right-edge + // centre sits halfway along it. + const shape = BeamShape(segment: BeamSegment.rightHalf); + await start(tester, shape: shape); + await tester.pumpWidget(beam(shape: shape, follow: const Offset(1, 0.5))); + await _frames(tester, 40); + expect(_driven(tester), closeTo(0.5, 0.005)); + }); + + testWidgets('line follows the coordinate along its edge', (tester) async { + for (final (edge, follow, target) in [ + (BeamEdge.bottom, const Offset(0.8, 0.2), 0.8), + (BeamEdge.top, const Offset(0.3, 0.9), 0.3), + (BeamEdge.left, const Offset(0.9, 0.7), 0.7), + ]) { + final effect = BeamEffect.line(edge: edge); + await start(tester, effect: effect); + await tester.pumpWidget(beam(effect: effect, follow: follow)); + await _frames(tester, 40); + expect(_driven(tester), closeTo(target, 0.005), reason: '$edge'); + // Unmount so the next edge starts on a fresh timeline. + await tester.pumpWidget(_host(const SizedBox())); + } + }); + + for (final (label, effect, shape, follow) in const [ + ('line', BeamEffect.line(), null, Offset(0.95, 0.5)), + ( + 'rotate on a segment', + BeamEffect.rotate(), + BeamShape(segment: BeamSegment.rightHalf), + // On the bottom edge just short of its centre: near the segment's + // far end. + Offset(0.6, 1), + ), + ]) { + testWidgets('$label eases along its travel without wrapping round', ( + tester, + ) async { + // Near the start of the sweep, a pointer at the far end is "closer" + // backwards through 0 on a loop, but these sweeps are not loops. + await start(tester, effect: effect, shape: shape); + await tester.pumpWidget( + beam(effect: effect, shape: shape, follow: follow), + ); + var previous = _timed(tester); + for (final now in await _frames(tester, 40)) { + expect( + (now - previous).abs(), + lessThan(0.2), + reason: 'the sweep jumped from $previous to $now', + ); + previous = now; + } + }); + } + }); + + // Every ambient effect, derived so a new one is covered too. + for (final effect in BeamEffect.values.where((e) => !e.travels)) { + testWidgets('${effect.name} has no travel for it to steer', (tester) async { + await start(tester, effect: effect); + await tester.pumpWidget( + beam(effect: effect, follow: const Offset(1, 0.5)), + ); + await _frames(tester, 20); + expect(_driven(tester), isNull); + expect(_sweep(tester), 0); + }); + } + + testWidgets('an explicit progress wins over it', (tester) async { + await start(tester); + await tester.pumpWidget(beam(progress: 0.5, follow: const Offset(1, 0.5))); + for (final now in await _frames(tester, 30)) { + expect(now, 0.5); + } + + // Dropping the progress hands the sweep back to the pointer. + await tester.pumpWidget(beam(follow: const Offset(1, 0.5))); + await _frames(tester, 2); + expect(_driven(tester), closeTo(0.25, 0.005)); + }); + + group('release', () { + // Follows [follow] until settled, lets go, and returns the sweep the + // pointer left the beam at. + Future followThenRelease( + WidgetTester tester, { + BeamTiming? timing, + BeamEffect? effect, + Offset follow = const Offset(1, 0.5), + int frames = 40, + }) async { + await tester.pumpWidget( + beam(effect: effect, timing: timing, follow: follow), + ); + await _frames(tester, frames); + final held = _sweep(tester); + expect(_driven(tester), held); + await tester.pumpWidget(beam(effect: effect, timing: timing)); + expect(_driven(tester), isNull); + return held; + } + + testWidgets('hands the sweep back to the clock without a snap', ( + tester, + ) async { + await start(tester); + final held = await followThenRelease(tester); + expect(_sweep(tester), closeTo(held, 1e-6)); + expect(_painter(tester).resolver.travelTimeOffset, isNot(0)); + + // And it travels on from there at the clock's pace (2.4s cycle). + await tester.pump(const Duration(milliseconds: 120)); + expect(_sweep(tester), closeTo(held + 0.05, 1e-6)); + + await tester.pumpWidget(_host(const SizedBox())); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('a reversed beam carries on backwards from there', ( + tester, + ) async { + const timing = BeamTiming(direction: BeamDirection.reverse); + await start(tester, timing: timing); + final held = await followThenRelease(tester, timing: timing); + expect(_sweep(tester), closeTo(held, 1e-6)); + await tester.pump(const Duration(milliseconds: 120)); + expect(_sweep(tester), closeTo(held - 0.05, 1e-6)); + }); + + testWidgets('a bouncing beam lets go inside a mirrored cycle', ( + tester, + ) async { + const timing = BeamTiming( + cycle: Duration(seconds: 1), + direction: BeamDirection.bounce, + ); + await start( + tester, + timing: timing, + lead: const Duration(milliseconds: 1100), + ); + final held = await followThenRelease(tester, timing: timing, frames: 25); + expect(_sweep(tester), closeTo(held, 1e-6)); + await tester.pump(const Duration(milliseconds: 50)); + expect(_sweep(tester), closeTo(held - 0.05, 1e-6), reason: 'mirrored'); + }); + + testWidgets( + 'a hand-back that crosses a cycle end keeps the mirrored direction', + (tester) async { + const timing = BeamTiming( + cycle: Duration(seconds: 1), + direction: BeamDirection.bounce, + ); + // 0.9s into the mirrored second cycle the sweep sits at 0.1, so the + // left edge (0.75) is 0.35 further along the mirrored run — past the + // end of this cycle. + await start( + tester, + timing: timing, + lead: const Duration(milliseconds: 1500), + ); + final held = await followThenRelease( + tester, + timing: timing, + follow: const Offset(0, 0.5), + frames: 25, + ); + expect(_sweep(tester), closeTo(held, 1e-6)); + }, + ); + + testWidgets( + 'letting go during the rest between sweeps resumes where it was left', + (tester) async { + const timing = BeamTiming( + cycle: Duration(seconds: 1), + cycleGap: Duration(seconds: 2), + ); + // Released 1.5s in: the clock's own sweep is resting in the gap. + await start( + tester, + timing: timing, + lead: const Duration(milliseconds: 900), + ); + final held = await followThenRelease(tester, timing: timing); + expect(_sweep(tester), closeTo(held, 1e-6)); + final painter = _painter(tester); + expect( + painter.resolver.sample(painter.clock.elapsedSeconds, 1).fadeOpacity, + 1, + reason: 'the beam does not vanish into the rest it was pulled from', + ); + }, + ); + + testWidgets('the hand-back survives a cycle change', (tester) async { + const short = BeamTiming(cycle: Duration(seconds: 4)); + await start(tester, timing: short, lead: Duration.zero); + + // A pointer parked most of a cycle behind the clock leaves a large + // negative travel offset, which puts the shifted timeline behind zero. + await followThenRelease( + tester, + timing: short, + follow: const Offset(0, 0.5), + ); + final before = _painter(tester); + final offset = before.resolver.travelTimeOffset; + expect(offset, lessThan(-before.clock.elapsedSeconds)); + final sweep = _sweep(tester); + + await tester.pumpWidget( + beam(timing: const BeamTiming(cycle: Duration(seconds: 16))), + ); + final after = _painter(tester); + expect( + after.resolver.travelTimeOffset, + closeTo(offset, 1e-9), + reason: 'a rebuilt resolver keeps the hand-back', + ); + expect(_sweep(tester), closeTo(sweep, 1e-6)); + }); + + testWidgets('a restart drops the hand-back', (tester) async { + await start(tester); + await followThenRelease(tester); + expect(_painter(tester).resolver.travelTimeOffset, isNot(0)); + + await tester.pumpWidget(beam(active: false)); + await tester.pump(const Duration(milliseconds: 600)); + await tester.pumpWidget(beam(active: true)); + final painter = _painter(tester); + expect(painter.clock.elapsedSeconds, 0); + expect(painter.resolver.travelTimeOffset, 0); + }); + }); +} diff --git a/test/widget/beam_motion_test.dart b/test/widget/beam_motion_test.dart index d30ee27..e3e1e74 100644 --- a/test/widget/beam_motion_test.dart +++ b/test/widget/beam_motion_test.dart @@ -1,8 +1,12 @@ -import 'package:flutter/material.dart'; +import 'dart:ui' as ui; + +import 'package:flutter/rendering.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_border_beam/src/animation/beam_clock.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; +import 'package:flutter_border_beam/src/animation/beam_phases.dart'; +import 'package:flutter_border_beam/src/render/beam_painter.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; Widget _host(Widget child, {bool disableAnimations = false}) => MaterialApp( theme: ThemeData(brightness: Brightness.dark), @@ -29,340 +33,176 @@ BeamPainter _painter(WidgetTester tester) => _painters(tester).first; BeamClock _clock(WidgetTester tester) => _painter(tester).clock; -/// Playback beyond plain on/off: what reduced motion does to the four -/// behaviors, when a repeat budget ends a run, and the one-shot brightness -/// envelopes. -void main() { - group('reducedMotion', () { - testWidgets('animate ignores the platform request', (tester) async { - await tester.pumpWidget( - _host( - disableAnimations: true, - const BorderBeam.rotate( - playback: BeamPlayback(reducedMotion: BeamReducedMotion.animate), - child: SizedBox.expand(), - ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); - final clock = _clock(tester); - expect(clock.isRunning, isTrue); - expect(clock.elapsedSeconds, closeTo(0.5, 1e-9)); - expect(_painter(tester).staticMode, isFalse); - expect(tester.binding.hasScheduledFrame, isTrue); - }); - - testWidgets('staticFrame freezes on one frame', (tester) async { - await tester.pumpWidget( - _host( - disableAnimations: true, - const BorderBeam.rotate( - playback: BeamPlayback( - reducedMotion: BeamReducedMotion.staticFrame, - ), - child: SizedBox.expand(), - ), - ), - ); - await tester.pump(const Duration(seconds: 1)); - expect(tester.binding.hasScheduledFrame, isFalse); - final painter = _painter(tester); - expect(painter.staticMode, isTrue); - expect(painter.clock.isRunning, isFalse); - }); - - testWidgets('staticFrame is the default', (tester) async { - await tester.pumpWidget( - _host( - disableAnimations: true, - const BorderBeam.rotate(child: SizedBox.expand()), - ), - ); - await tester.pump(const Duration(seconds: 1)); - expect(_painter(tester).staticMode, isTrue); - }); - - testWidgets('hide paints nothing and never ticks', (tester) async { - await tester.pumpWidget( - _host( - disableAnimations: true, - const BorderBeam.rotate( - playback: BeamPlayback(reducedMotion: BeamReducedMotion.hide), - child: SizedBox.expand(), - ), - ), - ); - await tester.pump(const Duration(seconds: 1)); - expect(_painters(tester), isEmpty, reason: 'no painter is mounted'); - expect(tester.binding.transientCallbackCount, 0); - expect(tester.binding.hasScheduledFrame, isFalse); - }); - - testWidgets('hide paints the beam again once the request lifts', ( - tester, - ) async { - Widget build(bool reduced) => _host( - disableAnimations: reduced, - const BorderBeam.rotate( - playback: BeamPlayback(reducedMotion: BeamReducedMotion.hide), - child: SizedBox.expand(), - ), - ); - - await tester.pumpWidget(build(true)); - await tester.pump(const Duration(seconds: 1)); - expect(_painters(tester), isEmpty); - - await tester.pumpWidget(build(false)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - expect(_painters(tester), isNotEmpty); - expect(_clock(tester).isRunning, isTrue); - }); - - testWidgets('slow runs the clock at a quarter rate', (tester) async { - await tester.pumpWidget( - _host( - disableAnimations: true, - const BorderBeam.rotate( - playback: BeamPlayback(reducedMotion: BeamReducedMotion.slow), - child: SizedBox.expand(), - ), - ), - ); - final clock = _clock(tester); - expect(clock.speed, 0.25); - expect(_painter(tester).staticMode, isFalse); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - expect(clock.elapsedSeconds, closeTo(0.25, 1e-9)); - }); - - testWidgets('slow scales the configured speed rather than replacing it', ( - tester, - ) async { - await tester.pumpWidget( - _host( - disableAnimations: true, - const BorderBeam.rotate( - timing: BeamTiming(speed: 2), - playback: BeamPlayback(reducedMotion: BeamReducedMotion.slow), - child: SizedBox.expand(), - ), - ), - ); - expect(_clock(tester).speed, 0.5); - }); - - testWidgets('slow restores the rate when the request lifts', ( - tester, - ) async { - Widget build(bool reduced) => _host( - disableAnimations: reduced, - const BorderBeam.rotate( - timing: BeamTiming(speed: 2), - playback: BeamPlayback(reducedMotion: BeamReducedMotion.slow), - child: SizedBox.expand(), - ), - ); - - await tester.pumpWidget(build(true)); - final clock = _clock(tester); - expect(clock.speed, 0.5); - - await tester.pumpWidget(build(false)); - expect(clock.speed, 2); +// The phases the mounted beam's resolver gives at [t] with a full fade. +BeamFramePhases _at(WidgetTester tester, double t) => + _painter(tester).resolver.sample(t, 1); + +// The phases the painter would draw right now. +BeamFramePhases _now(WidgetTester tester) { + final painter = _painter(tester); + return painter.resolver.sample( + painter.clock.elapsedSeconds, + 1, + progress: painter.progress?.value, + ); +} - await tester.pumpWidget(build(true)); - expect(clock.speed, 0.5); - }); +// The signed distance from [from] to [to] round the border, in (-0.5, 0.5]. +double _wrapDelta(double from, double to) => ((to - from) + 0.5) % 1.0 - 0.5; + +/// Sums the alpha channel of the beam's own repaint boundary. Rasterizing is +/// real async work, so it runs outside the fake clock. +Future _alphaSum(WidgetTester tester) async { + final boundary = tester.renderObject( + find + .descendant( + of: find.byType(BorderBeam), + matching: find.byType(RepaintBoundary), + ) + .first, + ); + final sum = await tester.runAsync(() async { + final image = await boundary.toImage(); + final bytes = await image.toByteData(format: ui.ImageByteFormat.rawRgba); + image.dispose(); + var total = 0; + for (var i = 3; i < bytes!.lengthInBytes; i += 4) { + total += bytes.getUint8(i); + } + return total; }); + return sum!; +} - group('repeat', () { - testWidgets('once fades out after a single cycle', (tester) async { - var deactivated = 0; - await tester.pumpWidget( - _host( - BorderBeam.rotate( - playback: BeamPlayback(repeat: const BeamRepeat.once()), - onDeactivate: () => deactivated++, - child: const SizedBox.expand(), - ), - ), - ); - await tester.pump(); - // The rotate cycle is 1.96s; nothing has expired before it. - await tester.pump(const Duration(milliseconds: 1900)); - expect(_clock(tester).stage, isNot(BeamFadeStage.fadingOut)); - expect(deactivated, 0); - - await tester.pump(const Duration(milliseconds: 100)); - expect( - _clock(tester).stage, - BeamFadeStage.fadingOut, - reason: 'the last cycle ends on a fade, not a cut', - ); - expect(deactivated, 0, reason: 'the fade has not finished yet'); +/// How the mounted beam moves: that its timing reaches the live sweep +/// (direction, phase offset), the one-shot pulse and flash accents, and the +/// live strength listenable. The sweep maths itself — direction, bounce, +/// phase offset, several travellers, ambient effects — is the resolver's, +/// tested in `test/animation/beam_travel_test.dart`; reduced motion and +/// repeat budgets are in `beam_playback_test.dart`. +void main() { + setUpAll(() async { + await BorderBeam.precache(); + }); - await tester.pump(const Duration(milliseconds: 600)); - expect(deactivated, 1); - expect(_clock(tester).isVisible, isFalse); - }); + // A one-second sweep with no rest, so instants map straight to progress. + BeamTiming oneSecond([BeamDirection? direction]) => BeamTiming( + cycle: const Duration(seconds: 1), + cycleGap: Duration.zero, + direction: direction, + ); - testWidgets('count(3) runs three cycles', (tester) async { - var deactivated = 0; + group('direction', () { + testWidgets('the live sweep runs the configured way', (tester) async { await tester.pumpWidget( _host( - BorderBeam.rotate( - playback: BeamPlayback(repeat: const BeamRepeat.count(3)), - onDeactivate: () => deactivated++, + BorderBeam( + timing: oneSecond(BeamDirection.reverse), child: const SizedBox.expand(), ), ), ); await tester.pump(); - await tester.pump(const Duration(milliseconds: 5800)); - expect(_clock(tester).stage, isNot(BeamFadeStage.fadingOut)); - - await tester.pump(const Duration(milliseconds: 200)); - expect(_clock(tester).stage, BeamFadeStage.fadingOut); - await tester.pump(const Duration(milliseconds: 600)); - expect(deactivated, 1); - }); + await tester.pump(const Duration(milliseconds: 250)); + final earlier = _now(tester).travelProgress; + expect(earlier, closeTo(0.75, 1e-9)); - testWidgets('the gap counts toward the budget', (tester) async { - await tester.pumpWidget( - _host( - const BorderBeam.rotate( - timing: BeamTiming(cycleGap: Duration(seconds: 1)), - playback: BeamPlayback(repeat: BeamRepeat.once()), - child: SizedBox.expand(), - ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 2500)); + await tester.pump(const Duration(milliseconds: 100)); + final later = _now(tester).travelProgress; expect( - _clock(tester).stage, - isNot(BeamFadeStage.fadingOut), - reason: 'the rest between sweeps is part of the cycle', + _wrapDelta(earlier, later), + closeTo(-0.1, 1e-9), + reason: 'a reversed beam moves counter-clockwise', ); - await tester.pump(const Duration(milliseconds: 600)); - expect(_clock(tester).stage, BeamFadeStage.fadingOut); }); + }); - testWidgets('forever never stops on its own', (tester) async { + group('phaseOffset', () { + testWidgets('shifts where the sweep starts', (tester) async { await tester.pumpWidget( _host( - const BorderBeam.rotate( - playback: BeamPlayback(repeat: BeamRepeat.forever()), + const BorderBeam( + timing: BeamTiming(cycle: Duration(seconds: 1), phaseOffset: 0.25), child: SizedBox.expand(), ), ), ); - await tester.pump(); - await tester.pump(const Duration(seconds: 12)); - expect(_clock(tester).isVisible, isTrue); - expect(_clock(tester).stage, isNot(BeamFadeStage.fadingOut)); - }); - - testWidgets('a restart runs the budget again', (tester) async { - final controller = BorderBeamController(); - addTearDown(controller.dispose); - await tester.pumpWidget( - _host( - BorderBeam.rotate( - controller: controller, - playback: const BeamPlayback(repeat: BeamRepeat.once()), - child: const SizedBox.expand(), - ), - ), - ); - controller.start(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 2000)); - expect(_clock(tester).stage, BeamFadeStage.fadingOut); - await tester.pump(const Duration(milliseconds: 600)); - expect(controller.isActive, isFalse); - - controller.start(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); - expect(controller.isActive, isTrue); - expect(_clock(tester).stage, isNot(BeamFadeStage.fadingOut)); + expect(_at(tester, 0).travelProgress, closeTo(0.25, 1e-9)); + expect(_at(tester, 0.5).travelProgress, closeTo(0.75, 1e-9)); + expect(_at(tester, 0.9).travelProgress, closeTo(0.15, 1e-9)); }); }); group('pulse and flash', () { - testWidgets('pulse rises and settles back to rest', (tester) async { + Future runningBeam(WidgetTester tester) async { final controller = BorderBeamController(); addTearDown(controller.dispose); await tester.pumpWidget( _host( - BorderBeam.rotate( - controller: controller, - child: const SizedBox.expand(), - ), + BorderBeam(controller: controller, child: const SizedBox.expand()), ), ); controller.start(); await tester.pump(); await tester.pump(const Duration(milliseconds: 700)); + return controller; + } + + testWidgets('pulse lifts the boost and settles back to 1', (tester) async { + final controller = await runningBeam(tester); final clock = _clock(tester); expect(clock.boost, 1); controller.pulse(); expect(clock.isBoosting, isTrue); - await tester.pump(const Duration(milliseconds: 240)); - expect(clock.boost, closeTo(BeamClock.pulsePeak, 1e-6)); - - await tester.pump(const Duration(milliseconds: 180)); - expect(clock.boost, greaterThan(1)); - expect(clock.boost, lessThan(BeamClock.pulsePeak)); - - await tester.pump(const Duration(milliseconds: 200)); + var peak = 1.0; + for (var i = 0; i < 20; i++) { + await tester.pump(const Duration(milliseconds: 16)); + // The rise is spring-eased, so it may crest a hair past the peak. + expect(clock.boost, greaterThanOrEqualTo(1)); + expect(clock.boost, lessThan(BeamClock.pulsePeak * 1.1)); + if (clock.boost > peak) peak = clock.boost; + } + expect(peak, greaterThan(1.5), reason: 'the pulse visibly rises'); + + await tester.pump(const Duration(milliseconds: 400)); expect(clock.boost, 1); expect(clock.isBoosting, isFalse); }); - testWidgets('flash holds at the peak before decaying', (tester) async { - final controller = BorderBeamController(); - addTearDown(controller.dispose); - await tester.pumpWidget( - _host( - BorderBeam.rotate( - controller: controller, - child: const SizedBox.expand(), - ), - ), - ); - controller.start(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); + testWidgets('flash jumps to its peak, holds, and settles back to 1', ( + tester, + ) async { + final controller = await runningBeam(tester); final clock = _clock(tester); controller.flash(); - expect(clock.boost, closeTo(BeamClock.flashPeak, 1e-9)); - await tester.pump(const Duration(milliseconds: 100)); - expect( - clock.boost, - closeTo(BeamClock.flashPeak, 1e-9), - reason: 'the hold keeps it at full for 120ms', - ); - await tester.pump(const Duration(milliseconds: 100)); - expect(clock.boost, lessThan(BeamClock.flashPeak)); - await tester.pump(const Duration(milliseconds: 250)); + expect(clock.boost, greaterThan(1), reason: 'a flash has no rise'); + final peak = clock.boost; + await tester.pump(const Duration(milliseconds: 60)); + expect(clock.boost, closeTo(peak, 1e-9), reason: 'held at the peak'); + + await tester.pump(const Duration(milliseconds: 500)); expect(clock.boost, 1); + expect(clock.isBoosting, isFalse); }); - testWidgets('cycle retiming preserves a pulse envelope in progress', ( - tester, - ) async { + testWidgets('a boost brightens the painted frame', (tester) async { + final controller = await runningBeam(tester); + final rest = await _alphaSum(tester); + expect(rest, greaterThan(0)); + + controller.flash(); + // A zero-length pump repaints at the same instant: only the boost moved. + await tester.pump(); + expect(await _alphaSum(tester), greaterThan(rest)); + }); + + testWidgets('a cycle retime carries a boost in progress', (tester) async { final controller = BorderBeamController(); addTearDown(controller.dispose); Widget build(Duration cycle) => _host( - BorderBeam.rotate( + BorderBeam( controller: controller, timing: BeamTiming(cycle: cycle), child: const SizedBox.expand(), @@ -377,11 +217,12 @@ void main() { controller.pulse(); await tester.pump(const Duration(milliseconds: 100)); final before = clock.boost; + expect(before, greaterThan(1)); await tester.pumpWidget(build(const Duration(seconds: 4))); expect(clock.boost, closeTo(before, 1e-9)); - await tester.pump(const Duration(milliseconds: 140)); - expect(clock.boost, closeTo(BeamClock.pulsePeak, 1e-6)); + await tester.pump(const Duration(milliseconds: 700)); + expect(clock.boost, 1); }); testWidgets('both are no-ops while the beam is hidden', (tester) async { @@ -389,68 +230,157 @@ void main() { addTearDown(controller.dispose); await tester.pumpWidget( _host( - BorderBeam.rotate( - controller: controller, - child: const SizedBox.expand(), - ), + BorderBeam(controller: controller, child: const SizedBox.expand()), ), ); final clock = _clock(tester); expect(clock.isVisible, isFalse); - controller.pulse(); + controller + ..pulse() + ..flash(); expect(clock.isBoosting, isFalse); expect(clock.boost, 1); - controller.flash(); - expect(clock.isBoosting, isFalse); expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('a boost is dropped when the beam restarts', (tester) async { - final controller = BorderBeamController(); - addTearDown(controller.dispose); + testWidgets('a paused beam takes no boost', (tester) async { + final controller = await runningBeam(tester); + controller.pause(); + await tester.pump(); + + controller.pulse(); + expect(_clock(tester).isBoosting, isFalse); + }); + }); + + group('strengthListenable', () { + testWidgets('scales the painted frame live, without a rebuild', ( + tester, + ) async { + final strength = ValueNotifier(1); + addTearDown(strength.dispose); + var builds = 0; await tester.pumpWidget( _host( - BorderBeam.rotate( - controller: controller, - child: const SizedBox.expand(), + Builder( + builder: (context) { + builds++; + return BorderBeam( + strengthListenable: strength, + child: const SizedBox.expand(), + ); + }, ), ), ); - controller.start(); await tester.pump(); await tester.pump(const Duration(milliseconds: 700)); - final clock = _clock(tester); - controller.flash(); - expect(clock.isBoosting, isTrue); + final painter = _painter(tester); + expect(identical(painter.strength, strength), isTrue); + final full = await _alphaSum(tester); + expect(full, greaterThan(0)); - controller.stop(); - await tester.pump(const Duration(milliseconds: 600)); - controller.start(); + strength.value = 0.4; await tester.pump(); - expect(clock.isBoosting, isFalse); - expect(clock.boost, 1); + final dimmed = await _alphaSum(tester); + expect(dimmed, greaterThan(0)); + expect(dimmed, lessThan(full)); + + expect(builds, 1, reason: 'the value never goes through a rebuild'); + expect(identical(_painter(tester).config, painter.config), isTrue); + expect(identical(_painter(tester).resolver, painter.resolver), isTrue); }); - testWidgets('a paused beam takes no boost', (tester) async { - final controller = BorderBeamController(); - addTearDown(controller.dispose); + testWidgets('zero paints nothing, and lifting it paints again', ( + tester, + ) async { + final strength = ValueNotifier(0); + addTearDown(strength.dispose); await tester.pumpWidget( _host( - BorderBeam.rotate( - controller: controller, + BorderBeam( + strengthListenable: strength, child: const SizedBox.expand(), ), ), ); - controller.start(); await tester.pump(); await tester.pump(const Duration(milliseconds: 700)); - controller.pause(); + expect(await _alphaSum(tester), 0); + + strength.value = 1; await tester.pump(); + expect(await _alphaSum(tester), greaterThan(0)); - controller.pulse(); - expect(_clock(tester).isBoosting, isFalse); + await tester.pumpWidget(_host(const SizedBox.expand())); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('a swapped listenable takes over, and removing it restores ' + 'the style strength', (tester) async { + final first = ValueNotifier(1); + addTearDown(first.dispose); + final second = ValueNotifier(0); + addTearDown(second.dispose); + Widget build(ValueNotifier? strength) => _host( + BorderBeam( + strengthListenable: strength, + child: const SizedBox.expand(), + ), + ); + + await tester.pumpWidget(build(first)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 700)); + final clock = _painter(tester).clock; + expect(await _alphaSum(tester), greaterThan(0)); + + await tester.pumpWidget(build(second)); + expect(identical(_painter(tester).strength, second), isTrue); + expect(await _alphaSum(tester), 0, reason: 'the new listenable is read'); + + second.value = 1; + await tester.pump(); + expect(await _alphaSum(tester), greaterThan(0)); + + second.value = 0; + await tester.pump(); + await tester.pumpWidget(build(null)); + expect(_painter(tester).strength, isNull); + expect( + await _alphaSum(tester), + greaterThan(0), + reason: 'without a listenable the style strength applies again', + ); + expect( + identical(_painter(tester).clock, clock), + isTrue, + reason: 'neither swap restarts the beam', + ); + }); + + testWidgets('scales a debug-frozen frame too', (tester) async { + final strength = ValueNotifier(0); + addTearDown(strength.dispose); + await tester.pumpWidget( + _host( + BorderBeam( + playback: const BeamPlayback( + debugFrozenAt: Duration(milliseconds: 1300), + ), + strengthListenable: strength, + child: const SizedBox.expand(), + ), + ), + ); + await tester.pump(); + expect(await _alphaSum(tester), 0); + + strength.value = 1; + await tester.pump(); + expect(await _alphaSum(tester), greaterThan(0)); + expect(tester.binding.transientCallbackCount, 0); }); }); } diff --git a/test/widget/beam_playback_test.dart b/test/widget/beam_playback_test.dart new file mode 100644 index 0000000..cf5e48e --- /dev/null +++ b/test/widget/beam_playback_test.dart @@ -0,0 +1,1063 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/animation/beam_clock.dart'; +import 'package:flutter_border_beam/src/animation/spring_curve.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +import 'test_utils.dart'; + +/// `BeamPlayback` through a mounted beam: whether and when it starts, how +/// long it runs, how it answers the platform's reduced-motion request, the +/// frozen debug frame, the fade curve, and the offscreen pause. +void main() { + // The frozen-frame and reduced-motion groups read pixels. + setUpAll(() async { + await BorderBeam.precache(); + }); + + group('scheduling', () { + testWidgets('autoPlay: false never starts by itself', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeam( + effect: BeamEffect.pulse(), + playback: BeamPlayback(autoPlay: false), + child: SizedBox.expand(), + ), + ), + ); + await tester.pump(const Duration(seconds: 1)); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('active: false stays idle until toggled', (tester) async { + var activated = 0; + var deactivated = 0; + Widget build(bool active) => beamHost( + BorderBeam( + active: active, + onActivate: () => activated++, + onDeactivate: () => deactivated++, + child: const SizedBox.expand(), + ), + ); + + await tester.pumpWidget(build(false)); + await tester.pump(const Duration(seconds: 1)); + expect(activated, 0); + expect(tester.binding.transientCallbackCount, 0); + + await tester.pumpWidget(build(true)); + await tester.pump(); + await tester.pump(pastFadeIn); + expect(activated, 1); + expect(deactivated, 0); + + await tester.pumpWidget(build(false)); + await tester.pump(pastFadeOut); + expect(deactivated, 1); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + await tester.pump(const Duration(milliseconds: 50)); + expect(tester.binding.transientCallbackCount, 0, reason: 'halted'); + }); + + testWidgets('the callbacks in force when a fade ends are the ones called', ( + tester, + ) async { + final calls = []; + Widget build(String tag) => beamHost( + BorderBeam( + onActivate: () => calls.add('$tag:activate'), + child: const SizedBox.expand(), + ), + ); + + await tester.pumpWidget(build('old')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpWidget(build('new')); + await tester.pump(const Duration(milliseconds: 400)); + expect(calls, ['new:activate']); + }); + + testWidgets('startAfter delays the start', (tester) async { + var activated = 0; + await tester.pumpWidget( + beamHost( + BorderBeam( + playback: const BeamPlayback(startAfter: Duration(seconds: 2)), + onActivate: () => activated++, + child: const SizedBox.expand(), + ), + ), + ); + await tester.pump(const Duration(seconds: 1)); + expect(activated, 0); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + expect(tester.binding.transientCallbackCount, 0); + + await tester.pump(const Duration(seconds: 1, milliseconds: 100)); + await tester.pump(); + await tester.pump(pastFadeIn); + expect(activated, 1); + }); + + testWidgets('duration bounds the total play time', (tester) async { + var deactivated = 0; + await tester.pumpWidget( + beamHost( + BorderBeam( + playback: const BeamPlayback(duration: Duration(seconds: 2)), + onDeactivate: () => deactivated++, + child: const SizedBox.expand(), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(deactivated, 0); + await tester.pump(const Duration(seconds: 1, milliseconds: 100)); + expect(beamPainterOf(tester).clock.stage, BeamFadeStage.fadingOut); + await tester.pump(pastFadeOut); + expect(deactivated, 1); + await tester.pump(const Duration(milliseconds: 50)); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('duration counts wall time, not sped-up timeline time', ( + tester, + ) async { + await tester.pumpWidget( + beamHost( + const BorderBeam( + timing: BeamTiming(speed: 4), + playback: BeamPlayback(duration: Duration(seconds: 1)), + child: SizedBox.expand(), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 900)); + expect(beamPainterOf(tester).clock.stage, isNot(BeamFadeStage.fadingOut)); + await tester.pump(const Duration(milliseconds: 200)); + expect(beamPainterOf(tester).clock.stage, BeamFadeStage.fadingOut); + }); + }); + + group('repeat', () { + for (final effect in [ + const BeamEffect.rotate(), + const BeamEffect.pulse(), + ]) { + testWidgets('${effect.name}: count(2) fades out after two cycles', ( + tester, + ) async { + var deactivated = 0; + await tester.pumpWidget( + beamHost( + BorderBeam( + effect: effect, + timing: const BeamTiming(cycle: Duration(seconds: 1)), + playback: const BeamPlayback(repeat: BeamRepeat.count(2)), + onDeactivate: () => deactivated++, + child: const SizedBox.expand(), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1900)); + final clock = beamPainterOf(tester).clock; + expect(clock.stage, isNot(BeamFadeStage.fadingOut)); + + await tester.pump(const Duration(milliseconds: 200)); + expect( + clock.stage, + BeamFadeStage.fadingOut, + reason: 'the last cycle ends on a fade, not a cut', + ); + expect(deactivated, 0); + + await tester.pump(pastFadeOut); + expect(deactivated, 1); + expect(clock.isVisible, isFalse); + expect(tester.binding.transientCallbackCount, 0); + }); + } + + testWidgets('once runs a single cycle', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeam( + timing: BeamTiming(cycle: Duration(seconds: 1)), + playback: BeamPlayback(repeat: BeamRepeat.once()), + child: SizedBox.expand(), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1100)); + expect(beamPainterOf(tester).clock.stage, BeamFadeStage.fadingOut); + }); + + testWidgets('forever keeps running', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeam( + timing: BeamTiming(cycle: Duration(milliseconds: 500)), + playback: BeamPlayback(repeat: BeamRepeat.forever()), + child: SizedBox.expand(), + ), + ), + ); + await tester.pump(); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 500)); + } + final clock = beamPainterOf(tester).clock; + expect(clock.isRunning, isTrue); + expect(clock.stage, isNot(BeamFadeStage.fadingOut)); + }); + + testWidgets('re-activating a spent beam plays the budget again', ( + tester, + ) async { + var deactivated = 0; + Widget build(bool active) => beamHost( + BorderBeam( + active: active, + timing: const BeamTiming(cycle: Duration(seconds: 1)), + playback: const BeamPlayback(repeat: BeamRepeat.once()), + onDeactivate: () => deactivated++, + child: const SizedBox.expand(), + ), + ); + + await tester.pumpWidget(build(true)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1100)); + await tester.pump(pastFadeOut); + expect(deactivated, 1); + + await tester.pumpWidget(build(false)); + await tester.pumpWidget(build(true)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 800)); + final clock = beamPainterOf(tester).clock; + expect(clock.isVisible, isTrue); + expect(clock.stage, isNot(BeamFadeStage.fadingOut)); + await tester.pump(const Duration(milliseconds: 300)); + expect(clock.stage, BeamFadeStage.fadingOut); + }); + }); + + group('reduced motion', () { + Widget reduced(BeamPlayback? playback, {bool on = true, bool? active}) => + beamHost( + disableAnimations: on, + BorderBeam( + active: active, + playback: playback, + child: const SizedBox.expand(), + ), + ); + + testWidgets('staticFrame (the default) paints without ticking', ( + tester, + ) async { + var activated = 0; + await tester.pumpWidget( + beamHost( + disableAnimations: true, + BorderBeam( + onActivate: () => activated++, + child: const SizedBox.expand(), + ), + ), + ); + await tester.pump(const Duration(seconds: 1)); + final painter = beamPainterOf(tester); + expect(painter.staticMode, isTrue); + expect(painter.clock.isRunning, isFalse); + expect(tester.binding.transientCallbackCount, 0); + expect(activated, 0, reason: 'nothing fades in'); + + final pixels = await beamPixels(tester); + expect(pixels.totalAlpha, greaterThan(0), reason: 'the static frame'); + expect(tester.takeException(), isNull); + }); + + testWidgets('staticFrame paints nothing for an inactive beam', ( + tester, + ) async { + await tester.pumpWidget(reduced(null, active: false)); + await tester.pump(const Duration(milliseconds: 200)); + expect(beamPainterOf(tester).staticMode, isFalse); + expect((await beamPixels(tester)).totalAlpha, 0); + }); + + testWidgets('hide removes the painter and paints nothing', (tester) async { + await tester.pumpWidget( + reduced(const BeamPlayback(reducedMotion: BeamReducedMotion.hide)), + ); + await tester.pump(const Duration(milliseconds: 500)); + expect(maybeBeamPainterOf(tester), isNull); + expect(tester.binding.transientCallbackCount, 0); + expect((await beamPixels(tester)).totalAlpha, 0); + }); + + testWidgets('slow runs the clock at a quarter rate', (tester) async { + await tester.pumpWidget( + reduced(const BeamPlayback(reducedMotion: BeamReducedMotion.slow)), + ); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + final clock = beamPainterOf(tester).clock; + expect(clock.isRunning, isTrue); + expect(clock.speed, closeTo(0.25, 1e-12)); + expect(clock.elapsedSeconds, closeTo(0.25, 1e-9)); + expect(beamPainterOf(tester).staticMode, isFalse); + }); + + testWidgets('animate ignores the request', (tester) async { + await tester.pumpWidget( + reduced(const BeamPlayback(reducedMotion: BeamReducedMotion.animate)), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + final painter = beamPainterOf(tester); + expect(painter.staticMode, isFalse); + expect(painter.clock.isRunning, isTrue); + expect(painter.clock.speed, 1); + expect(painter.clock.elapsedSeconds, closeTo(0.5, 1e-9)); + }); + + testWidgets('without the request every mode animates normally', ( + tester, + ) async { + for (final mode in BeamReducedMotion.values) { + await tester.pumpWidget( + reduced(BeamPlayback(reducedMotion: mode), on: false), + ); + await tester.pump(); + final painter = beamPainterOf(tester); + expect(painter.staticMode, isFalse, reason: mode.name); + expect(painter.clock.isRunning, isTrue, reason: mode.name); + expect(painter.clock.speed, 1, reason: mode.name); + } + }); + + testWidgets('turning it on pauses a running beam, off resumes it', ( + tester, + ) async { + Widget build(bool on) => reduced(null, on: on); + + await tester.pumpWidget(build(false)); + await tester.pump(); + await tester.pump(pastFadeIn); + final clock = beamPainterOf(tester).clock; + expect(clock.isRunning, isTrue); + final frozenAt = clock.elapsedSeconds; + + await tester.pumpWidget(build(true)); + expect(clock.isRunning, isFalse); + expect(beamPainterOf(tester).staticMode, isTrue); + await tester.pump(const Duration(milliseconds: 200)); + expect(tester.binding.transientCallbackCount, 0); + expect(clock.elapsedSeconds, closeTo(frozenAt, 1e-9)); + expect(clock.isVisible, isTrue, reason: 'it keeps its play state'); + + await tester.pumpWidget(build(false)); + expect(clock.isRunning, isTrue); + expect(beamPainterOf(tester).staticMode, isFalse); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect( + clock.elapsedSeconds, + greaterThan(frozenAt), + reason: 'the timeline continues where it was frozen', + ); + }); + + testWidgets('turning hide on and off removes and restores the painter', ( + tester, + ) async { + Widget build(bool on) => reduced( + const BeamPlayback(reducedMotion: BeamReducedMotion.hide), + on: on, + ); + + await tester.pumpWidget(build(false)); + await tester.pump(); + await tester.pump(pastFadeIn); + final clock = beamPainterOf(tester).clock; + + await tester.pumpWidget(build(true)); + expect(maybeBeamPainterOf(tester), isNull); + expect(clock.isRunning, isFalse); + await tester.pump(const Duration(milliseconds: 100)); + expect(tester.binding.transientCallbackCount, 0); + + await tester.pumpWidget(build(false)); + expect(identical(beamPainterOf(tester).clock, clock), isTrue); + expect(clock.isRunning, isTrue); + }); + + testWidgets('turning slow on and off changes the rate in place', ( + tester, + ) async { + Widget build(bool on) => reduced( + const BeamPlayback(reducedMotion: BeamReducedMotion.slow), + on: on, + ); + + await tester.pumpWidget(build(false)); + await tester.pump(); + final clock = beamPainterOf(tester).clock; + expect(clock.speed, 1); + + await tester.pumpWidget(build(true)); + expect(clock.speed, closeTo(0.25, 1e-12)); + expect(clock.isRunning, isTrue); + + await tester.pumpWidget(build(false)); + expect(clock.speed, 1); + }); + + testWidgets('turning it off starts a beam that never got to start', ( + tester, + ) async { + Widget build(bool on) => reduced(null, on: on); + + await tester.pumpWidget(build(true)); + await tester.pump(const Duration(milliseconds: 100)); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + expect(tester.binding.transientCallbackCount, 0); + + await tester.pumpWidget(build(false)); + expect(beamPainterOf(tester).clock.isVisible, isTrue); + await tester.pump(const Duration(milliseconds: 50)); + expect(beamPainterOf(tester).clock.isRunning, isTrue); + }); + + testWidgets('turning it off respects a pending startAfter', (tester) async { + Widget build(bool on) => + reduced(const BeamPlayback(startAfter: Duration(seconds: 2)), on: on); + + await tester.pumpWidget(build(true)); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pumpWidget(build(false)); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + await tester.pump(const Duration(seconds: 2)); + await tester.pump(); + expect(beamPainterOf(tester).clock.isVisible, isTrue); + }); + + testWidgets('turning it off does not replay a beam that already ran', ( + tester, + ) async { + var deactivated = 0; + Widget build(bool on) => beamHost( + disableAnimations: on, + BorderBeam( + playback: const BeamPlayback(duration: Duration(seconds: 1)), + onDeactivate: () => deactivated++, + child: const SizedBox.expand(), + ), + ); + + await tester.pumpWidget(build(false)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1100)); + await tester.pump(pastFadeOut); + expect(deactivated, 1); + + await tester.pumpWidget(build(true)); + await tester.pump(const Duration(milliseconds: 50)); + await tester.pumpWidget(build(false)); + await tester.pump(const Duration(milliseconds: 50)); + expect( + beamPainterOf(tester).clock.isVisible, + isFalse, + reason: 'its play time is spent', + ); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('turning it off does not resume a controller-paused beam', ( + tester, + ) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + Widget build(bool on) => beamHost( + disableAnimations: on, + BorderBeam(controller: controller, child: const SizedBox.expand()), + ); + + await tester.pumpWidget(build(false)); + controller.start(); + await tester.pump(); + await tester.pump(pastFadeIn); + controller.pause(); + await tester.pump(const Duration(milliseconds: 50)); + expect(controller.isRunning, isFalse); + + await tester.pumpWidget(build(true)); + await tester.pump(const Duration(milliseconds: 50)); + await tester.pumpWidget(build(false)); + await tester.pump(const Duration(milliseconds: 50)); + expect( + controller.isRunning, + isFalse, + reason: 'the controller owns the pause', + ); + expect(controller.isActive, isTrue); + }); + + group('with a controller', () { + Widget controlled( + BorderBeamController controller, { + bool on = true, + BeamReducedMotion? mode, + }) => beamHost( + disableAnimations: on, + BorderBeam( + controller: controller, + playback: BeamPlayback(reducedMotion: mode), + child: const SizedBox.expand(), + ), + ); + + BorderBeamController newController() { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + return controller; + } + + testWidgets('start shows the static frame without ticking', ( + tester, + ) async { + final controller = newController(); + await tester.pumpWidget(controlled(controller)); + controller.start(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + + expect(controller.isActive, isTrue); + expect(controller.isRunning, isFalse); + expect(tester.binding.transientCallbackCount, 0); + expect(beamPainterOf(tester).staticMode, isTrue); + expect((await beamPixels(tester)).totalAlpha, greaterThan(0)); + }); + + testWidgets('start under hide paints nothing and never ticks', ( + tester, + ) async { + final controller = newController(); + await tester.pumpWidget( + controlled(controller, mode: BeamReducedMotion.hide), + ); + controller.start(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + + expect(controller.isRunning, isFalse); + expect(tester.binding.transientCallbackCount, 0); + expect((await beamPixels(tester)).totalAlpha, 0); + }); + + testWidgets('resume does not set a still beam moving', (tester) async { + final controller = newController(); + await tester.pumpWidget(controlled(controller, on: false)); + controller.start(); + await tester.pump(); + await tester.pump(pastFadeIn); + await tester.pumpWidget(controlled(controller)); + await tester.pump(); + expect(controller.isRunning, isFalse); + + controller.resume(); + await tester.pump(const Duration(milliseconds: 200)); + expect(controller.isRunning, isFalse); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('turning it off runs a beam the controller started', ( + tester, + ) async { + final controller = newController(); + await tester.pumpWidget(controlled(controller)); + controller.start(); + await tester.pump(); + await tester.pumpWidget(controlled(controller, on: false)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + expect(controller.isRunning, isTrue); + expect(beamPainterOf(tester).staticMode, isFalse); + expect( + beamPainterOf(tester).clock.fadeOpacity, + 1, + reason: 'the still frame was at full opacity; no fade replays', + ); + }); + + testWidgets('stop still takes a still beam away', (tester) async { + final controller = newController(); + await tester.pumpWidget(controlled(controller)); + controller.start(); + await tester.pump(); + controller.stop(); + await tester.pump(); + await tester.pump(pastFadeOut); + + expect(controller.isActive, isFalse); + expect(tester.binding.transientCallbackCount, 0); + expect((await beamPixels(tester)).totalAlpha, 0); + }); + }); + }); + + group('debugFrozenAt', () { + // Transparent child: every pixel with alpha is the beam's. + Widget frozen( + Duration at, { + BeamStyle? style, + ValueListenable? strength, + }) => beamHost( + BorderBeam( + style: style, + strengthListenable: strength, + playback: BeamPlayback(debugFrozenAt: at), + child: const SizedBox.expand(), + ), + ); + + Future repaint(WidgetTester tester) async { + tester + .renderObject( + find.descendant( + of: find.byType(BorderBeam), + matching: find.byType(CustomPaint), + ), + ) + .markNeedsPaint(); + await tester.pump(); + } + + testWidgets('never starts the clock', (tester) async { + await tester.pumpWidget(frozen(const Duration(seconds: 2))); + await tester.pump(const Duration(seconds: 1)); + final painter = beamPainterOf(tester); + expect(painter.frozenAt, const Duration(seconds: 2)); + expect(painter.clock.isRunning, isFalse); + expect(painter.clock.isVisible, isFalse); + expect(painter.clock.elapsedSeconds, 0); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('paints the same pixels however much time passes', ( + tester, + ) async { + await tester.pumpWidget(frozen(const Duration(milliseconds: 1300))); + final first = await beamPixels(tester); + expect(first.totalAlpha, greaterThan(0)); + + await tester.pump(const Duration(seconds: 4)); + await tester.pump(const Duration(seconds: 7)); + await repaint(tester); + final later = await beamPixels(tester); + expect(later.bytes, first.bytes); + }); + + testWidgets('is the frame the live timeline paints at that instant', ( + tester, + ) async { + await tester.pumpWidget(frozen(const Duration(milliseconds: 1300))); + final still = await beamPixels(tester); + + // A fresh State: the live beam starts its own clock from zero. + await tester.pumpWidget( + beamHost( + const BorderBeam(key: ValueKey('live'), child: SizedBox.expand()), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1300)); + expect(beamPainterOf(tester).clock.elapsedSeconds, closeTo(1.3, 1e-12)); + final live = await beamPixels(tester); + expect(live.bytes, still.bytes); + }); + + testWidgets('clearing it on a mounted beam starts the beam', ( + tester, + ) async { + await tester.pumpWidget(frozen(const Duration(milliseconds: 1300))); + await tester.pump(const Duration(milliseconds: 100)); + + await tester.pumpWidget( + beamHost(const BorderBeam(child: SizedBox.expand())), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + final clock = beamPainterOf(tester).clock; + expect(clock.isVisible, isTrue); + expect(clock.isRunning, isTrue); + }); + + testWidgets('setting it on a running beam stops spending frames', ( + tester, + ) async { + await tester.pumpWidget( + beamHost(const BorderBeam(child: SizedBox.expand())), + ); + await tester.pump(); + await tester.pump(pastFadeIn); + + await tester.pumpWidget(frozen(const Duration(seconds: 1))); + await tester.pump(const Duration(milliseconds: 100)); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets("leaves a controller's clock to the controller", ( + tester, + ) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + Widget build({Duration? at}) => beamHost( + BorderBeam( + controller: controller, + playback: BeamPlayback(debugFrozenAt: at), + child: const SizedBox.expand(), + ), + ); + + await tester.pumpWidget(build()); + controller.start(); + await tester.pump(); + await tester.pump(pastFadeIn); + expect(controller.isRunning, isTrue); + + // Pinning the frame does not pause a clock the controller runs... + await tester.pumpWidget(build(at: const Duration(seconds: 1))); + expect(controller.isRunning, isTrue); + expect(beamPainterOf(tester).frozenAt, const Duration(seconds: 1)); + + // ...and unpinning does not resume one the controller paused. + controller.pause(); + await tester.pumpWidget(build()); + expect(controller.isRunning, isFalse, reason: 'the controller paused'); + expect(controller.isActive, isTrue); + }); + + testWidgets('a different instant is a different frame', (tester) async { + await tester.pumpWidget(frozen(const Duration(milliseconds: 1300))); + final early = await beamPixels(tester); + await tester.pumpWidget(frozen(const Duration(milliseconds: 1900))); + await tester.pump(); + final late = await beamPixels(tester); + expect(late.totalAlpha, greaterThan(0)); + expect(late.bytes, isNot(early.bytes)); + }); + + testWidgets('honors style strength', (tester) async { + const at = Duration(milliseconds: 1300); + await tester.pumpWidget(frozen(at)); + final full = (await beamPixels(tester)).totalAlpha; + + await tester.pumpWidget( + frozen(at, style: const BeamStyle(strength: 0.5)), + ); + await tester.pump(); + final half = (await beamPixels(tester)).totalAlpha; + + await tester.pumpWidget(frozen(at, style: const BeamStyle(strength: 0))); + await tester.pump(); + final none = (await beamPixels(tester)).totalAlpha; + + expect(full, greaterThan(0)); + expect(half, inExclusiveRange(0, full)); + expect(none, 0); + }); + + testWidgets('honors a live strength listenable', (tester) async { + final strength = ValueNotifier(0); + addTearDown(strength.dispose); + await tester.pumpWidget( + frozen(const Duration(milliseconds: 1300), strength: strength), + ); + expect((await beamPixels(tester)).totalAlpha, 0); + + strength.value = 1; + await tester.pump(); + expect((await beamPixels(tester)).totalAlpha, greaterThan(0)); + expect(tester.binding.transientCallbackCount, 0, reason: 'still frozen'); + }); + }); + + group('fadeCurve', () { + // Points along each fade, from the clock's own lengths. + Duration seconds(double s) => Duration(microseconds: (s * 1e6).round()); + final halfIn = seconds(BeamClock.fadeInSeconds / 2); + final quarterIn = seconds(BeamClock.fadeInSeconds / 4); + final halfOut = seconds(BeamClock.fadeOutSeconds / 2); + + testWidgets('the widget hands its curve to the clock', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeam( + playback: BeamPlayback(fadeCurve: BeamPlayback.cssEase), + child: SizedBox.expand(), + ), + ), + ); + await tester.pump(); + await tester.pump(halfIn); + final clock = beamPainterOf(tester).clock; + expect(clock.fadeCurve, BeamPlayback.cssEase); + expect( + clock.fadeOpacity, + closeTo(BeamPlayback.cssEase.transform(0.5), 1e-9), + ); + }); + + testWidgets('a curve replaces the spring on both fades', (tester) async { + Widget build(bool active) => beamHost( + BorderBeam( + active: active, + playback: const BeamPlayback(fadeCurve: Curves.linear), + child: const SizedBox.expand(), + ), + ); + + await tester.pumpWidget(build(true)); + await tester.pump(); + await tester.pump(halfIn); + final clock = beamPainterOf(tester).clock; + expect(clock.fadeOpacity, closeTo(0.5, 1e-9), reason: 'half way in'); + + await tester.pump(halfIn + const Duration(milliseconds: 100)); + await tester.pumpWidget(build(false)); + await tester.pump(halfOut); + expect(clock.fadeOpacity, closeTo(0.5, 1e-9), reason: 'half way out'); + }); + + testWidgets('the default fade is the spring, not a plain ease', ( + tester, + ) async { + await tester.pumpWidget( + beamHost(const BorderBeam(child: SizedBox.expand())), + ); + await tester.pump(); + await tester.pump(halfIn); + final clock = beamPainterOf(tester).clock; + expect(clock.fadeCurve, isNull); + expect( + clock.fadeOpacity, + closeTo(BeamSpringCurve.fadeIn.transform(0.5), 1e-3), + reason: 'halfway through the fade-in, the fade-in spring', + ); + expect( + clock.fadeOpacity, + isNot(closeTo(BeamPlayback.cssEase.transform(0.5), 1e-3)), + reason: 'not the CSS ease', + ); + + await tester.pump(pastFadeIn); + await tester.pumpWidget( + beamHost(const BorderBeam(active: false, child: SizedBox.expand())), + ); + await tester.pump(halfOut); + expect( + clock.fadeOpacity, + closeTo(1 - BeamSpringCurve.fadeOut.transform(0.5), 1e-3), + reason: 'halfway through the fade-out, the fade-out spring', + ); + }); + + testWidgets('changing the curve mid-fade lands on the next frame', ( + tester, + ) async { + Widget build(Curve? curve) => beamHost( + BorderBeam( + playback: BeamPlayback(fadeCurve: curve), + child: const SizedBox.expand(), + ), + ); + + await tester.pumpWidget(build(null)); + await tester.pump(); + await tester.pump(quarterIn); + await tester.pumpWidget(build(Curves.linear)); + await tester.pump(halfIn - quarterIn); + final clock = beamPainterOf(tester).clock; + expect(clock.fadeCurve, Curves.linear); + expect(clock.fadeOpacity, closeTo(0.5, 1e-9)); + }); + }); + + group('pauseWhenOffscreen', () { + // The cache extent keeps rows built well past the 256px margin, so there + // is something offscreen left to pause. + Widget list({bool? pause, Widget Function(int index)? row}) => beamHost( + size: const Size(400, 600), + ListView.builder( + scrollCacheExtent: const ScrollCacheExtent.pixels(4000), + itemCount: 12, + itemBuilder: (context, index) => SizedBox( + height: 200, + child: + row?.call(index) ?? + BorderBeam( + key: ValueKey(index), + playback: BeamPlayback(pauseWhenOffscreen: pause), + child: const SizedBox.expand(), + ), + ), + ), + ); + + BeamClock clockAt(WidgetTester tester, int index) => beamPainterOf( + tester, + within: find.byKey(ValueKey(index), skipOffstage: false), + ).clock; + + testWidgets('offscreen rows stop ticking and resume on return', ( + tester, + ) async { + await tester.pumpWidget(list()); + await tester.pump(); + // Rows 0–2 fill the 600px viewport; 3 and 4 start within the 256px + // margin below it; 5 onward are further out. + for (final index in [0, 1, 2, 3, 4]) { + expect(clockAt(tester, index).isRunning, isTrue, reason: '$index'); + } + for (final index in [5, 6, 11]) { + expect(clockAt(tester, index).isRunning, isFalse, reason: '$index'); + } + + // A paused beam keeps its play state and its timeline. + final resting = clockAt(tester, 6); + expect(resting.isVisible, isTrue); + final held = resting.elapsedSeconds; + + // Not pumpAndSettle: a running beam schedules frames forever. Two + // frames are enough — one lands the scroll, one runs the post-frame + // visibility check. + await tester.drag(find.byType(ListView), const Offset(0, -1200)); + await tester.pump(); + await tester.pump(); + + expect(clockAt(tester, 6).isRunning, isTrue, reason: 'scrolled in'); + expect( + clockAt(tester, 6).elapsedSeconds, + greaterThanOrEqualTo(held), + reason: 'it resumes rather than restarting', + ); + expect(clockAt(tester, 0).isRunning, isFalse, reason: 'now far above'); + }); + + testWidgets('false keeps every row running', (tester) async { + await tester.pumpWidget(list(pause: false)); + await tester.pump(); + for (final index in [0, 6, 11]) { + expect(clockAt(tester, index).isRunning, isTrue, reason: '$index'); + } + }); + + testWidgets('offscreen time does not consume a duration budget', ( + tester, + ) async { + await tester.pumpWidget( + list( + row: (index) => index == 6 + ? const BorderBeam( + key: ValueKey(6), + playback: BeamPlayback(duration: Duration(seconds: 1)), + child: SizedBox.expand(), + ) + : const SizedBox.expand(), + ), + ); + await tester.pump(); + final clock = clockAt(tester, 6); + expect(clock.isRunning, isFalse, reason: 'the beam starts offscreen'); + + await tester.pump(const Duration(seconds: 2)); + expect(clock.isVisible, isTrue); + expect(clock.stage, isNot(BeamFadeStage.fadingOut)); + + await tester.drag(find.byType(ListView), const Offset(0, -1200)); + await tester.pump(); + await tester.pump(); + expect(clock.isRunning, isTrue); + await tester.pump(const Duration(milliseconds: 900)); + expect(clock.stage, isNot(BeamFadeStage.fadingOut)); + await tester.pump(const Duration(milliseconds: 200)); + expect(clock.stage, BeamFadeStage.fadingOut); + }); + + testWidgets("pinning a controller's offscreen beam lifts its own pause", ( + tester, + ) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + Widget rows({Duration? at}) => list( + row: (index) => index == 6 + ? BorderBeam( + key: const ValueKey(6), + controller: controller, + playback: BeamPlayback(debugFrozenAt: at), + child: const SizedBox.expand(), + ) + : const SizedBox.expand(), + ); + + await tester.pumpWidget(rows()); + controller.start(); + await tester.pump(); + // A small scroll re-runs the visibility check on the running beam. + await tester.drag(find.byType(ListView), const Offset(0, -10)); + await tester.pump(); + await tester.pump(); + expect(controller.isRunning, isFalse, reason: 'paused offscreen'); + + // A pinned beam stops watching the scroll, so the pause the beam took + // for it is lifted — not handed to the pin, which holds nothing of a + // controller's. + await tester.pumpWidget(rows(at: const Duration(seconds: 1))); + expect(controller.isRunning, isTrue); + }); + + testWidgets('a beam outside any scrollable is never paused', ( + tester, + ) async { + await tester.pumpWidget( + beamHost( + const SizedBox( + width: 350, + height: 140, + child: BorderBeam(child: SizedBox.expand()), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(beamPainterOf(tester).clock.isRunning, isTrue); + }); + + testWidgets('an offscreen beam disposes without leaking its ticker', ( + tester, + ) async { + await tester.pumpWidget(list()); + await tester.pump(); + expect(clockAt(tester, 11).isRunning, isFalse); + await tester.pumpWidget(beamHost(const SizedBox.expand())); + await tester.pump(); + expect(tester.takeException(), isNull); + expect(tester.binding.transientCallbackCount, 0); + }); + }); +} diff --git a/test/widget/beam_progress_test.dart b/test/widget/beam_progress_test.dart index 946c7e6..c937103 100644 --- a/test/widget/beam_progress_test.dart +++ b/test/widget/beam_progress_test.dart @@ -1,14 +1,17 @@ -import 'dart:math' as math; -import 'dart:ui' as ui; - -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam/src/animation/beam_clock.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; +import 'package:flutter_border_beam/src/animation/beam_phases.dart'; +import 'package:flutter_border_beam/src/look/rotate_look.dart'; +import 'package:flutter_border_beam/src/render/beam_frame.dart'; +import 'package:flutter_border_beam/src/render/beam_painter.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -Widget _host(Widget child) => MaterialApp( +Widget _host(Widget child, {bool disableAnimations = false}) => MaterialApp( theme: ThemeData(brightness: Brightness.dark), + builder: (context, app) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: disableAnimations), + child: app!, + ), home: Scaffold( body: Center(child: SizedBox(width: 350, height: 140, child: child)), ), @@ -25,419 +28,273 @@ BeamPainter _painter(WidgetTester tester) => tester .whereType() .first; -BeamClock _clock(WidgetTester tester) => _painter(tester).clock; - -/// Whether the painter leaves a non-transparent pixel in a 350x140 box. -/// -/// Rasterizing is real async work, so it runs outside the fake clock. -Future _paintsPixels(WidgetTester tester, BeamPainter painter) async { - const size = ui.Size(350, 140); - final painted = await tester.runAsync(() async { - final recorder = ui.PictureRecorder(); - painter.paint(ui.Canvas(recorder), size); - final picture = recorder.endRecording(); - final image = await picture.toImage( - size.width.toInt(), - size.height.toInt(), - ); - final bytes = await image.toByteData(format: ui.ImageByteFormat.rawRgba); - picture.dispose(); - image.dispose(); - for (var i = 3; i < bytes!.lengthInBytes; i += 4) { - if (bytes.getUint8(i) != 0) return true; - } - return false; - }); - return painted!; +// The phases the painter draws right now, driven sweep included. +BeamFramePhases _now(WidgetTester tester) { + final painter = _painter(tester); + return painter.resolver.sample( + painter.clock.elapsedSeconds, + painter.clock.fadeOpacity, + progress: painter.progress?.value, + ); } -/// The three ways something other than the clock moves the beam — a driven -/// [BorderBeam.progress], a [BorderBeam.follow] pointer, and the live -/// strength/speed listenables — plus the childless overlay constructor. -void main() { - group('progress', () { - testWidgets('drives the sweep from the value', (tester) async { - await tester.pumpWidget( - _host(const BorderBeam.rotate(progress: 0.25, child: SizedBox())), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - final painter = _painter(tester); - expect(painter.progress?.value, 0.25); - expect( - painter.resolver - .sample(painter.clock.elapsedSeconds, 1, progress: 0.25) - .angleRadians, - closeTo(math.pi / 2, 1e-9), - ); - }); - - testWidgets('changing it does not re-resolve the config', (tester) async { - Widget build(double progress) => - _host(BorderBeam.rotate(progress: progress, child: const SizedBox())); +BeamFrameData _frame(WidgetTester tester) => + _painter(tester).renderer.debugFrame; - await tester.pumpWidget(build(0.1)); - final before = _painter(tester); - await tester.pumpWidget(build(0.9)); - final after = _painter(tester); - expect(identical(before.config, after.config), isTrue); - expect(identical(before.resolver, after.resolver), isTrue); - expect(after.progress?.value, 0.9); - }); +// How far the painted rotate head sits from [progress] round the ring. +double _headOffset(WidgetTester tester, double progress) { + final head = _frame(tester).conicStart + rotateHeadStop; + return ((head - progress) + 0.5) % 1.0 - 0.5; +} - testWidgets('clamps out-of-range values', (tester) async { - await tester.pumpWidget( - _host(const BorderBeam.rotate(progress: 1.7, child: SizedBox())), - ); - expect(_painter(tester).progress?.value, 1); - }); +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 700)); +} - testWidgets('the clock still runs underneath', (tester) async { - await tester.pumpWidget( - _host(const BorderBeam.line(progress: 0.5, child: SizedBox())), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - final painter = _painter(tester); - expect(painter.clock.isRunning, isTrue); - final early = painter.resolver.sample(0.7, 1, progress: 0.5); - final late = painter.resolver.sample(3.7, 1, progress: 0.5); - expect(early.lineX, closeTo(late.lineX, 1e-9)); - expect(early.hueDegrees, isNot(closeTo(late.hueDegrees, 1e-6))); - }); +// Derived, so a new effect joins the family it belongs to. +final _travelling = [ + for (final effect in BeamEffect.values) + if (effect.travels) effect, +]; - testWidgets('null hands the travel back to the clock', (tester) async { - Widget build(double? progress) => - _host(BorderBeam.rotate(progress: progress, child: const SizedBox())); +final _ambient = [ + for (final effect in BeamEffect.values) + if (!effect.travels) effect, +]; - await tester.pumpWidget(build(0.25)); - await tester.pumpWidget(build(null)); - expect(_painter(tester).progress?.value, isNull); - }); +/// `BorderBeam.progress`: a value, not the clock, places the sweep of a +/// travelling effect, while the fade and the hue keep running underneath. +void main() { + setUpAll(() async { + await BorderBeam.precache(); }); - group('follow', () { - testWidgets('eases the sweep toward the pointer', (tester) async { - Widget build(Offset? follow) => - _host(BorderBeam.rotate(follow: follow, child: const SizedBox())); - - await tester.pumpWidget(build(null)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - - // The right edge of the box: a quarter of the way round from 12 - // o'clock. - await tester.pumpWidget(build(const Offset(1, 0.5))); - final painter = _painter(tester); - for (var i = 0; i < 10; i++) { - await tester.pump(const Duration(milliseconds: 16)); - } - final part = painter.progress?.value; - expect(part, isNotNull); - expect( - part, - isNot(closeTo(0.25, 0.005)), - reason: 'the beam eases rather than snapping', - ); - - for (var i = 0; i < 30; i++) { - await tester.pump(const Duration(milliseconds: 16)); - } - expect(painter.progress?.value, closeTo(0.25, 0.01)); - }); - - testWidgets('takes the short way round', (tester) async { - Widget build(Offset? follow) => - _host(BorderBeam.rotate(follow: follow, child: const SizedBox())); - - await tester.pumpWidget(build(null)); - await tester.pump(); - // 100ms into the 1.96s cycle: the beam is just past 12 o'clock. - await tester.pump(const Duration(milliseconds: 100)); - // The left edge is progress 0.75 — a short hop backwards through 0, - // not three quarters of a lap forwards. - await tester.pumpWidget(build(const Offset(0, 0.5))); - final painter = _painter(tester); - await tester.pump(const Duration(milliseconds: 16)); - var previous = painter.progress!.value!; - for (var i = 0; i < 40; i++) { - await tester.pump(const Duration(milliseconds: 16)); - final now = painter.progress!.value!; - final step = ((now - previous) + 0.5) % 1.0 - 0.5; - expect( - step, - lessThanOrEqualTo(1e-9), - reason: 'every step runs backwards toward the target', - ); - previous = now; - } - expect(previous, closeTo(0.75, 0.01)); - }); - - testWidgets('releasing resumes from where the pointer left it', ( + for (final effect in _travelling) { + testWidgets('drives the ${effect.name} sweep and holds it there', ( tester, ) async { - Widget build(Offset? follow) => - _host(BorderBeam.rotate(follow: follow, child: const SizedBox())); - - await tester.pumpWidget(build(null)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - await tester.pumpWidget(build(const Offset(1, 0.5))); - for (var i = 0; i < 40; i++) { - await tester.pump(const Duration(milliseconds: 16)); - } - final painter = _painter(tester); - final held = painter.progress!.value!; - - await tester.pumpWidget(build(null)); - expect(painter.progress?.value, isNull); - final resumed = painter.resolver - .sample(painter.clock.elapsedSeconds, 1) - .travelProgress; - expect( - resumed, - closeTo(held, 1e-6), - reason: 'the timed sweep picks up where the follow ended', - ); - expect(painter.resolver.travelTimeOffset, isNot(0)); - - // And it keeps travelling from there. - await tester.pump(const Duration(milliseconds: 100)); - final later = painter.resolver - .sample(painter.clock.elapsedSeconds, 1) - .travelProgress; - expect(later, greaterThan(resumed)); - }); - - testWidgets('the line variant follows the axis it travels', (tester) async { - Widget build(Offset? follow) => - _host(BorderBeam.line(follow: follow, child: const SizedBox())); - - await tester.pumpWidget(build(null)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - await tester.pumpWidget(build(const Offset(0.8, 0.2))); - final painter = _painter(tester); - for (var i = 0; i < 40; i++) { - await tester.pump(const Duration(milliseconds: 16)); - } - expect(painter.progress?.value, closeTo(0.8, 0.01)); - }); - - testWidgets('the pulse variants have no travel to steer', (tester) async { await tester.pumpWidget( _host( - const BorderBeam.pulseInside( - follow: Offset(1, 0.5), - child: SizedBox(), + BorderBeam( + effect: effect, + progress: 0.3, + child: const SizedBox.expand(), ), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - for (var i = 0; i < 10; i++) { - await tester.pump(const Duration(milliseconds: 16)); - } - expect(_painter(tester).progress?.value, isNull); + await _settle(tester); + expect(_painter(tester).progress?.value, 0.3); + var phases = _now(tester); + expect(phases.travelProgress, 0.3); + expect(phases.travellers.first, 0.3); + expect(phases.driven, isTrue); + + await tester.pump(const Duration(milliseconds: 900)); + phases = _now(tester); + expect(phases.travelProgress, 0.3, reason: 'time does not move it'); + expect(phases.driven, isTrue); }); + } - testWidgets('an explicit progress wins over it', (tester) async { - await tester.pumpWidget( - _host( - const BorderBeam.rotate( - progress: 0.5, - follow: Offset(1, 0.5), - child: SizedBox(), - ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - for (var i = 0; i < 20; i++) { - await tester.pump(const Duration(milliseconds: 16)); - } - expect(_painter(tester).progress?.value, 0.5); - }); - }); + testWidgets('clamps out-of-range values into 0–1', (tester) async { + Widget build(double progress) => + _host(BorderBeam(progress: progress, child: const SizedBox.expand())); - group('strengthListenable', () { - testWidgets('scales the painted layers without a rebuild', (tester) async { - final strength = ValueNotifier(1); - addTearDown(strength.dispose); - var builds = 0; - await tester.pumpWidget( - _host( - Builder( - builder: (context) { - builds++; - return BorderBeam.rotate( - strengthListenable: strength, - child: const SizedBox(), - ); - }, - ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - final painter = _painter(tester); - expect(await _paintsPixels(tester, painter), isTrue); - expect(builds, 1); + await tester.pumpWidget(build(1.7)); + expect(_painter(tester).progress?.value, 1); + expect(_now(tester).travelProgress, 1); - strength.value = 0; - await tester.pump(); - expect( - await _paintsPixels(tester, _painter(tester)), - isFalse, - reason: 'a strength of 0 suppresses every layer', - ); - expect(builds, 1, reason: 'the value never goes through a rebuild'); - expect(identical(_painter(tester).config, painter.config), isTrue); - }); + await tester.pumpWidget(build(-0.4)); + expect(_painter(tester).progress?.value, 0); + expect(_now(tester).travelProgress, 0); + }); - testWidgets('reaches the painter as the listenable itself', (tester) async { - final strength = ValueNotifier(0.4); - addTearDown(strength.dispose); - await tester.pumpWidget( - _host( - BorderBeam.rotate( - strengthListenable: strength, - child: const SizedBox(), - ), + testWidgets('the clock, fade and hue keep running underneath', ( + tester, + ) async { + await tester.pumpWidget( + _host( + const BorderBeam( + effect: BeamEffect.line(), + progress: 0.5, + child: SizedBox.expand(), ), - ); - expect(identical(_painter(tester).strength, strength), isTrue); - }); + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + final painter = _painter(tester); + expect(painter.clock.isRunning, isTrue); + final fading = _now(tester); + expect(fading.fadeOpacity, lessThan(1), reason: 'still fading in'); + + await tester.pump(const Duration(milliseconds: 1500)); + final later = _now(tester); + expect(later.fadeOpacity, closeTo(1, 1e-6)); + expect(later.travelProgress, fading.travelProgress); + expect(later.hueDegrees, isNot(closeTo(fading.hueDegrees, 1e-6))); + }); - testWidgets('still scales a debug-frozen frame', (tester) async { - final strength = ValueNotifier(0); - addTearDown(strength.dispose); - await tester.pumpWidget( - _host( - BorderBeam.rotate( - playback: const BeamPlayback( - debugFrozenAt: Duration(milliseconds: 1300), - ), - strengthListenable: strength, - child: const SizedBox(), + testWidgets('the rest between sweeps does not dim a driven sweep', ( + tester, + ) async { + // A 1.4s sweep that rests 1.6s after each pass. + await tester.pumpWidget( + _host( + const BorderBeam( + timing: BeamTiming( + cycle: Duration(milliseconds: 1400), + cycleGap: Duration(milliseconds: 1600), ), + progress: 0.5, + child: SizedBox.expand(), ), - ); - await tester.pump(); - expect(await _paintsPixels(tester, _painter(tester)), isFalse); - - strength.value = 1; - await tester.pump(); - expect(await _paintsPixels(tester, _painter(tester)), isTrue); - }); + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 2200)); + final painter = _painter(tester); + final t = painter.clock.elapsedSeconds; + expect( + painter.resolver.sample(t, 1).fadeOpacity, + 0, + reason: 'the timed sweep would be resting now', + ); + expect(painter.progress?.value, 0.5); + final driven = painter.resolver.sample( + t, + 1, + progress: painter.progress?.value, + ); + expect(driven.fadeOpacity, 1); + expect(driven.travelProgress, 0.5); }); - group('speedListenable', () { - testWidgets('drives the clock rate without a rebuild', (tester) async { - final speed = ValueNotifier(2); - addTearDown(speed.dispose); - var builds = 0; - await tester.pumpWidget( - _host( - Builder( - builder: (context) { - builds++; - return BorderBeam.rotate( - speedListenable: speed, - child: const SizedBox(), - ); - }, - ), + testWidgets('a change repaints without re-resolving the config', ( + tester, + ) async { + // Frozen: the clock never ticks, so only the progress itself can repaint. + Widget build(double progress) => _host( + BorderBeam( + effect: const BeamEffect.rotate(), + progress: progress, + playback: const BeamPlayback( + debugFrozenAt: Duration(milliseconds: 1300), ), - ); - final clock = _clock(tester); - expect(clock.speed, 2); - - speed.value = 0.5; - await tester.pump(); - expect(clock.speed, 0.5); - expect(builds, 1); - }); + child: const SizedBox.expand(), + ), + ); - testWidgets('wins over the timing speed', (tester) async { - final speed = ValueNotifier(3); - addTearDown(speed.dispose); - await tester.pumpWidget( - _host( - BorderBeam.rotate( - timing: const BeamTiming(speed: 0.5), - speedListenable: speed, - child: const SizedBox(), - ), - ), - ); - expect(_clock(tester).speed, 3); - }); + await tester.pumpWidget(build(0.2)); + await tester.pump(); + final before = _painter(tester); + expect(_headOffset(tester, 0.2), closeTo(0, 1e-6)); + + await tester.pumpWidget(build(0.8)); + final after = _painter(tester); + expect(identical(before.config, after.config), isTrue); + expect(identical(before.resolver, after.resolver), isTrue); + expect(after.shouldRepaint(before), isFalse); + expect(after.progress?.value, 0.8); + expect( + _headOffset(tester, 0.8), + closeTo(0, 1e-6), + reason: 'the new value reached the painted frame', + ); + expect(tester.binding.transientCallbackCount, 0); + }); - testWidgets('a swap moves the listener across', (tester) async { - final first = ValueNotifier(2); - final second = ValueNotifier(4); - addTearDown(first.dispose); - addTearDown(second.dispose); - Widget build(ValueNotifier speed) => _host( - BorderBeam.rotate(speedListenable: speed, child: const SizedBox()), - ); + testWidgets('null hands the travel back to the clock', (tester) async { + Widget build(double? progress) => _host( + BorderBeam( + progress: progress, + timing: const BeamTiming(cycle: Duration(seconds: 2)), + child: const SizedBox.expand(), + ), + ); - await tester.pumpWidget(build(first)); - await tester.pumpWidget(build(second)); - expect(_clock(tester).speed, 4); + await tester.pumpWidget(build(0.9)); + await _settle(tester); + expect(_now(tester).travelProgress, 0.9); + + await tester.pumpWidget(build(null)); + final painter = _painter(tester); + expect(painter.progress?.value, isNull); + final phases = _now(tester); + expect(phases.driven, isFalse); + expect( + phases.travelProgress, + closeTo((painter.clock.elapsedSeconds / 2) % 1.0, 1e-9), + reason: 'the timed sweep, wherever its schedule has it', + ); - first.value = 9; - await tester.pump(); - expect(_clock(tester).speed, 4, reason: 'the old listener is gone'); - second.value = 0.5; - await tester.pump(); - expect(_clock(tester).speed, 0.5); - }); + await tester.pumpWidget(_host(const SizedBox.expand())); + expect(tester.binding.transientCallbackCount, 0); }); - group('BorderBeam.overlay', () { - testWidgets('fills its parent in a Stack and paints', (tester) async { + for (final effect in _ambient) { + testWidgets('${effect.name} has no travel for it to drive', (tester) async { await tester.pumpWidget( _host( - const Stack( - children: [ - Center(child: Text('content')), - Positioned.fill(child: BorderBeam.overlay(borderRadius: 16)), - ], + BorderBeam( + effect: effect, + progress: 0.5, + child: const SizedBox.expand(), ), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - expect(find.text('content'), findsOneWidget); - expect(tester.getSize(find.byType(BorderBeam)), const Size(350, 140)); - expect(await _paintsPixels(tester, _painter(tester)), isTrue); - expect(tester.takeException(), isNull); + await _settle(tester); + final phases = _now(tester); + expect(phases.travelProgress, 0); + expect(phases.driven, isFalse); }); + } + + testWidgets('a reduced-motion static frame still reads the value', ( + tester, + ) async { + await tester.pumpWidget( + _host( + disableAnimations: true, + const BorderBeam( + effect: BeamEffect.rotate(), + progress: 0.6, + child: SizedBox.expand(), + ), + ), + ); + await tester.pump(const Duration(seconds: 1)); + final painter = _painter(tester); + expect(painter.staticMode, isTrue); + expect(tester.binding.transientCallbackCount, 0); - testWidgets('takes the same options as the generic constructor', ( - tester, - ) async { - await tester.pumpWidget( - _host( - const Stack( - children: [ - Positioned.fill( - child: BorderBeam.overlay( - variant: BeamVariant.line, - colors: BeamColors.ocean, - progress: 0.3, - ), + final phases = painter.resolver.staticFrame( + progress: painter.progress?.value, + ); + expect(phases.travelProgress, 0.6); + expect(phases.driven, isTrue); + expect(_headOffset(tester, 0.6), closeTo(0, 1e-6)); + }); + + testWidgets('BorderBeam.overlay takes it too', (tester) async { + await tester.pumpWidget( + _host( + const Stack( + children: [ + Positioned.fill( + child: BorderBeam.overlay( + effect: BeamEffect.line(), + progress: 0.3, ), - ], - ), + ), + ], ), - ); - final painter = _painter(tester); - expect(painter.config.variant, BeamVariant.line); - expect(painter.progress?.value, 0.3); - }); + ), + ); + await _settle(tester); + expect(tester.getSize(find.byType(BorderBeam)), const Size(350, 140)); + expect(_painter(tester).progress?.value, 0.3); + expect(_now(tester).travelProgress, 0.3); }); } diff --git a/test/widget/beam_research_features_test.dart b/test/widget/beam_research_features_test.dart deleted file mode 100644 index d03b5fa..0000000 --- a/test/widget/beam_research_features_test.dart +++ /dev/null @@ -1,665 +0,0 @@ -import 'dart:ui' as ui; - -import 'package:flutter/material.dart'; -import 'package:flutter/scheduler.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam/src/animation/beam_clock.dart'; -import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; -import 'package:flutter_test/flutter_test.dart'; - -/// The options ported from the reference implementations: the stock -/// pulse-outside look, the pulse-inside wash scale, the render-scale -/// magnification, and the three playback fields (offscreen pause, frozen -/// time, fade curve). -/// -/// The pixel assertions are deliberately coarse — presence, absence, and the -/// ordering of totals — so they pin behaviour without pinning the look, which -/// the goldens own. -void main() { - const beamSize = ui.Size(350, 140); - - // ─── BeamStyle.pulseOutsideStock ────────────────────────────────────────── - - group('BeamStyle.pulseOutsideStock', () { - test('rolls the demo tuning back through the hooks that carry it', () { - final config = _config( - BeamVariant.pulseOutside, - style: BeamStyle.pulseOutsideStock, - ); - // Stock tuning disables the demo-only behind-glow boost in the - // strategy, leaving the shared foreground/behind hook neutral. - expect(config.glowBoost, 1); - for (final factor in [ - config.strokeOpacityFactor, - config.innerOpacityFactor, - config.bloomOpacityFactor, - ]) { - expect(factor * 1.71, closeTo(1, 1e-12)); - } - expect(config.glowBrightness, 1.3, reason: 'the untuned preset'); - expect(config.glowSaturation, 1.2); - expect(config.pulseOutsideTuning, BeamPulseOutsideTuning.stock); - }); - - test('leaves the blur overrides free for the caller', () { - // The stock blurs differ by brightness (3/6 core, 22.5/15 bloom), which - // one const double cannot say — the tuning flag carries them, and the - // hooks stay null so a caller can still override either. - expect(BeamStyle.pulseOutsideStock.coreBlur, isNull); - expect(BeamStyle.pulseOutsideStock.bloomBlur, isNull); - }); - - for (final brightness in ui.Brightness.values) { - test('$brightness: paints a dimmer glow than the demo recipe', () async { - // The behind-child pass is the whole outward glow; give it room. - const canvas = ui.Size(750, 540); - const origin = ui.Offset(200, 200); - Future<_Pixels> render(BeamStyle style) => _paint( - _config( - BeamVariant.pulseOutside, - style: style, - brightness: brightness, - ), - size: beamSize, - canvas: canvas, - origin: origin, - behind: true, - ); - final demo = await render(const BeamStyle()); - final stock = await render(BeamStyle.pulseOutsideStock); - final all = ui.Offset.zero & canvas; - final stockAlpha = stock.totalAlpha(all); - expect(stockAlpha, greaterThan(0), reason: 'it still glows'); - expect( - stockAlpha, - lessThan(demo.totalAlpha(all)), - reason: 'the demo recipe multiplies every glow layer by 1.71', - ); - }); - - test('$brightness: the tuning flag alone moves the geometry', () async { - // Same opacities on both sides, so only the insets, the blurs, and - // the size unit can account for the difference. - Future<_Pixels> render(BeamPulseOutsideTuning tuning) => _paint( - _config( - BeamVariant.pulseOutside, - style: BeamStyle(pulseOutsideTuning: tuning), - brightness: brightness, - ), - size: beamSize, - canvas: const ui.Size(750, 540), - origin: const ui.Offset(200, 200), - behind: true, - ); - final demo = await render(BeamPulseOutsideTuning.demo); - final stock = await render(BeamPulseOutsideTuning.stock); - expect(stock.bytes, isNot(demo.bytes)); - }); - } - - test('is a value, and layering keeps the stock geometry', () { - expect(BeamStyle.pulseOutsideStock, BeamStyle.pulseOutsideStock); - final louder = BeamStyle.pulseOutsideStock.copyWith(glowBoost: 1.4); - expect(louder.glowBoost, 1.4); - expect(louder.pulseOutsideTuning, BeamPulseOutsideTuning.stock); - expect( - louder.strokeOpacityFactor, - BeamStyle.pulseOutsideStock.strokeOpacityFactor, - ); - }); - }); - - // ─── BeamStyle.innerSizeScale ───────────────────────────────────────────── - - group('innerSizeScale', () { - test('1 paints exactly what leaving it unset paints', () async { - final bare = await _paint(_config(BeamVariant.pulseInside)); - final one = await _paint( - _config( - BeamVariant.pulseInside, - style: const BeamStyle(innerSizeScale: 1), - ), - ); - expect(one.bytes, bare.bytes); - }); - - test('below 1 pulls the inner wash tighter to the border', () async { - final rect = ui.Offset.zero & beamSize; - // The inner wash is the only layer that moves, so read it alone. - Future innerAlpha(double scale) async { - final pixels = await _paint( - _config( - BeamVariant.pulseInside, - style: BeamStyle( - innerSizeScale: scale, - // Silence the ring and the bloom: their geometry is fixed. - strokeOpacityFactor: 0, - bloomOpacityFactor: 0, - ), - ), - ); - return pixels.totalAlpha(rect); - } - - final full = await innerAlpha(1); - final tight = await innerAlpha(0.6); - expect(tight, greaterThan(0), reason: 'the wash is still painted'); - expect(tight, lessThan(full * 0.9)); - }); - - test('only the pulse-inside variant reads it', () async { - for (final variant in BeamVariant.values) { - if (variant == BeamVariant.pulseInside) continue; - final bare = await _paint(_config(variant)); - final scaled = await _paint( - _config(variant, style: const BeamStyle(innerSizeScale: 0.4)), - ); - expect(scaled.bytes, bare.bytes, reason: '$variant'); - } - }); - }); - - // ─── BeamStyle.renderScale ──────────────────────────────────────────────── - - group('renderScale', () { - test('resolves clamped to 0.25-1', () { - double resolved(double value) => _config( - BeamVariant.rotate, - style: BeamStyle(renderScale: value), - ).renderScale; - expect(resolved(0.1), 0.25); - expect(resolved(4), 1); - expect(resolved(0.5), 0.5); - expect(_config(BeamVariant.rotate).renderScale, 1); - }); - - test('scaledBy moves the box-relative lengths and nothing else', () { - final base = _config( - BeamVariant.rotate, - shape: const BeamShape( - radius: BorderRadius.all(Radius.circular(24)), - borderWidth: 2, - ringOffset: 6, - ), - ); - final half = base.scaledBy(0.5); - expect(half.borderRadius, BorderRadius.circular(12)); - expect(half.borderWidth, 1); - expect(half.ringOffset, 3); - expect(half.renderScale, 1, reason: 'the copy has spent the scale'); - expect(half.palette, base.palette); - expect(half.cycleSeconds, base.cycleSeconds); - }); - - testWidgets('1 paints exactly what leaving it unset paints', ( - tester, - ) async { - final bare = await _paintThroughPainter( - tester, - _config(BeamVariant.rotate), - ); - final one = await _paintThroughPainter( - tester, - _config(BeamVariant.rotate, style: const BeamStyle(renderScale: 1)), - ); - expect(one.bytes, bare.bytes); - }); - - testWidgets('below 1 repaints the same box differently', (tester) async { - const large = ui.Size(700, 280); - final full = await _paintThroughPainter( - tester, - _config(BeamVariant.rotate), - size: large, - ); - final scaled = await _paintThroughPainter( - tester, - _config(BeamVariant.rotate, style: const BeamStyle(renderScale: 0.5)), - size: large, - ); - expect(scaled.bytes, isNot(full.bytes)); - expect(scaled.totalAlpha(ui.Offset.zero & large), greaterThan(0)); - }); - - testWidgets('the magnified beam still lands on the box bounds', ( - tester, - ) async { - // The transform is the part that can silently go wrong: scaling about - // anything but the origin slides the whole beam off its box. The - // pulse-inside wash hugs all four edges, so a shifted beam loses one. - const large = ui.Size(700, 280); - final pixels = await _paintThroughPainter( - tester, - _config( - BeamVariant.pulseInside, - style: const BeamStyle(renderScale: 0.5), - ), - size: large, - ); - const probe = 8.0; - final edges = { - 'top': ui.Rect.fromLTWH(0, 0, large.width, probe), - 'bottom': ui.Rect.fromLTWH(0, large.height - probe, large.width, probe), - 'left': ui.Rect.fromLTWH(0, 0, probe, large.height), - 'right': ui.Rect.fromLTWH(large.width - probe, 0, probe, large.height), - }; - for (final MapEntry(key: name, value: band) in edges.entries) { - expect(pixels.totalAlpha(band), greaterThan(0), reason: name); - } - }); - }); - - // ─── BeamPlayback.debugFrozenAt ─────────────────────────────────────────── - - group('debugFrozenAt', () { - testWidgets('never starts the clock', (tester) async { - await tester.pumpWidget( - _app( - const BorderBeam.rotate( - playback: BeamPlayback(debugFrozenAt: Duration(seconds: 2)), - child: SizedBox.expand(), - ), - ), - ); - await tester.pump(const Duration(seconds: 1)); - final painter = _painterOf(tester); - expect(painter.frozenAt, const Duration(seconds: 2)); - expect(painter.clock.isRunning, isFalse); - expect(painter.clock.elapsedSeconds, 0); - expect(tester.binding.transientCallbackCount, 0); - }); - - testWidgets('two frames a wall-clock apart paint the same pixels', ( - tester, - ) async { - await tester.pumpWidget( - _app( - const BorderBeam.rotate( - playback: BeamPlayback(debugFrozenAt: Duration(milliseconds: 1300)), - child: SizedBox.expand(), - ), - ), - ); - final first = await _recordIn(tester, _painterOf(tester), beamSize); - await tester.pump(const Duration(seconds: 4)); - await tester.pump(const Duration(seconds: 7)); - final later = await _recordIn(tester, _painterOf(tester), beamSize); - expect(later.bytes, first.bytes); - expect(first.totalAlpha(ui.Offset.zero & beamSize), greaterThan(0)); - }); - - testWidgets('paints the frame the timeline holds at that instant', ( - tester, - ) async { - const at = Duration(milliseconds: 1300); - final config = _config(BeamVariant.rotate); - late _Pixels expected; - late _Pixels actual; - await tester.runAsync(() async { - expected = await _paint(config, t: 1.3); - final clock = BeamClock(createTicker: Ticker.new); - final painter = BeamPainter( - clock: clock, - config: config, - resolver: BeamPhaseResolver(config), - strategy: strategyFor(config.variant), - behind: false, - staticMode: false, - frozenAt: at, - ); - actual = await _record(painter, beamSize); - clock.dispose(); - }); - expect(actual.bytes, expected.bytes); - }); - }); - - // ─── BeamPlayback.fadeCurve ─────────────────────────────────────────────── - - group('fadeCurve', () { - test('cssEase is the web ease', () { - expect(BeamPlayback.cssEase, const Cubic(0.25, 0.1, 0.25, 1)); - }); - - testWidgets('a curve replaces the spring on the fade-in', (tester) async { - final clock = BeamClock( - createTicker: tester.createTicker, - fadeCurve: BeamPlayback.cssEase, - )..activate(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - expect( - clock.fadeOpacity, - closeTo(BeamPlayback.cssEase.transform(0.5), 1e-9), - ); - clock.dispose(); - }); - - testWidgets('and on the fade-out', (tester) async { - final clock = BeamClock( - createTicker: tester.createTicker, - fadeCurve: BeamPlayback.cssEase, - )..activate(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - expect(clock.fadeOpacity, 1); - clock.deactivate(); - await tester.pump(const Duration(milliseconds: 250)); - expect( - clock.fadeOpacity, - closeTo(1 - BeamPlayback.cssEase.transform(0.5), 1e-9), - ); - clock.dispose(); - }); - - testWidgets('the default fade is the spring, not the ease', (tester) async { - final clock = BeamClock(createTicker: tester.createTicker)..activate(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - final spring = clock.fadeOpacity; - clock.dispose(); - expect(spring, isNot(closeTo(BeamPlayback.cssEase.transform(0.5), 1e-3))); - expect(spring, greaterThan(0)); - expect(spring, lessThanOrEqualTo(1)); - }); - - testWidgets('the widget hands its curve to the clock', (tester) async { - await tester.pumpWidget( - _app( - const BorderBeam.rotate( - playback: BeamPlayback(fadeCurve: BeamPlayback.cssEase), - child: SizedBox.expand(), - ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - expect( - _painterOf(tester).clock.fadeOpacity, - closeTo(BeamPlayback.cssEase.transform(0.5), 1e-9), - ); - }); - }); - - // ─── BeamPlayback.pauseWhenOffscreen ────────────────────────────────────── - - group('pauseWhenOffscreen', () { - // cacheExtent keeps rows built well past the 256px margin, so there is - // something offscreen left to pause. The double form is the one every - // supported Flutter accepts (ScrollCacheExtent arrives after 3.35). - Widget list({bool? pause}) => _app( - ListView.builder( - // ignore: deprecated_member_use - cacheExtent: 4000, - itemCount: 12, - itemBuilder: (context, index) => SizedBox( - height: 200, - child: BorderBeam.rotate( - key: ValueKey(index), - playback: BeamPlayback(pauseWhenOffscreen: pause), - child: const SizedBox.expand(), - ), - ), - ), - size: const Size(400, 600), - ); - - testWidgets('offscreen rows stop ticking, and start again on return', ( - tester, - ) async { - await tester.pumpWidget(list()); - await tester.pump(); - expect(_clockAt(tester, 0).isRunning, isTrue, reason: 'in view'); - expect(_clockAt(tester, 1).isRunning, isTrue, reason: 'in view'); - expect( - _clockAt(tester, 2).isRunning, - isTrue, - reason: 'inside the 256px margin', - ); - expect(_clockAt(tester, 6).isRunning, isFalse, reason: 'far below'); - expect(_clockAt(tester, 11).isRunning, isFalse); - - // A paused beam keeps its play state and its timeline. - final resting = _clockAt(tester, 6); - expect(resting.isVisible, isTrue); - final held = resting.elapsedSeconds; - - // Not pumpAndSettle: a running beam schedules frames forever, so the - // tree never settles. Two frames are enough — one to land the scroll, - // one to run the post-frame visibility check. - await tester.drag(find.byType(ListView), const Offset(0, -1200)); - await tester.pump(); - await tester.pump(); - - expect(_clockAt(tester, 6).isRunning, isTrue, reason: 'scrolled in'); - expect( - _clockAt(tester, 6).elapsedSeconds, - greaterThanOrEqualTo(held), - reason: 'it resumes rather than restarting', - ); - expect(_clockAt(tester, 0).isRunning, isFalse, reason: 'now far above'); - }); - - testWidgets('false keeps every row running', (tester) async { - await tester.pumpWidget(list(pause: false)); - await tester.pump(); - for (final index in [0, 6, 11]) { - expect(_clockAt(tester, index).isRunning, isTrue, reason: '$index'); - } - }); - - testWidgets('offscreen time does not consume a duration budget', ( - tester, - ) async { - await tester.pumpWidget( - _app( - ListView.builder( - // ignore: deprecated_member_use - cacheExtent: 4000, - itemCount: 12, - itemBuilder: (context, index) => index == 6 - ? SizedBox( - key: const ValueKey(6), - height: 200, - child: const BorderBeam.rotate( - playback: BeamPlayback(duration: Duration(seconds: 1)), - child: SizedBox.expand(), - ), - ) - : const SizedBox(height: 200), - ), - size: const Size(400, 600), - ), - ); - await tester.pump(); - final clock = _clockAt(tester, 6); - expect(clock.isRunning, isFalse, reason: 'the beam starts offscreen'); - - await tester.pump(const Duration(seconds: 2)); - expect(clock.isVisible, isTrue); - expect(clock.stage, isNot(BeamFadeStage.fadingOut)); - - await tester.drag(find.byType(ListView), const Offset(0, -1200)); - await tester.pump(); - await tester.pump(); - expect(clock.isRunning, isTrue); - await tester.pump(const Duration(milliseconds: 1100)); - expect(clock.stage, BeamFadeStage.fadingOut); - }); - - testWidgets('a beam outside any scrollable is never paused', ( - tester, - ) async { - await tester.pumpWidget( - _app(const BorderBeam.rotate(child: SizedBox.expand())), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - expect(_painterOf(tester).clock.isRunning, isTrue); - }); - - testWidgets('an offscreen beam disposes without leaking its ticker', ( - tester, - ) async { - await tester.pumpWidget(list()); - await tester.pump(); - expect(_clockAt(tester, 11).isRunning, isFalse); - await tester.pumpWidget(_app(const SizedBox.expand())); - await tester.pump(); - expect(tester.binding.transientCallbackCount, 0); - }); - }); -} - -// ─── Harness ──────────────────────────────────────────────────────────────── - -Widget _app(Widget child, {Size size = const Size(350, 140)}) => MaterialApp( - debugShowCheckedModeBanner: false, - home: Center( - child: SizedBox(width: size.width, height: size.height, child: child), - ), -); - -BeamPainter _painterOf(WidgetTester tester) => tester - .widgetList(find.byType(CustomPaint)) - .map((paint) => paint.foregroundPainter) - .whereType() - .first; - -/// The clock of the beam keyed [index]. -/// -/// `skipOffstage: false`: a row parked in the scrollable's cache extent is -/// laid out but never painted, and it is exactly the row this feature is -/// about — the default finders would skip it. -BeamClock _clockAt(WidgetTester tester, int index) => tester - .widgetList( - find.descendant( - of: find.byKey(ValueKey(index), skipOffstage: false), - matching: find.byType(CustomPaint, skipOffstage: false), - ), - ) - .map((paint) => paint.foregroundPainter) - .whereType() - .first - .clock; - -BeamConfig _config( - BeamVariant variant, { - BeamStyle style = const BeamStyle(), - BeamShape shape = const BeamShape(), - ui.Brightness brightness = ui.Brightness.dark, -}) => BeamConfig.resolve( - variant: variant, - palette: (style.colors ?? BeamColors.colorful).resolve(), - brightness: brightness, - style: style, - shape: shape, -); - -/// Renders one strategy frame of [config] and returns its pixels. -Future<_Pixels> _paint( - BeamConfig config, { - double t = 0.9, - ui.Size size = const ui.Size(350, 140), - ui.Size? canvas, - ui.Offset origin = ui.Offset.zero, - bool behind = false, -}) async { - final target = canvas ?? size; - final recorder = ui.PictureRecorder(); - final c = ui.Canvas(recorder); - c.translate(origin.dx, origin.dy); - final frame = BeamPhaseResolver(config).sample(t, 1); - final strategy = strategyFor(config.variant); - if (behind) { - strategy.paintBehind(c, size, config, frame); - } else { - strategy.paintAbove(c, size, config, frame); - } - return _rasterize(recorder, target); -} - -/// Renders one frame through a [BeamPainter], which is where `renderScale` -/// lives — a strategy never sees it. -Future<_Pixels> _paintThroughPainter( - WidgetTester tester, - BeamConfig config, { - ui.Size size = const ui.Size(350, 140), - Duration at = const Duration(milliseconds: 900), -}) async { - late _Pixels pixels; - await tester.runAsync(() async { - final clock = BeamClock(createTicker: Ticker.new); - final painter = BeamPainter( - clock: clock, - config: config, - resolver: BeamPhaseResolver(config), - strategy: strategyFor(config.variant), - behind: false, - staticMode: false, - frozenAt: at, - ); - pixels = await _record(painter, size); - clock.dispose(); - }); - return pixels; -} - -/// [_record], run on the real event loop: `toImage` never completes under a -/// widget test's fake async. -Future<_Pixels> _recordIn( - WidgetTester tester, - BeamPainter painter, - ui.Size size, -) async { - late _Pixels pixels; - await tester.runAsync(() async { - pixels = await _record(painter, size); - }); - return pixels; -} - -Future<_Pixels> _record(BeamPainter painter, ui.Size size) async { - final recorder = ui.PictureRecorder(); - painter.paint(ui.Canvas(recorder), size); - return _rasterize(recorder, size); -} - -Future<_Pixels> _rasterize(ui.PictureRecorder recorder, ui.Size size) async { - final image = await recorder.endRecording().toImage( - size.width.toInt(), - size.height.toInt(), - ); - final bytes = await image.toByteData(format: ui.ImageByteFormat.rawRgba); - final width = image.width; - final height = image.height; - image.dispose(); - return _Pixels(bytes!.buffer.asUint8List(), width, height); -} - -/// The alpha channel of a rendered frame. -class _Pixels { - _Pixels(this.bytes, this.width, this.height); - - final List bytes; - final int width; - final int height; - - double _alphaAt(int x, int y) { - if (x < 0 || y < 0 || x >= width || y >= height) return 0; - return bytes[(y * width + x) * 4 + 3] / 255; - } - - /// Total alpha inside [rect], in whole-pixel units. - double totalAlpha(ui.Rect rect) { - var sum = 0.0; - for (var y = rect.top.round(); y < rect.bottom.round(); y++) { - for (var x = rect.left.round(); x < rect.right.round(); x++) { - sum += _alphaAt(x, y); - } - } - return sum; - } -} diff --git a/test/widget/beam_shape_test.dart b/test/widget/beam_shape_test.dart index 3498f25..4fc1d58 100644 --- a/test/widget/beam_shape_test.dart +++ b/test/widget/beam_shape_test.dart @@ -1,62 +1,57 @@ -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -Widget _host(Widget child, {TextDirection? textDirection}) => MaterialApp( - theme: ThemeData(brightness: Brightness.dark), - home: Scaffold( - body: Center( - child: SizedBox( - width: 350, - height: 140, - child: textDirection == null - ? child - : Directionality(textDirection: textDirection, child: child), - ), - ), - ), -); - -BeamConfig _config(WidgetTester tester) => tester - .widgetList( - find.descendant( - of: find.byType(BorderBeam), - matching: find.byType(CustomPaint), - ), - ) - .expand((paint) => [paint.painter, paint.foregroundPainter]) - .whereType() - .first - .config; +import 'test_utils.dart'; + +BeamConfig _config(WidgetTester tester) => beamPainterOf(tester).config; /// How `BeamShape` reaches `BeamConfig`: inherited from a `BorderBeamTheme`, -/// overridden field by field on the widget, short-circuited by the -/// `borderRadius:` shorthand, and — for a directional radius — resolved -/// against the ambient `Directionality`. +/// overridden field by field on the widget, and — for a directional radius — +/// resolved against the ambient `Directionality`. (The `borderRadius:` +/// shorthand is covered in `beam_shorthand_test.dart`.) void main() { group('inheritance', () { + testWidgets('a bare beam falls through to the shape defaults', ( + tester, + ) async { + for (final effect in BeamEffect.values) { + await tester.pumpWidget( + beamHost(BorderBeam(effect: effect, child: const SizedBox.expand())), + ); + final config = _config(tester); + expect( + config.borderRadius, + const BeamShape().resolveRadius(TextDirection.ltr), + reason: effect.name, + ); + expect(config.superellipse, isFalse, reason: effect.name); + expect(config.segment, isNull, reason: effect.name); + expect(config.dashes, 0, reason: effect.name); + } + }); + testWidgets('a theme borderWidth and superellipse reach the config', ( tester, ) async { await tester.pumpWidget( - _host( + beamHost( const BorderBeamTheme( data: BorderBeamThemeData( shape: BeamShape(borderWidth: 4, superellipse: true), ), - child: BorderBeam.rotate(child: SizedBox.expand()), + child: BorderBeam(child: SizedBox.expand()), ), ), ); final config = _config(tester); expect(config.borderWidth, 4); - expect(config.useSuperellipse, isTrue); + expect(config.superellipse, isTrue); expect( config.borderRadius, - BorderRadius.circular(16), - reason: 'the radius still falls through to the rotate preset', + const BeamShape().resolveRadius(TextDirection.ltr), + reason: 'the radius still falls through to the default', ); }); @@ -64,12 +59,12 @@ void main() { tester, ) async { await tester.pumpWidget( - _host( + beamHost( const BorderBeamTheme( data: BorderBeamThemeData( shape: BeamShape(superellipse: true, borderWidth: 4), ), - child: BorderBeam.rotate( + child: BorderBeam( shape: BeamShape(superellipse: false), child: SizedBox.expand(), ), @@ -77,91 +72,115 @@ void main() { ), ); final config = _config(tester); - expect(config.useSuperellipse, isFalse, reason: 'false is a value'); + expect(config.superellipse, isFalse, reason: 'false is a value'); expect(config.borderWidth, 4, reason: 'the field it did not set'); }); - testWidgets('each variant keeps its own default radius and width', ( + testWidgets('ring offset, segment, and dashes reach the config', ( tester, ) async { - for (final variant in BeamVariant.values) { - await tester.pumpWidget( - _host(BorderBeam(variant: variant, child: const SizedBox.expand())), - ); - final config = _config(tester); - expect( - config.borderRadius, - BorderRadius.circular(variant == BeamVariant.small ? 32 : 16), - reason: '$variant', - ); - expect(config.borderWidth, 1, reason: '$variant'); - expect(config.useSuperellipse, isFalse, reason: '$variant'); - } + await tester.pumpWidget( + beamHost( + const BorderBeamTheme( + data: BorderBeamThemeData( + shape: BeamShape(ringOffset: 6, segment: BeamSegment.topHalf), + ), + child: BorderBeam( + shape: BeamShape(dashes: 8, segment: BeamSegment.bottomHalf), + child: SizedBox.expand(), + ), + ), + ), + ); + final config = _config(tester); + expect(config.ringOffset, 6); + expect(config.segment, BeamSegment.bottomHalf); + expect(config.dashes, 8); }); }); - group('borderRadius shorthand', () { - testWidgets('beats shape.radius on the same widget', (tester) async { + group('radius', () { + testWidgets('BeamShape.all and BeamShape.circular resolve alike', ( + tester, + ) async { await tester.pumpWidget( - _host( - BorderBeam.rotate( - borderRadius: 8, - shape: BeamShape(radius: BorderRadius.circular(40)), + beamHost( + const BorderBeam(shape: BeamShape.all(24), child: SizedBox.expand()), + ), + ); + final all = _config(tester); + await tester.pumpWidget( + beamHost( + BorderBeam( + shape: BeamShape.circular(24), child: const SizedBox.expand(), ), ), ); - expect(_config(tester).borderRadius, BorderRadius.circular(8)); + expect( + identical(_config(tester), all), + isTrue, + reason: 'equal shapes: the cached config is reused', + ); + expect(all.borderRadius, BorderRadius.circular(24)); }); - testWidgets('beats a theme radius', (tester) async { + testWidgets('per-corner radii reach the config', (tester) async { + const radius = BorderRadius.only( + topLeft: Radius.circular(4), + topRight: Radius.circular(12), + bottomRight: Radius.elliptical(20, 10), + ); await tester.pumpWidget( - _host( - BorderBeamTheme( - data: BorderBeamThemeData( - shape: BeamShape(radius: BorderRadius.circular(40)), - ), - child: const BorderBeam.rotate( - borderRadius: 8, - child: SizedBox.expand(), - ), + beamHost( + const BorderBeam( + shape: BeamShape(radius: radius), + child: SizedBox.expand(), ), ), ); - expect(_config(tester).borderRadius, BorderRadius.circular(8)); + expect(_config(tester).borderRadius, radius); }); - testWidgets('leaves the other shape fields alone', (tester) async { + testWidgets('a stadium reaches the config as an infinite radius', ( + tester, + ) async { await tester.pumpWidget( - _host( - const BorderBeam.rotate( - borderRadius: 8, - shape: BeamShape(borderWidth: 6, superellipse: true), + beamHost( + const BorderBeam( + shape: BeamShape.stadium(), child: SizedBox.expand(), ), ), ); - final config = _config(tester); - expect(config.borderRadius, BorderRadius.circular(8)); - expect(config.borderWidth, 6); - expect(config.useSuperellipse, isTrue); + expect( + _config(tester).borderRadius, + const BorderRadius.all(Radius.circular(double.infinity)), + reason: 'the outline, not the config, clamps it to the box', + ); + expect(tester.takeException(), isNull); }); - testWidgets('a stadium shape survives to the config as an infinite ' - 'radius', (tester) async { + testWidgets('a stadium from a theme survives a widget radius-free shape', ( + tester, + ) async { await tester.pumpWidget( - _host( - const BorderBeam.rotate( - shape: BeamShape.stadium(), - child: SizedBox.expand(), + beamHost( + const BorderBeamTheme( + data: BorderBeamThemeData(shape: BeamShape.stadium()), + child: BorderBeam( + shape: BeamShape(borderWidth: 2), + child: SizedBox.expand(), + ), ), ), ); + final config = _config(tester); expect( - _config(tester).borderRadius, + config.borderRadius, const BorderRadius.all(Radius.circular(double.infinity)), - reason: 'the ring geometry, not the config, clamps it to the box', ); + expect(config.borderWidth, 2); }); }); @@ -170,9 +189,9 @@ void main() { topStart: Radius.circular(20), ); - Widget beam(TextDirection direction) => _host( + Widget beam(TextDirection direction) => beamHost( textDirection: direction, - const BorderBeam.rotate( + const BorderBeam( shape: BeamShape(radius: directional), child: SizedBox.expand(), ), @@ -185,6 +204,8 @@ void main() { final radius = _config(tester).borderRadius; expect(radius.topLeft, const Radius.circular(20)); expect(radius.topRight, Radius.zero); + expect(radius.bottomLeft, Radius.zero); + expect(radius.bottomRight, Radius.zero); }); testWidgets('topStart resolves to the top-right corner in RTL', ( @@ -215,17 +236,32 @@ void main() { expect(back.borderRadius, ltr.borderRadius); }); + testWidgets('a directional radius from a theme resolves at the beam', ( + tester, + ) async { + await tester.pumpWidget( + beamHost( + textDirection: TextDirection.rtl, + const BorderBeamTheme( + data: BorderBeamThemeData(shape: BeamShape(radius: directional)), + child: BorderBeam(child: SizedBox.expand()), + ), + ), + ); + expect(_config(tester).borderRadius.topRight, const Radius.circular(20)); + }); + testWidgets('a non-directional radius is unaffected by RTL', ( tester, ) async { await tester.pumpWidget( - _host( + beamHost( textDirection: TextDirection.rtl, - BorderBeam.rotate( + const BorderBeam( shape: BeamShape( - radius: const BorderRadius.only(topLeft: Radius.circular(20)), + radius: BorderRadius.only(topLeft: Radius.circular(20)), ), - child: const SizedBox.expand(), + child: SizedBox.expand(), ), ), ); diff --git a/test/widget/beam_shorthand_test.dart b/test/widget/beam_shorthand_test.dart index 0e2fb5a..3ff4795 100644 --- a/test/widget/beam_shorthand_test.dart +++ b/test/widget/beam_shorthand_test.dart @@ -1,61 +1,39 @@ -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -Widget _host(Widget child) => MaterialApp( - theme: ThemeData(brightness: Brightness.dark), - home: Scaffold( - body: Center(child: SizedBox(width: 350, height: 140, child: child)), - ), -); +import 'test_utils.dart'; -BeamPainter _painter(WidgetTester tester) => tester - .widgetList( - find.descendant( - of: find.byType(BorderBeam), - matching: find.byType(CustomPaint), - ), - ) - .expand((paint) => [paint.painter, paint.foregroundPainter]) - .whereType() - .first; - -/// The three shorthands (`colors`, `active`, `borderRadius`) are the top of -/// the resolution order: they beat the value object they abbreviate on the -/// same widget, and everything a `BorderBeamTheme` supplies. The generic -/// `BorderBeam(variant:)` constructor must build exactly what the matching -/// named constructor does. -/// -/// The `borderRadius` shorthand is covered in `beam_shape_test.dart`, next -/// to the rest of the shape resolution. +/// The three shorthands (`colors`, `active`, `borderRadius`) sit at the top +/// of the resolution order: they beat the value-object field they abbreviate +/// on the same widget, and everything a `BorderBeamTheme` supplies — and they +/// leave every other field of that value object alone. void main() { - group('colors shorthand', () { + group('colors', () { testWidgets('beats style.colors on the same widget', (tester) async { await tester.pumpWidget( - _host( - const BorderBeam.rotate( + beamHost( + const BorderBeam( colors: BeamColors.sunset, - style: BeamStyle(colors: BeamColors.ocean, strength: 0.3), + style: BeamStyle(colors: BeamColors.ocean, strength: 0.3, glow: 2), child: SizedBox.expand(), ), ), ); - final config = _painter(tester).config; - expect(identical(config.palette, BeamColors.sunset.resolve()), isTrue); + final config = beamPainterOf(tester).config; + expect(config.palette, BeamColors.sunset.resolve()); expect(config.strength, 0.3, reason: 'the rest of the style survives'); + expect(config.glow, 2); }); - testWidgets('beats a theme colors and the widget style together', ( - tester, - ) async { + testWidgets('beats a theme and the widget style together', (tester) async { await tester.pumpWidget( - _host( + beamHost( const BorderBeamTheme( data: BorderBeamThemeData( - style: BeamStyle(colors: BeamColors.ocean), + style: BeamStyle(colors: BeamColors.ocean, hueBase: 40), ), - child: BorderBeam.rotate( + child: BorderBeam( colors: BeamColors.sunset, style: BeamStyle(colors: BeamColors.mono), child: SizedBox.expand(), @@ -63,38 +41,46 @@ void main() { ), ), ); - final config = _painter(tester).config; - expect(identical(config.palette, BeamColors.sunset.resolve()), isTrue); + final config = beamPainterOf(tester).config; + expect(config.palette, BeamColors.sunset.resolve()); expect( - config.staticColors, - isFalse, - reason: 'the mono palette never took effect', + config.hueMode, + isNot(BeamHueMode.none), + reason: 'the fixed-hue mono palette never took effect', ); + expect(config.hueBase, 40, reason: 'the theme fills the rest'); }); - testWidgets('a null shorthand leaves style.colors in charge', ( + testWidgets('a null shorthand leaves style.colors in control', ( tester, ) async { await tester.pumpWidget( - _host( - const BorderBeam.rotate( + beamHost( + const BorderBeam( style: BeamStyle(colors: BeamColors.ocean), child: SizedBox.expand(), ), ), ); - expect( - identical(_painter(tester).config.palette, BeamColors.ocean.resolve()), - isTrue, + expect(beamPainterOf(tester).config.palette, BeamColors.ocean.resolve()); + }); + + testWidgets('a custom palette passes through', (tester) async { + const custom = BeamColors([Color(0xFFFF0000), Color(0xFF0000FF)]); + await tester.pumpWidget( + beamHost(const BorderBeam(colors: custom, child: SizedBox.expand())), ); + final palette = beamPainterOf(tester).config.palette; + expect(palette, custom.resolve()); + expect(palette.colors, hasLength(2)); }); }); - group('active shorthand', () { - testWidgets('beats playback.active on the same widget', (tester) async { + group('active', () { + testWidgets('true beats playback.active: false', (tester) async { await tester.pumpWidget( - _host( - const BorderBeam.rotate( + beamHost( + const BorderBeam( active: true, playback: BeamPlayback(active: false), child: SizedBox.expand(), @@ -103,16 +89,14 @@ void main() { ); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); - expect(_painter(tester).clock.isVisible, isTrue); - expect(tester.binding.hasScheduledFrame, isTrue); + expect(beamPainterOf(tester).clock.isVisible, isTrue); + expect(tester.binding.transientCallbackCount, 1); }); - testWidgets('active: false wins over playback.active: true', ( - tester, - ) async { + testWidgets('false beats playback.active: true', (tester) async { await tester.pumpWidget( - _host( - const BorderBeam.rotate( + beamHost( + const BorderBeam( active: false, playback: BeamPlayback(active: true), child: SizedBox.expand(), @@ -120,45 +104,45 @@ void main() { ), ); await tester.pump(const Duration(seconds: 1)); - expect(_painter(tester).clock.isVisible, isFalse); - expect(tester.binding.hasScheduledFrame, isFalse); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + expect(tester.binding.transientCallbackCount, 0); }); testWidgets('beats a theme playback', (tester) async { await tester.pumpWidget( - _host( + beamHost( const BorderBeamTheme( data: BorderBeamThemeData(playback: BeamPlayback(active: false)), - child: BorderBeam.rotate(active: true, child: SizedBox.expand()), + child: BorderBeam(active: true, child: SizedBox.expand()), ), ), ); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); - expect(_painter(tester).clock.isVisible, isTrue); + expect(beamPainterOf(tester).clock.isVisible, isTrue); }); testWidgets('a theme active: false keeps a plain beam idle', ( tester, ) async { await tester.pumpWidget( - _host( + beamHost( const BorderBeamTheme( data: BorderBeamThemeData(playback: BeamPlayback(active: false)), - child: BorderBeam.rotate(child: SizedBox.expand()), + child: BorderBeam(child: SizedBox.expand()), ), ), ); await tester.pump(const Duration(seconds: 1)); - expect(_painter(tester).clock.isVisible, isFalse); - expect(tester.binding.hasScheduledFrame, isFalse); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('the shorthand keeps the rest of the playback', (tester) async { + testWidgets('keeps the rest of the playback', (tester) async { var deactivated = 0; await tester.pumpWidget( - _host( - BorderBeam.rotate( + beamHost( + BorderBeam( active: true, playback: const BeamPlayback( active: false, @@ -176,83 +160,81 @@ void main() { }); }); - group('the generic constructor', () { - Widget named(BeamVariant variant) => switch (variant) { - BeamVariant.rotate => const BorderBeam.rotate( - colors: BeamColors.ocean, - child: SizedBox.expand(), - ), - BeamVariant.small => const BorderBeam.small( - colors: BeamColors.ocean, - child: SizedBox.expand(), - ), - BeamVariant.line => const BorderBeam.line( - colors: BeamColors.ocean, - child: SizedBox.expand(), - ), - BeamVariant.pulseInside => const BorderBeam.pulseInside( - colors: BeamColors.ocean, - child: SizedBox.expand(), - ), - BeamVariant.pulseOutside => const BorderBeam.pulseOutside( - colors: BeamColors.ocean, - child: SizedBox.expand(), - ), - }; - - for (final variant in BeamVariant.values) { - testWidgets('$variant matches its named constructor', (tester) async { - await tester.pumpWidget( - _host( - BorderBeam( - variant: variant, - colors: BeamColors.ocean, - child: const SizedBox.expand(), - ), + group('borderRadius', () { + testWidgets('beats shape.radius on the same widget', (tester) async { + await tester.pumpWidget( + beamHost( + BorderBeam( + borderRadius: 8, + shape: BeamShape(radius: BorderRadius.circular(40)), + child: const SizedBox.expand(), ), - ); - final generic = _painter(tester); - expect(generic.config.variant, variant); - expect( - identical(generic.strategy, strategyFor(variant)), - isTrue, - reason: 'the strategy for $variant', - ); + ), + ); + expect( + beamPainterOf(tester).config.borderRadius, + BorderRadius.circular(8), + ); + }); - await tester.pumpWidget(_host(named(variant))); - final byName = _painter(tester); - expect(byName.config, generic.config); - expect(identical(byName.strategy, generic.strategy), isTrue); - expect(byName.behind, generic.behind); - }); - } + testWidgets('beats a theme radius', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeamTheme( + data: BorderBeamThemeData(shape: BeamShape.all(40)), + child: BorderBeam(borderRadius: 8, child: SizedBox.expand()), + ), + ), + ); + expect( + beamPainterOf(tester).config.borderRadius, + BorderRadius.circular(8), + ); + }); - testWidgets('pulseOutside is the only variant that paints behind', ( + testWidgets('beats a per-corner radius, not just a uniform one', ( tester, ) async { - for (final variant in BeamVariant.values) { - await tester.pumpWidget( - _host(BorderBeam(variant: variant, child: const SizedBox.expand())), - ); - final custom = tester.widget( - find - .descendant( - of: find.byType(BorderBeam), - matching: find.byType(CustomPaint), - ) - .first, - ); - expect( - custom.painter, - variant == BeamVariant.pulseOutside ? isA() : isNull, - reason: '$variant', - ); - expect( - custom.foregroundPainter, - isA(), - reason: '$variant', - ); - } + await tester.pumpWidget( + beamHost( + const BorderBeam( + borderRadius: 8, + shape: BeamShape( + radius: BorderRadiusDirectional.only( + topStart: Radius.circular(30), + ), + ), + child: SizedBox.expand(), + ), + ), + ); + expect( + beamPainterOf(tester).config.borderRadius, + BorderRadius.circular(8), + ); + }); + + testWidgets('leaves the other shape fields alone', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeam( + borderRadius: 8, + shape: BeamShape( + borderWidth: 6, + superellipse: true, + ringOffset: 4, + dashes: 6, + ), + child: SizedBox.expand(), + ), + ), + ); + final config = beamPainterOf(tester).config; + expect(config.borderRadius, BorderRadius.circular(8)); + expect(config.borderWidth, 6); + expect(config.superellipse, isTrue); + expect(config.ringOffset, 4); + expect(config.dashes, 6); }); }); } diff --git a/test/widget/beam_speed_test.dart b/test/widget/beam_speed_test.dart index 7ee5e12..14c09aa 100644 --- a/test/widget/beam_speed_test.dart +++ b/test/widget/beam_speed_test.dart @@ -1,11 +1,15 @@ -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_border_beam/src/animation/beam_clock.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; +import 'package:flutter_border_beam/src/render/beam_painter.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -Widget _host(Widget child) => MaterialApp( +Widget _host(Widget child, {bool disableAnimations = false}) => MaterialApp( theme: ThemeData(brightness: Brightness.dark), + builder: (context, app) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: disableAnimations), + child: app!, + ), home: Scaffold( body: Center(child: SizedBox(width: 350, height: 140, child: child)), ), @@ -24,179 +28,138 @@ BeamPainter _painter(WidgetTester tester) => tester BeamClock _clock(WidgetTester tester) => _painter(tester).clock; -/// `BeamTiming.speed` is the declarative playback rate: the beam's timeline -/// advances by `speed` seconds of animation per second of wall time. A -/// `BorderBeamController` owns the rate instead whenever one is attached. -void main() { - testWidgets('speed 2 advances the timeline at twice wall time', ( - tester, - ) async { - await tester.pumpWidget( - _host( - const BorderBeam.rotate( - timing: BeamTiming(speed: 2), - child: SizedBox.expand(), - ), - ), - ); - final clock = _clock(tester); - expect(clock.speed, 2); - // The first tick after Ticker.start reports elapsed 0. - await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); - expect(clock.elapsedSeconds, closeTo(1, 1e-9)); - await tester.pump(const Duration(milliseconds: 500)); - expect(clock.elapsedSeconds, closeTo(2, 1e-9)); - }); - - testWidgets('the default rate is real time', (tester) async { - await tester.pumpWidget( - _host(const BorderBeam.rotate(child: SizedBox.expand())), - ); - final clock = _clock(tester); - expect(clock.speed, 1); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); - expect(clock.elapsedSeconds, closeTo(0.5, 1e-9)); - }); - - testWidgets('changing speed on rebuild takes effect from the next frame', ( - tester, - ) async { - Widget build(double speed) => _host( - BorderBeam.rotate( - timing: BeamTiming(speed: speed), - child: const SizedBox.expand(), - ), - ); +double _travel(WidgetTester tester) { + final painter = _painter(tester); + return painter.resolver + .sample(painter.clock.elapsedSeconds, 1) + .travelProgress; +} - await tester.pumpWidget(build(2)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); - final clock = _clock(tester); - expect(clock.elapsedSeconds, closeTo(1, 1e-9)); - - await tester.pumpWidget(build(0.5)); - expect(clock.speed, 0.5); - expect( - clock.elapsedSeconds, - closeTo(1, 1e-9), - reason: 'a rate change does not move the timeline', - ); - await tester.pump(const Duration(seconds: 1)); - expect(clock.elapsedSeconds, closeTo(1.5, 1e-9)); - }); +/// The playback rate: `BeamTiming.speed`, a controller's `speed`, and a live +/// `speedListenable`, which win in reverse order; reduced motion's quarter +/// rate on top of whichever is in force; and a rate change riding through +/// without re-resolving the beam or moving its timeline. +void main() { + group('timing.speed', () { + testWidgets('the default rate is real time', (tester) async { + await tester.pumpWidget( + _host(const BorderBeam(child: SizedBox.expand())), + ); + final clock = _clock(tester); + expect(clock.speed, 1); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + expect(clock.elapsedSeconds, closeTo(0.5, 1e-9)); + }); - testWidgets('changing only the speed keeps the resolved config', ( - tester, - ) async { - Widget build(double speed) => _host( - BorderBeam.rotate( - timing: BeamTiming(speed: speed), - child: const SizedBox.expand(), - ), - ); + testWidgets('speed 2 advances the timeline at twice wall time', ( + tester, + ) async { + await tester.pumpWidget( + _host( + const BorderBeam( + timing: BeamTiming(speed: 2), + child: SizedBox.expand(), + ), + ), + ); + final clock = _clock(tester); + expect(clock.speed, 2); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + expect(clock.elapsedSeconds, closeTo(1, 1e-9)); + }); - await tester.pumpWidget(build(2)); - final before = _painter(tester); - await tester.pumpWidget(build(0.5)); - final after = _painter(tester); - expect( - identical(before.config, after.config), - isTrue, - reason: 'the rate is applied to the clock, not painted', - ); - expect(identical(before.resolver, after.resolver), isTrue); - }); + testWidgets('a rate change neither moves the timeline nor re-resolves', ( + tester, + ) async { + Widget build(double speed) => _host( + BorderBeam( + timing: BeamTiming(speed: speed), + child: const SizedBox.expand(), + ), + ); - testWidgets('changing the cycle does re-resolve the config', (tester) async { - Widget build(Duration cycle) => _host( - BorderBeam.rotate( - timing: BeamTiming(cycle: cycle), - child: const SizedBox.expand(), - ), - ); + await tester.pumpWidget(build(2)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + final before = _painter(tester); + final travel = _travel(tester); + expect(before.clock.elapsedSeconds, closeTo(1, 1e-9)); - await tester.pumpWidget(build(const Duration(seconds: 2))); - final before = _painter(tester); - await tester.pumpWidget(build(const Duration(seconds: 3))); - expect(identical(before.config, _painter(tester).config), isFalse); - }); + await tester.pumpWidget(build(0.5)); + final after = _painter(tester); + expect(after.clock.speed, 0.5); + expect(after.clock.elapsedSeconds, closeTo(1, 1e-9)); + expect(_travel(tester), closeTo(travel, 1e-9), reason: 'no snap'); + expect( + identical(before.config, after.config), + isTrue, + reason: 'the rate is applied to the clock, never painted', + ); + expect(identical(before.resolver, after.resolver), isTrue); - testWidgets('a BorderBeamTheme speed is inherited', (tester) async { - await tester.pumpWidget( - _host( - const BorderBeamTheme( - data: BorderBeamThemeData(timing: BeamTiming(speed: 3)), - child: BorderBeam.rotate(child: SizedBox.expand()), - ), - ), - ); - final clock = _clock(tester); - expect(clock.speed, 3); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); - expect(clock.elapsedSeconds, closeTo(0.6, 1e-9)); - }); + await tester.pump(const Duration(seconds: 1)); + expect(after.clock.elapsedSeconds, closeTo(1.5, 1e-9)); + }); - testWidgets('a widget speed beats an inherited one', (tester) async { - await tester.pumpWidget( - _host( - const BorderBeamTheme( - data: BorderBeamThemeData(timing: BeamTiming(speed: 3)), - child: BorderBeam.rotate( - timing: BeamTiming(speed: 0.25), - child: SizedBox.expand(), - ), + testWidgets('a BorderBeamTheme speed is inherited; the widget wins', ( + tester, + ) async { + Widget build(BeamTiming? timing) => _host( + BorderBeamTheme( + data: const BorderBeamThemeData(timing: BeamTiming(speed: 3)), + child: BorderBeam(timing: timing, child: const SizedBox.expand()), ), - ), - ); - expect(_clock(tester).speed, 0.25); - }); + ); - test('a non-positive speed asserts at the value-object boundary', () { - final zero = double.parse('0'); - expect( - () => BeamTiming(speed: zero), - throwsA( - isA().having( - (error) => error.message, - 'message', - contains('speed must be finite and positive'), - ), - ), - ); + await tester.pumpWidget(build(null)); + expect(_clock(tester).speed, 3); + await tester.pumpWidget(build(const BeamTiming(speed: 0.25))); + expect(_clock(tester).speed, 0.25); + }); }); - group('with a controller attached', () { - testWidgets('the widget speed is ignored', (tester) async { - final controller = BorderBeamController(); + group('precedence', () { + testWidgets('a controller replaces the timing speed', (tester) async { + final controller = BorderBeamController()..speed = 4; addTearDown(controller.dispose); await tester.pumpWidget( _host( - BorderBeam.rotate( + BorderBeam( controller: controller, - timing: const BeamTiming(speed: 5), + timing: const BeamTiming(speed: 0.5), child: const SizedBox.expand(), ), ), ); final clock = _clock(tester); - expect(clock.speed, 1, reason: "the controller's own rate wins"); - - controller.speed = 4; expect(clock.speed, 4); + controller.start(); await tester.pump(); await tester.pump(const Duration(milliseconds: 250)); expect(clock.elapsedSeconds, closeTo(1, 1e-9)); + + controller.speed = 2; + expect(clock.speed, 2, reason: 'a live controller change lands at once'); + + // Rejected outright, not only by a debug assertion, and the rate in + // force is left as it was. + for (final bad in [0.0, -1.0, double.nan, double.infinity]) { + expect(() => controller.speed = bad, throwsArgumentError); + } + expect(controller.speed, 2); + expect(clock.speed, 2); }); - testWidgets('a rebuild does not restore the widget speed', (tester) async { + testWidgets('a rebuild does not restore the timing speed over it', ( + tester, + ) async { final controller = BorderBeamController(); addTearDown(controller.dispose); Widget build(BeamColors colors) => _host( - BorderBeam.rotate( + BorderBeam( controller: controller, colors: colors, timing: const BeamTiming(speed: 5), @@ -210,23 +173,280 @@ void main() { expect(_clock(tester).speed, 2); }); - testWidgets('detaching hands the rate back to the widget', (tester) async { - final controller = BorderBeamController(); + testWidgets('speedListenable wins over the timing speed', (tester) async { + final speed = ValueNotifier(3); + addTearDown(speed.dispose); + await tester.pumpWidget( + _host( + BorderBeam( + timing: const BeamTiming(speed: 0.5), + speedListenable: speed, + child: const SizedBox.expand(), + ), + ), + ); + expect(_clock(tester).speed, 3); + }); + + testWidgets('speedListenable wins over a controller', (tester) async { + final controller = BorderBeamController()..speed = 4; addTearDown(controller.dispose); - Widget build(BorderBeamController? c) => _host( - BorderBeam.rotate( - controller: c, - timing: const BeamTiming(speed: 5), + final speed = ValueNotifier(2); + addTearDown(speed.dispose); + await tester.pumpWidget( + _host( + BorderBeam( + controller: controller, + speedListenable: speed, + child: const SizedBox.expand(), + ), + ), + ); + expect(_clock(tester).speed, 2); + speed.value = 3; + expect(_clock(tester).speed, 3); + }); + + testWidgets( + 'a controller speed change does not override a speedListenable', + (tester) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + final speed = ValueNotifier(2); + addTearDown(speed.dispose); + await tester.pumpWidget( + _host( + BorderBeam( + controller: controller, + speedListenable: speed, + child: const SizedBox.expand(), + ), + ), + ); + controller.speed = 8; + expect( + _clock(tester).speed, + 2, + reason: 'the listenable wins while it is set', + ); + }, + ); + + testWidgets('dropping each source hands the rate down the chain', ( + tester, + ) async { + final controller = BorderBeamController()..speed = 4; + addTearDown(controller.dispose); + final speed = ValueNotifier(2); + addTearDown(speed.dispose); + Widget build({ + BorderBeamController? controller, + ValueNotifier? speed, + }) => _host( + BorderBeam( + controller: controller, + speedListenable: speed, + timing: const BeamTiming(speed: 0.5), child: const SizedBox.expand(), ), ); - await tester.pumpWidget(build(controller)); - controller.speed = 2; + await tester.pumpWidget(build(controller: controller, speed: speed)); expect(_clock(tester).speed, 2); - await tester.pumpWidget(build(null)); - expect(_clock(tester).speed, 5); + await tester.pumpWidget(build(controller: controller)); + expect(_clock(tester).speed, 4); + speed.value = 9; + expect(_clock(tester).speed, 4, reason: 'the old listener is gone'); + + await tester.pumpWidget(build()); + expect(_clock(tester).speed, 0.5); + }); + }); + + group('speedListenable', () { + testWidgets('drives the rate live, without a rebuild or a snap', ( + tester, + ) async { + final speed = ValueNotifier(2); + addTearDown(speed.dispose); + var builds = 0; + await tester.pumpWidget( + _host( + Builder( + builder: (context) { + builds++; + return BorderBeam( + speedListenable: speed, + child: const SizedBox.expand(), + ); + }, + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + final painter = _painter(tester); + expect(painter.clock.elapsedSeconds, closeTo(1, 1e-9)); + final travel = _travel(tester); + + speed.value = 0.5; + await tester.pump(); + expect(painter.clock.speed, 0.5); + expect(painter.clock.elapsedSeconds, closeTo(1, 1e-9)); + expect(_travel(tester), closeTo(travel, 1e-9)); + await tester.pump(const Duration(seconds: 1)); + expect(painter.clock.elapsedSeconds, closeTo(1.5, 1e-9)); + + expect(builds, 1); + expect(identical(_painter(tester).config, painter.config), isTrue); + }); + + testWidgets('a swap moves the listener across', (tester) async { + final first = ValueNotifier(2); + final second = ValueNotifier(4); + addTearDown(first.dispose); + addTearDown(second.dispose); + Widget build(ValueNotifier speed) => _host( + BorderBeam(speedListenable: speed, child: const SizedBox.expand()), + ); + + await tester.pumpWidget(build(first)); + await tester.pumpWidget(build(second)); + expect(_clock(tester).speed, 4); + + first.value = 9; + expect(_clock(tester).speed, 4, reason: 'the old listener is gone'); + second.value = 0.5; + expect(_clock(tester).speed, 0.5); + }); + }); + + group('reduced motion slow', () { + Widget slow(Widget beam) => _host(disableAnimations: true, beam); + + testWidgets('quarters the timing speed and restores it after', ( + tester, + ) async { + Widget build({required bool reduced}) => _host( + disableAnimations: reduced, + const BorderBeam( + timing: BeamTiming(speed: 2), + playback: BeamPlayback(reducedMotion: BeamReducedMotion.slow), + child: SizedBox.expand(), + ), + ); + + await tester.pumpWidget(build(reduced: true)); + final clock = _clock(tester); + expect(clock.speed, 0.5); + await tester.pumpWidget(build(reduced: false)); + expect(clock.speed, 2); + await tester.pumpWidget(build(reduced: true)); + expect(clock.speed, 0.5); + }); + + testWidgets('quarters a speedListenable, live', (tester) async { + final speed = ValueNotifier(2); + addTearDown(speed.dispose); + await tester.pumpWidget( + slow( + BorderBeam( + speedListenable: speed, + playback: const BeamPlayback(reducedMotion: BeamReducedMotion.slow), + child: const SizedBox.expand(), + ), + ), + ); + expect(_clock(tester).speed, 0.5); + speed.value = 4; + expect(_clock(tester).speed, 1); + }); + + testWidgets('quarters the speed a controller had when it attached', ( + tester, + ) async { + final controller = BorderBeamController()..speed = 2; + addTearDown(controller.dispose); + await tester.pumpWidget( + slow( + BorderBeam( + controller: controller, + playback: const BeamPlayback(reducedMotion: BeamReducedMotion.slow), + child: const SizedBox.expand(), + ), + ), + ); + expect(_clock(tester).speed, 0.5); + }); + + testWidgets('quarters a live controller speed change', (tester) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + slow( + BorderBeam( + controller: controller, + playback: const BeamPlayback(reducedMotion: BeamReducedMotion.slow), + child: const SizedBox.expand(), + ), + ), + ); + controller.speed = 4; + expect(_clock(tester).speed, 1); + }); + }); + + group('under a BeamSync', () { + testWidgets('a member leaves the rate to the group', (tester) async { + final speed = ValueNotifier(9); + addTearDown(speed.dispose); + await tester.pumpWidget( + _host( + BeamSync( + speed: 3, + child: BorderBeam( + timing: const BeamTiming(speed: 0.5), + speedListenable: speed, + child: const SizedBox.expand(), + ), + ), + ), + ); + final clock = _clock(tester); + expect(clock.speed, 3); + speed.value = 7; + expect(clock.speed, 3, reason: "a member's listenable is ignored"); + + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); + expect(clock.elapsedSeconds, closeTo(0.6, 1e-9)); + }); + + testWidgets('a group speed change does not move the timeline', ( + tester, + ) async { + Widget build(double speed) => _host( + BeamSync( + speed: speed, + child: const BorderBeam(child: SizedBox()), + ), + ); + + await tester.pumpWidget(build(2)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + final clock = _clock(tester); + expect(clock.elapsedSeconds, closeTo(0.6, 1e-9)); + + await tester.pumpWidget(build(0.5)); + expect(clock.speed, 0.5); + expect(clock.elapsedSeconds, closeTo(0.6, 1e-9)); + await tester.pump(const Duration(milliseconds: 200)); + expect(clock.elapsedSeconds, closeTo(0.7, 1e-9)); + + await tester.pumpWidget(_host(const SizedBox())); + expect(tester.binding.transientCallbackCount, 0); }); }); } diff --git a/test/widget/beam_sync_test.dart b/test/widget/beam_sync_test.dart index 3ebb6e0..7fc72e0 100644 --- a/test/widget/beam_sync_test.dart +++ b/test/widget/beam_sync_test.dart @@ -1,8 +1,8 @@ -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_border_beam/src/animation/beam_clock.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; +import 'package:flutter_border_beam/src/render/beam_painter.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; import 'test_utils.dart'; @@ -26,370 +26,498 @@ List _painters(WidgetTester tester) => tester .whereType() .toList(); -Widget _beam({double? phaseOffset, Key? key}) => SizedBox( +BeamPainter _painterOf(WidgetTester tester, Key key) => tester + .widgetList( + find.descendant(of: find.byKey(key), matching: find.byType(CustomPaint)), + ) + .map((paint) => paint.foregroundPainter) + .whereType() + .first; + +double _sweep(BeamPainter painter) => + painter.resolver.sample(painter.clock.elapsedSeconds, 1).travelProgress; + +Widget _beam({ + Key? key, + BeamEffect? effect, + BeamTiming? timing, + BeamPlayback? playback, + Offset? follow, +}) => SizedBox( width: 120, height: 60, - child: BorderBeam.rotate( + child: BorderBeam( key: key, - timing: BeamTiming(phaseOffset: phaseOffset), + effect: effect, + timing: timing, + playback: playback, + follow: follow, child: const SizedBox.expand(), ), ); +Widget _row(List children) => + Row(mainAxisSize: MainAxisSize.min, children: children); + /// A group of beams on one clock: one ticker, one timeline, and playback /// owned by the scope rather than by each member. void main() { - testWidgets('three beams share a single ticker', (tester) async { - await tester.pumpWidget( - _host( - BeamSync( - child: Row( - mainAxisSize: MainAxisSize.min, - children: [_beam(), _beam(), _beam()], + group('the shared clock', () { + testWidgets('three members share one clock and one ticker', (tester) async { + await tester.pumpWidget( + _host(BeamSync(child: _row([_beam(), _beam(), _beam()]))), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + final clocks = _painters(tester).map((p) => p.clock).toSet(); + expect(clocks, hasLength(1)); + expect(clocks.single.elapsedSeconds, closeTo(0.3, 1e-9)); + expect(tester.binding.transientCallbackCount, 1); + }); + + testWidgets('the same three beams unsynced run a ticker each', ( + tester, + ) async { + await tester.pumpWidget(_host(_row([_beam(), _beam(), _beam()]))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(_painters(tester).map((p) => p.clock).toSet(), hasLength(3)); + expect(tester.binding.transientCallbackCount, 3); + }); + + testWidgets('a member added later joins the running timeline', ( + tester, + ) async { + Widget build(int count) => _host( + BeamSync(child: _row([for (var i = 0; i < count; i++) _beam()])), + ); + + await tester.pumpWidget(build(1)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pumpWidget(build(2)); + final painters = _painters(tester); + expect(painters, hasLength(2)); + expect(identical(painters[0].clock, painters[1].clock), isTrue); + expect(painters[1].clock.elapsedSeconds, closeTo(0.5, 1e-9)); + expect(_sweep(painters[1]), _sweep(painters[0])); + }); + + testWidgets('members sit at one sweep position; offsets stay per beam', ( + tester, + ) async { + const cycle = Duration(seconds: 2); + await tester.pumpWidget( + _host( + BeamSync( + child: _row([ + _beam(timing: const BeamTiming(cycle: cycle)), + _beam(timing: const BeamTiming(cycle: cycle)), + _beam(timing: const BeamTiming(cycle: cycle, phaseOffset: 0.25)), + ]), ), ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - expect(find.byType(BorderBeam), findsNWidgets(3)); - expect(tester.binding.transientCallbackCount, 1); + ); + await tester.pump(); + await tester.pump(pastFadeIn); + final sweeps = _painters(tester).map(_sweep).toList(); + expect(sweeps[1], sweeps[0]); + expect((sweeps[2] - sweeps[0]) % 1.0, closeTo(0.25, 1e-9)); + }); }); - testWidgets('the same three beams unsynced run three tickers', ( - tester, - ) async { - await tester.pumpWidget( - _host( - Row( - mainAxisSize: MainAxisSize.min, - children: [_beam(), _beam(), _beam()], + group('group playback', () { + test('a non-finite or non-positive speed is rejected', () { + for (final bad in [0.0, -1.0, double.nan, double.infinity]) { + expect( + () => BeamSync(speed: bad, child: const SizedBox()), + throwsAssertionError, + reason: '$bad', + ); + } + }); + + testWidgets("a member's own playback is ignored", (tester) async { + await tester.pumpWidget( + _host( + BeamSync( + child: _row([ + _beam(), + _beam( + playback: const BeamPlayback(active: false, autoPlay: false), + ), + ]), + ), ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - expect(tester.binding.transientCallbackCount, 3); - }); - - testWidgets('every beam paints from the one clock', (tester) async { - await tester.pumpWidget( - _host( - BeamSync( - child: Row( - mainAxisSize: MainAxisSize.min, - children: [_beam(), _beam(), _beam()], + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + final painters = _painters(tester); + expect(painters[1].clock, same(painters[0].clock)); + expect(painters[1].clock.isVisible, isTrue); + expect(tester.binding.transientCallbackCount, 1); + }); + + testWidgets('the group fades every member out and back in together', ( + tester, + ) async { + Widget build({required bool active}) => + _host(BeamSync(active: active, child: _row([_beam(), _beam()]))); + + await tester.pumpWidget(build(active: true)); + await tester.pump(); + await tester.pump(pastFadeIn); + final clock = _painters(tester).first.clock; + expect(clock.isVisible, isTrue); + + await tester.pumpWidget(build(active: false)); + expect(clock.stage, BeamFadeStage.fadingOut); + await tester.pump(pastFadeOut); + expect(clock.isVisible, isFalse); + expect(tester.binding.transientCallbackCount, 0); + + await tester.pumpWidget(build(active: true)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(clock.isVisible, isTrue); + expect(tester.binding.transientCallbackCount, 1); + }); + + testWidgets('the group reverses a fade-out that has not finished', ( + tester, + ) async { + Widget build({required bool active}) => + _host(BeamSync(active: active, child: _beam())); + + await tester.pumpWidget(build(active: true)); + await tester.pump(); + await tester.pump(pastFadeIn); + final clock = _painters(tester).single.clock; + + await tester.pumpWidget(build(active: false)); + await tester.pump(const Duration(milliseconds: 100)); + expect(clock.stage, BeamFadeStage.fadingOut); + final elapsed = clock.elapsedSeconds; + + await tester.pumpWidget(build(active: true)); + expect(clock.stage, BeamFadeStage.fadingIn); + expect( + clock.elapsedSeconds, + closeTo(elapsed, 1e-9), + reason: 'a reversed fade keeps the timeline it was on', + ); + await tester.pump(pastFadeIn); + expect(clock.fadeOpacity, closeTo(1, 1e-6)); + }); + + testWidgets('a group that starts stopped never runs a ticker', ( + tester, + ) async { + await tester.pumpWidget(_host(BeamSync(active: false, child: _beam()))); + await tester.pump(const Duration(seconds: 1)); + expect(tester.binding.transientCallbackCount, 0); + expect(_painters(tester).single.clock.isVisible, isFalse); + }); + + testWidgets('reduced motion freezes the whole group on a static frame', ( + tester, + ) async { + await tester.pumpWidget( + _host( + disableAnimations: true, + BeamSync(child: _row([_beam(), _beam()])), + ), + ); + await tester.pump(const Duration(seconds: 1)); + expect(tester.binding.transientCallbackCount, 0); + final painters = _painters(tester); + expect(painters, hasLength(2)); + for (final painter in painters) { + expect(painter.staticMode, isTrue); + } + }); + + testWidgets('the group slow policy quarters the shared clock', ( + tester, + ) async { + await tester.pumpWidget( + _host( + disableAnimations: true, + BeamSync( + reducedMotion: BeamReducedMotion.slow, + child: _beam( + playback: const BeamPlayback( + reducedMotion: BeamReducedMotion.staticFrame, + ), + ), ), ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - final clocks = _painters(tester).map((p) => p.clock).toSet(); - expect(clocks, hasLength(1)); - expect(clocks.single.elapsedSeconds, closeTo(0.3, 1e-9)); - }); - - testWidgets('lockstep beams sit at the same sweep position', (tester) async { - await tester.pumpWidget( - _host( - BeamSync( - child: Row( - mainAxisSize: MainAxisSize.min, - children: [_beam(), _beam()], + ); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + final painter = _painters(tester).single; + expect(painter.staticMode, isFalse, reason: 'the group policy wins'); + expect(painter.clock.speed, 0.25); + expect(painter.clock.elapsedSeconds, closeTo(0.25, 1e-9)); + }); + + testWidgets('a controller inside a group asserts', (tester) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + // The group is stopped so it never starts a ticker: a build that throws + // leaves a tree Flutter 3.35 cannot unmount, and a ticker started here + // would outlive the test. + await pumpExpectingAssertion( + tester, + _host( + BeamSync( + active: false, + child: SizedBox( + width: 120, + height: 60, + child: BorderBeam( + controller: controller, + child: const SizedBox.expand(), + ), + ), ), ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - final painters = _painters(tester); - final progress = painters - .map((p) => p.resolver.sample(p.clock.elapsedSeconds, 1).travelProgress) - .toSet(); - expect(progress, hasLength(1)); - }); + message: 'A BorderBeam under a BeamSync runs on the group clock', + ); + }); - testWidgets('each beam still applies its own phase offset', (tester) async { - await tester.pumpWidget( - _host( + testWidgets("one member's cycle change does not move the others", ( + tester, + ) async { + Widget build(Duration cycle) => _host( BeamSync( - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - _beam(), - _beam(phaseOffset: 0.25), - _beam(phaseOffset: 0.5), - ], - ), + child: _row([ + _beam(key: const ValueKey('steady')), + _beam(timing: BeamTiming(cycle: cycle)), + ]), ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - final painters = _painters(tester); - final progress = painters - .map((p) => p.resolver.sample(p.clock.elapsedSeconds, 1).travelProgress) - .toList(); - expect(progress, hasLength(3)); - expect(progress[1] - progress[0], closeTo(0.25, 1e-9)); - expect(progress[2] - progress[0], closeTo(0.5, 1e-9)); + ); + + await tester.pumpWidget(build(const Duration(seconds: 2))); + await tester.pump(); + await tester.pump(pastFadeIn); + final steady = _sweep(_painterOf(tester, const ValueKey('steady'))); + + await tester.pumpWidget(build(const Duration(seconds: 4))); + expect( + _sweep(_painterOf(tester, const ValueKey('steady'))), + closeTo(steady, 1e-9), + ); + }); }); - testWidgets('the group speed drives the shared clock', (tester) async { - await tester.pumpWidget(_host(BeamSync(speed: 3, child: _beam()))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); - expect(_painters(tester).first.clock.elapsedSeconds, closeTo(0.6, 1e-9)); - }); - - testWidgets('the group stops and starts every beam together', (tester) async { - Widget build({required bool active}) => _host( - BeamSync( - active: active, - child: Row( + group('joining and leaving', () { + testWidgets('leaving the group hands the beam its own clock, started', ( + tester, + ) async { + final key = GlobalKey(); + Widget build({required bool synced}) { + final beam = _beam(key: key); + return _host(synced ? BeamSync(child: beam) : beam); + } + + await tester.pumpWidget(build(synced: true)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + final shared = _painters(tester).single.clock; + + await tester.pumpWidget(build(synced: false)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + final own = _painters(tester).single.clock; + expect(own, isNot(same(shared))); + expect(own.isVisible, isTrue); + expect(own.isRunning, isTrue); + expect(own.elapsedSeconds, closeTo(0.3, 1e-9), reason: 'a fresh start'); + expect(tester.binding.transientCallbackCount, 1); + + await tester.pumpWidget(_host(const SizedBox())); + expect(tester.binding.transientCallbackCount, 0); + expect(tester.takeException(), isNull); + }); + + testWidgets('one member leaving keeps the group running', (tester) async { + final key = GlobalKey(); + Widget build({required bool moved}) => _host( + Column( mainAxisSize: MainAxisSize.min, - children: [_beam(), _beam()], + children: [ + BeamSync(child: _row([_beam(), if (!moved) _beam(key: key)])), + if (moved) _beam(key: key), + ], ), - ), - ); - - await tester.pumpWidget(build(active: true)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - final clock = _painters(tester).first.clock; - expect(clock.isVisible, isTrue); - - await tester.pumpWidget(build(active: false)); - expect(clock.stage, BeamFadeStage.fadingOut); - await tester.pump(const Duration(milliseconds: 600)); - expect(clock.isVisible, isFalse); - expect(tester.binding.transientCallbackCount, 0); - - await tester.pumpWidget(build(active: true)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - expect(clock.isVisible, isTrue); - expect(tester.binding.transientCallbackCount, 1); + ); + + await tester.pumpWidget(build(moved: false)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(tester.binding.transientCallbackCount, 1); + + await tester.pumpWidget(build(moved: true)); + await tester.pump(); + final clocks = _painters(tester).map((p) => p.clock).toSet(); + expect(clocks, hasLength(2)); + expect(clocks.every((clock) => clock.isRunning), isTrue); + expect(tester.binding.transientCallbackCount, 2); + }); + + testWidgets('joining a group retires the beam own clock', (tester) async { + final key = GlobalKey(); + Widget build({required bool synced}) { + final beam = _beam(key: key); + return _host(synced ? BeamSync(child: beam) : beam); + } + + await tester.pumpWidget(build(synced: false)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + final own = _painters(tester).single.clock; + + await tester.pumpWidget(build(synced: true)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(_painters(tester).single.clock, isNot(same(own))); + expect(tester.binding.transientCallbackCount, 1); + }); + + testWidgets('removing members leaves the rest running', (tester) async { + Widget build(int count) => _host( + BeamSync(child: _row([for (var i = 0; i < count; i++) _beam()])), + ); + + await tester.pumpWidget(build(3)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpWidget(build(1)); + await tester.pump(const Duration(milliseconds: 300)); + expect(tester.binding.transientCallbackCount, 1); + expect(_painters(tester).single.clock.elapsedSeconds, closeTo(0.6, 1e-9)); + + await tester.pumpWidget(_host(const SizedBox())); + expect(tester.binding.transientCallbackCount, 0); + expect(tester.takeException(), isNull); + }); }); - testWidgets('the group reverses a fade-out that has not finished', ( - tester, - ) async { - Widget build({required bool active}) => - _host(BeamSync(active: active, child: _beam())); - - await tester.pumpWidget(build(active: true)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - final clock = _painters(tester).first.clock; - - await tester.pumpWidget(build(active: false)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - expect(clock.stage, BeamFadeStage.fadingOut); - expect(clock.fadeOpacity, lessThan(1)); - final elapsed = clock.elapsedSeconds; - - // Back on mid-fade: the fade must turn around from where it is instead of - // running on to invisible. - await tester.pumpWidget(build(active: true)); - expect(clock.stage, BeamFadeStage.fadingIn); - expect( - clock.elapsedSeconds, - closeTo(elapsed, 1e-9), - reason: 'a reversed fade keeps the timeline it was on', - ); - await tester.pump(const Duration(milliseconds: 700)); - expect(clock.isVisible, isTrue); - expect(clock.fadeOpacity, closeTo(1, 1e-6)); - }); - - testWidgets('a group that starts stopped never runs a ticker', ( - tester, - ) async { - await tester.pumpWidget(_host(BeamSync(active: false, child: _beam()))); - await tester.pump(const Duration(seconds: 1)); - expect(tester.binding.transientCallbackCount, 0); - expect(_painters(tester).first.clock.isVisible, isFalse); - }); - - testWidgets('reduced motion freezes the group on a static frame', ( - tester, - ) async { - await tester.pumpWidget( - _host( - disableAnimations: true, - BeamSync( - child: Row( - mainAxisSize: MainAxisSize.min, - children: [_beam(), _beam()], - ), - ), - ), - ); - await tester.pump(const Duration(seconds: 1)); - expect(tester.binding.transientCallbackCount, 0); - final painters = _painters(tester); - expect(painters, hasLength(2)); - for (final painter in painters) { - expect(painter.staticMode, isTrue); + group('timeline resets', () { + // Follows a pointer, then lets go: the hand-back leaves a travel offset + // on the member, measured against the clock it is on right now. + Future handBack( + WidgetTester tester, + Widget Function({Offset? follow}) build, + ) async { + await tester.pumpWidget(build(follow: const Offset(1, 0.5))); + for (var i = 0; i < 30; i++) { + await tester.pump(const Duration(milliseconds: 16)); + } + await tester.pumpWidget(build()); } - }); - - testWidgets('the group resumes when the request lifts', (tester) async { - Widget build({required bool reduced}) => - _host(disableAnimations: reduced, BeamSync(child: _beam())); - - await tester.pumpWidget(build(reduced: true)); - await tester.pump(const Duration(seconds: 1)); - expect(tester.binding.transientCallbackCount, 0); - await tester.pumpWidget(build(reduced: false)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); - expect(tester.binding.transientCallbackCount, 1); - expect(_painters(tester).first.staticMode, isFalse); - }); - - testWidgets('returning to active under reduced motion stops a fade ticker', ( - tester, - ) async { - Widget build(bool active) => _host( - disableAnimations: true, - BeamSync(active: active, child: _beam()), - ); - - await tester.pumpWidget(build(true)); - expect(tester.binding.transientCallbackCount, 0); - await tester.pumpWidget(build(false)); - expect(tester.binding.transientCallbackCount, 1); - await tester.pumpWidget(build(true)); - expect(tester.binding.transientCallbackCount, 0); - expect(_painters(tester).first.clock.isRunning, isFalse); - }); - - testWidgets('the group can opt into full motion under reduced motion', ( - tester, - ) async { - await tester.pumpWidget( - _host( - disableAnimations: true, - BeamSync(reducedMotion: BeamReducedMotion.animate, child: _beam()), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); - final painter = _painters(tester).first; - expect(painter.staticMode, isFalse); - expect(painter.clock.isRunning, isTrue); - expect(painter.clock.elapsedSeconds, closeTo(0.2, 1e-9)); - }); - - testWidgets('the group slow policy scales its shared clock', (tester) async { - await tester.pumpWidget( - _host( - disableAnimations: true, - BeamSync(reducedMotion: BeamReducedMotion.slow, child: _beam()), - ), - ); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - final painter = _painters(tester).first; - expect(painter.staticMode, isFalse); - expect(painter.clock.speed, 0.25); - expect(painter.clock.elapsedSeconds, closeTo(0.25, 1e-9)); - }); - - testWidgets('disposing the group leaves no ticker behind', (tester) async { - await tester.pumpWidget( - _host( + testWidgets('a group restart drops its members corrections', ( + tester, + ) async { + var active = true; + Widget build({Offset? follow}) => _host( BeamSync( - child: Row( - mainAxisSize: MainAxisSize.min, - children: [_beam(), _beam(), _beam()], - ), + active: active, + child: _beam(follow: follow), ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - expect(tester.binding.transientCallbackCount, 1); - - await tester.pumpWidget(_host(const SizedBox())); - expect(tester.binding.transientCallbackCount, 0); - expect(tester.takeException(), isNull); - }); - - testWidgets('removing one beam leaves the rest running', (tester) async { - Widget build(int count) => _host( - BeamSync( - child: Row( - mainAxisSize: MainAxisSize.min, - children: [for (var i = 0; i < count; i++) _beam()], - ), - ), - ); - - await tester.pumpWidget(build(3)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - await tester.pumpWidget(build(1)); - await tester.pump(const Duration(milliseconds: 300)); - expect(tester.binding.transientCallbackCount, 1); - expect(_painters(tester), hasLength(1)); - expect(tester.takeException(), isNull); - }); - - testWidgets('a controller inside a group asserts', (tester) async { - final controller = BorderBeamController(); - addTearDown(controller.dispose); - // The group is stopped so it never starts a ticker: a build that throws - // leaves a tree Flutter 3.35 cannot unmount (`InheritedElement.unmount` - // asserts on its dependents), so a ticker started here would outlive the - // test and count against the next one. - await pumpExpectingAssertion( + ); + + await tester.pumpWidget(build()); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + await handBack(tester, build); + expect(_painters(tester).single.resolver.travelTimeOffset, isNot(0)); + + // The group owns the clock, so the member is never told to restart — + // it has to hear it from the clock itself. + active = false; + await tester.pumpWidget(build()); + await tester.pump(pastFadeOut); + active = true; + await tester.pumpWidget(build()); + final painter = _painters(tester).single; + expect(painter.clock.elapsedSeconds, 0); + expect(painter.resolver.travelTimeOffset, 0); + }); + + testWidgets('a beam that left the group listens to its own clock', ( tester, - _host( - BeamSync( - active: false, - child: SizedBox( - width: 120, - height: 60, - child: BorderBeam.rotate( - controller: controller, - child: const SizedBox.expand(), - ), + ) async { + final key = GlobalKey(); + final stays = GlobalKey(); + var moved = false; + var groupActive = true; + var beamActive = true; + Widget build({Offset? follow}) { + final leaver = SizedBox( + width: 120, + height: 60, + child: BorderBeam( + key: key, + active: beamActive, + follow: follow, + child: const SizedBox.expand(), ), - ), - ), - message: 'A BorderBeam under a BeamSync runs on the group clock', - ); - }); - - testWidgets('leaving the group hands the beam its own clock', (tester) async { - final key = GlobalKey(); - Widget build({required bool synced}) { - final beam = _beam(key: key); - return _host(synced ? BeamSync(child: beam) : beam); - } - - await tester.pumpWidget(build(synced: true)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - final shared = _painters(tester).first.clock; - expect(tester.binding.transientCallbackCount, 1); - - await tester.pumpWidget(build(synced: false)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - final own = _painters(tester).first.clock; - expect(identical(own, shared), isFalse); - expect(own.isVisible, isTrue); - expect(tester.binding.transientCallbackCount, 1); - - await tester.pumpWidget(_host(const SizedBox())); - expect(tester.binding.transientCallbackCount, 0); - expect(tester.takeException(), isNull); + ); + // The group keeps its place in the tree, so it is the same group — + // and the same clock — before and after the move. + return _host( + Column( + mainAxisSize: MainAxisSize.min, + children: [ + BeamSync( + active: groupActive, + child: _row([_beam(key: stays), if (!moved) leaver]), + ), + if (moved) leaver, + ], + ), + ); + } + + await tester.pumpWidget(build()); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + final groupClock = _painterOf(tester, stays).clock; + expect(_painterOf(tester, key).clock, same(groupClock)); + + moved = true; + await tester.pumpWidget(build()); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(_painterOf(tester, stays).clock, same(groupClock)); + + BeamPainter leaver() => _painterOf(tester, key); + expect(leaver().clock, isNot(same(groupClock))); + + await handBack(tester, build); + final offset = leaver().resolver.travelTimeOffset; + expect(offset, isNot(0)); + + // The group it left restarts: none of the leaver's business. + groupActive = false; + await tester.pumpWidget(build()); + await tester.pump(pastFadeOut); + expect(groupClock.isVisible, isFalse); + groupActive = true; + await tester.pumpWidget(build()); + expect(leaver().resolver.travelTimeOffset, offset); + + // Its own clock restarts: that clears it. + beamActive = false; + await tester.pumpWidget(build()); + await tester.pump(pastFadeOut); + beamActive = true; + await tester.pumpWidget(build()); + expect(leaver().clock.elapsedSeconds, 0); + expect(leaver().resolver.travelTimeOffset, 0); + }); }); } diff --git a/test/widget/beam_theme_config_test.dart b/test/widget/beam_theme_config_test.dart deleted file mode 100644 index ef5e378..0000000 --- a/test/widget/beam_theme_config_test.dart +++ /dev/null @@ -1,256 +0,0 @@ -import 'dart:typed_data'; -import 'dart:ui' as ui; - -import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam/src/constants/theme_presets.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; -import 'package:flutter_test/flutter_test.dart'; - -Widget _host(Widget child) => MaterialApp( - theme: ThemeData(brightness: Brightness.dark), - home: Scaffold( - body: Center( - child: SizedBox( - width: 200, - height: 100, - child: RepaintBoundary(child: child), - ), - ), - ), -); - -BeamConfig _config(WidgetTester tester) => tester - .widgetList( - find.descendant( - of: find.byType(BorderBeam), - matching: find.byType(CustomPaint), - ), - ) - .expand((paint) => [paint.painter, paint.foregroundPainter]) - .whereType() - .first - .config; - -/// Rasterizes the beam's repaint boundary as raw RGBA. -Future _pixels(WidgetTester tester) async { - final boundary = tester.renderObject( - find.byType(BorderBeam), - ); - final bytes = await tester.runAsync(() async { - final image = await boundary.toImage(); - final data = await image.toByteData(format: ui.ImageByteFormat.rawRgba); - image.dispose(); - return data!.buffer.asUint8List(); - }); - return bytes!; -} - -/// `BeamStyle.themeConfig` replaces the whole variant×brightness preset, so a -/// layer opacity set to zero must reach the painter's config *and* the -/// rasterized frame. -void main() { - group('themeConfig through a mounted beam', () { - Widget beam(BeamThemeConfig? themeConfig) => _host( - BorderBeam.rotate( - style: BeamStyle(themeConfig: themeConfig), - // A frozen palette and no hue animation keeps two renders of the - // same config byte-identical. - colors: BeamColors.ocean, - child: const SizedBox.expand(), - ), - ); - - testWidgets('replaces the preset the variant would have used', ( - tester, - ) async { - final preset = BeamThemeConfig.presetFor( - BeamVariant.rotate, - Brightness.dark, - ); - await tester.pumpWidget(beam(preset.copyWith(strokeOpacity: 0))); - final config = _config(tester); - expect(config.theme.strokeOpacity, 0); - expect( - config.theme.innerOpacity, - preset.innerOpacity, - reason: 'the untouched fields still come from the preset', - ); - expect(config.theme.bloomOpacity, preset.bloomOpacity); - expect(config.theme.innerShadow, preset.innerShadow); - }); - - testWidgets('a zero stroke opacity changes the rendered frame', ( - tester, - ) async { - final preset = BeamThemeConfig.presetFor( - BeamVariant.rotate, - Brightness.dark, - ); - - await tester.pumpWidget(beam(null)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1300)); - final withStroke = await _pixels(tester); - - // The same tree again: the rasterization itself is deterministic, so a - // difference below can only come from the config. - await tester.pumpWidget(beam(null)); - await tester.pump(); - expect( - await _pixels(tester), - withStroke, - reason: 'an unchanged config renders the identical frame', - ); - - await tester.pumpWidget(beam(preset.copyWith(strokeOpacity: 0))); - await tester.pump(); - final withoutStroke = await _pixels(tester); - expect( - withoutStroke, - isNot(withStroke), - reason: 'the stroke layer is gone', - ); - expect(withoutStroke.length, withStroke.length); - }); - - testWidgets('a fully transparent preset paints nothing', (tester) async { - const blank = BeamThemeConfig( - strokeOpacity: 0, - innerOpacity: 0, - bloomOpacity: 0, - innerShadow: Color(0x00000000), - saturation: 1, - ); - await tester.pumpWidget(beam(blank)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1300)); - final pixels = await _pixels(tester); - var opaque = 0; - for (var i = 3; i < pixels.length; i += 4) { - if (pixels[i] != 0) opaque++; - } - expect(opaque, 0, reason: 'every beam layer opacity is zero'); - }); - - testWidgets('style brightness and saturation still override it', ( - tester, - ) async { - await tester.pumpWidget( - _host( - BorderBeam.rotate( - style: BeamStyle( - themeConfig: BeamThemeConfig.presetFor( - BeamVariant.rotate, - Brightness.dark, - ).copyWith(brightness: 2, saturation: 3), - brightness: 0.5, - saturation: 0.25, - ), - child: const SizedBox.expand(), - ), - ), - ); - final config = _config(tester); - expect(config.brightnessFactor, 0.5); - expect(config.saturation, 0.25); - }); - - testWidgets('a themeConfig from a BorderBeamTheme is inherited', ( - tester, - ) async { - final preset = BeamThemeConfig.presetFor( - BeamVariant.line, - Brightness.dark, - ).copyWith(bloomOpacity: 0.05); - await tester.pumpWidget( - _host( - BorderBeamTheme( - data: BorderBeamThemeData(style: BeamStyle(themeConfig: preset)), - child: const BorderBeam.line(child: SizedBox.expand()), - ), - ), - ); - expect(_config(tester).theme.bloomOpacity, 0.05); - }); - }); - - group('BeamThemeConfig', () { - test('presetFor matches themePresetFor for every variant × brightness', () { - for (final variant in BeamVariant.values) { - for (final brightness in Brightness.values) { - final preset = BeamThemeConfig.presetFor(variant, brightness); - final expected = themePresetFor(variant, brightness); - expect(preset, expected, reason: '$variant $brightness'); - expect(preset.strokeOpacity, expected.strokeOpacity); - expect(preset.innerOpacity, expected.innerOpacity); - expect(preset.bloomOpacity, expected.bloomOpacity); - expect(preset.innerShadow, expected.innerShadow); - expect(preset.saturation, expected.saturation); - expect(preset.brightness, expected.brightness); - expect(preset.hairlineOpacity, expected.hairlineOpacity); - } - } - }); - - test('dark and light presets differ for every variant', () { - for (final variant in BeamVariant.values) { - expect( - BeamThemeConfig.presetFor(variant, Brightness.dark), - isNot(BeamThemeConfig.presetFor(variant, Brightness.light)), - reason: '$variant', - ); - } - }); - - test('copyWith keeps every field it is not given', () { - const base = BeamThemeConfig( - strokeOpacity: 0.26, - innerOpacity: 0.42, - bloomOpacity: 0.24, - innerShadow: Color(0x44FFFFFF), - saturation: 1.2, - brightness: 1.1, - hairlineOpacity: 0.3, - ); - final copy = base.copyWith(bloomOpacity: 0.9); - expect(copy.bloomOpacity, 0.9); - expect(copy.strokeOpacity, base.strokeOpacity); - expect(copy.innerOpacity, base.innerOpacity); - expect(copy.innerShadow, base.innerShadow); - expect(copy.saturation, base.saturation); - expect(copy.brightness, base.brightness); - expect(copy.hairlineOpacity, base.hairlineOpacity); - expect(base.copyWith(), base, reason: 'an empty copy is the same value'); - }); - - test('equality and hashCode are by value', () { - const a = BeamThemeConfig( - strokeOpacity: 0.5, - innerOpacity: 0.4, - bloomOpacity: 0.3, - innerShadow: Color(0x22000000), - saturation: 1.5, - ); - const b = BeamThemeConfig( - strokeOpacity: 0.5, - innerOpacity: 0.4, - bloomOpacity: 0.3, - innerShadow: Color(0x22000000), - saturation: 1.5, - ); - expect(a, b); - expect(a.hashCode, b.hashCode); - expect(a, isNot(b.copyWith(strokeOpacity: 0.51))); - expect(a, isNot(b.copyWith(innerOpacity: 0.41))); - expect(a, isNot(b.copyWith(bloomOpacity: 0.31))); - expect(a, isNot(b.copyWith(innerShadow: const Color(0x22000001)))); - expect(a, isNot(b.copyWith(saturation: 1.51))); - expect(a, isNot(b.copyWith(brightness: 1))); - expect(a, isNot(b.copyWith(hairlineOpacity: 0))); - expect(a.toString(), contains('strokeOpacity: 0.5')); - }); - }); -} diff --git a/test/widget/border_beam_cycle_gap_test.dart b/test/widget/border_beam_cycle_gap_test.dart index 4f9509f..e2cfd2f 100644 --- a/test/widget/border_beam_cycle_gap_test.dart +++ b/test/widget/border_beam_cycle_gap_test.dart @@ -1,16 +1,12 @@ -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/animation/beam_clock.dart'; import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; +import 'package:flutter_border_beam/src/render/beam_painter.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -Widget _host(Widget child, {bool disableAnimations = false}) => MaterialApp( +Widget _host(Widget child) => MaterialApp( theme: ThemeData(brightness: Brightness.dark), - builder: (context, app) => MediaQuery( - data: MediaQuery.of(context).copyWith(disableAnimations: disableAnimations), - child: app!, - ), home: Scaffold( body: Center(child: SizedBox(width: 350, height: 140, child: child)), ), @@ -27,659 +23,330 @@ BeamPainter _painter(WidgetTester tester) => tester .whereType() .first; -BeamPhaseResolver _resolver(WidgetTester tester) => _painter(tester).resolver; - -// A resolver built straight from a config, for the instants the envelope is -// specified at — no clock, no widget. -BeamPhaseResolver _direct({ - required Duration cycle, - required Duration gap, - BeamVariant variant = BeamVariant.rotate, -}) => BeamPhaseResolver( - BeamConfig.resolve( - variant: variant, - palette: BeamColors.colorful.resolve(), - brightness: Brightness.dark, - timing: BeamTiming(cycle: cycle, cycleGap: gap), - ), -); +// The mounted beam's phases at [t] with a beam fade of [fade]. +BeamFramePhases _at(WidgetTester tester, double t, [double fade = 1]) => + _painter(tester).resolver.sample(t, fade); + +// The mounted beam's phases right now, before its own fade. +BeamFramePhases _now(WidgetTester tester) { + final painter = _painter(tester); + return painter.resolver.sample(painter.clock.elapsedSeconds, 1); +} + +// Derived, so a new effect joins the family it belongs to. +final _travelling = [ + for (final effect in BeamEffect.values) + if (effect.travels) effect, +]; -/// `BeamTiming.cycleGap` rests the traveling beam between sweeps: the sweep -/// still takes `cycle`, then the beam parks at the end of its travel and its -/// fade envelope eases to zero for the rest of the gap. Phases are sampled -/// directly off the mounted beam's resolver so the instants are exact. +/// `BeamTiming.cycleGap` rests a travelling effect between sweeps: the sweep +/// still takes `cycle`, then the beam parks at the end of its travel while +/// its envelope eases to zero and back. Ambient effects have no sweep to rest +/// and ignore it. void main() { - const timing = BeamTiming( + const oneAndOne = BeamTiming( cycle: Duration(seconds: 1), cycleGap: Duration(seconds: 1), ); - testWidgets('rotate fades out through the gap and back in on the next ' - 'sweep', (tester) async { - await tester.pumpWidget( - _host(const BorderBeam.rotate(timing: timing, child: SizedBox.expand())), - ); - final resolver = _resolver(tester); - expect(resolver.config.gapSeconds, closeTo(1, 1e-9)); - - expect(resolver.sample(0.5, 1).fadeOpacity, 1, reason: 'mid sweep'); - expect(resolver.sample(1.5, 1).fadeOpacity, 0, reason: 'mid rest'); - expect(resolver.sample(2.5, 1).fadeOpacity, 1, reason: 'next sweep'); - }); + group('the rest', () { + for (final effect in _travelling) { + testWidgets('${effect.name} sweeps, then parks and rests', ( + tester, + ) async { + await tester.pumpWidget( + _host( + BorderBeam( + effect: effect, + timing: oneAndOne, + child: const SizedBox.expand(), + ), + ), + ); + expect(_painter(tester).config.gapSeconds, closeTo(1, 1e-9)); - testWidgets('rotate parks its angle at the end of the sweep', (tester) async { - await tester.pumpWidget( - _host(const BorderBeam.rotate(timing: timing, child: SizedBox.expand())), - ); - final resolver = _resolver(tester); - // Progress is pinned to 1.0 for the whole rest, so the beam holds where - // its sweep ended rather than drifting on. - expect(resolver.sample(1.2, 1).angleRadians, closeTo(2 * 3.14159265, 1e-5)); - expect(resolver.sample(1.9, 1).angleRadians, closeTo(2 * 3.14159265, 1e-5)); - }); + final sweep = _at(tester, 0.5); + expect(sweep.fadeOpacity, 1); + expect(sweep.travelProgress, closeTo(0.5, 1e-9)); - testWidgets('the gap eases in and out rather than cutting', (tester) async { - await tester.pumpWidget( - _host(const BorderBeam.rotate(timing: timing, child: SizedBox.expand())), - ); - final resolver = _resolver(tester); - // gapFade = min(0.25, gap / 2) = 0.25s at each end of the rest. - final entering = resolver.sample(1.125, 1).fadeOpacity; - final leaving = resolver.sample(1.875, 1).fadeOpacity; - expect(entering, greaterThan(0)); - expect(entering, lessThan(1)); - expect(leaving, closeTo(entering, 1e-9)); - expect(resolver.sample(1.0, 1).fadeOpacity, closeTo(1, 1e-9)); - expect(resolver.sample(2.0, 1).fadeOpacity, closeTo(1, 1e-9)); - }); - - testWidgets('line parks invisible at the end of its travel', (tester) async { - await tester.pumpWidget( - _host(const BorderBeam.line(timing: timing, child: SizedBox.expand())), - ); - final resolver = _resolver(tester); - for (final t in [1.2, 1.5, 1.9]) { - final phases = resolver.sample(t, 1); - expect(phases.lineX, closeTo(0.94, 1e-9), reason: 'parked at t=$t'); - expect(phases.edge, 0, reason: 'edge fade is already 0 at t=$t'); + for (final t in [1.2, 1.5, 1.8]) { + expect(_at(tester, t).travelProgress, 1, reason: 'parked at t=$t'); + } + expect(_at(tester, 1.5).fadeOpacity, 0, reason: 'dark mid-rest'); + final easing = _at(tester, 1.1).fadeOpacity; + expect(easing, greaterThan(0)); + expect(easing, lessThan(1)); + + final next = _at(tester, 2.5); + expect(next.fadeOpacity, 1, reason: 'back for the next sweep'); + expect(next.travelProgress, closeTo(0.5, 1e-9)); + }); } - }); - testWidgets('a zero gap leaves the sweep untouched', (tester) async { - await tester.pumpWidget( - _host( - const BorderBeam.rotate( - timing: BeamTiming(cycle: Duration(seconds: 1)), - child: SizedBox.expand(), - ), - ), - ); - final resolver = _resolver(tester); - expect(resolver.config.gapSeconds, 0); - for (final t in [0.0, 0.25, 0.5, 0.99, 1.5, 7.3]) { - expect(resolver.sample(t, 1).fadeOpacity, 1, reason: 't=$t'); - expect( - resolver.sample(t, 1).angleRadians, - closeTo((t % 1.0) * 2 * 3.14159265358979, 1e-9), - reason: 't=$t', + testWidgets('the live beam rests and comes back', (tester) async { + await tester.pumpWidget( + _host(const BorderBeam(timing: oneAndOne, child: SizedBox.expand())), ); - } + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1500)); + var phases = _now(tester); + expect(phases.fadeOpacity, 0); + expect(phases.travelProgress, 1); + expect(_painter(tester).clock.isRunning, isTrue, reason: 'still ticking'); + + await tester.pump(const Duration(seconds: 1)); + phases = _now(tester); + expect(phases.fadeOpacity, 1); + expect(phases.travelProgress, closeTo(0.5, 1e-9)); + }); }); - group('retiming across a gap', () { - const twoPlusOne = BeamTiming( - cycle: Duration(seconds: 2), - cycleGap: Duration(seconds: 1), - ); + group('defaults', () { + for (final effect in _travelling) { + testWidgets('${effect.name} runs without a rest by default', ( + tester, + ) async { + await tester.pumpWidget( + _host(BorderBeam(effect: effect, child: const SizedBox.expand())), + ); + expect(_painter(tester).config.gapSeconds, 0); + }); + } + }); - testWidgets('a cycle change mid-sweep keeps travel progress continuous', ( + group('ambient effects ignore it', () { + testWidgets('a gap change on an ambient beam does not move it', ( tester, ) async { - Widget build(BeamTiming timing) => _host( - BorderBeam.rotate(timing: timing, child: const SizedBox.expand()), - ); - - await tester.pumpWidget(build(twoPlusOne)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 900)); - final before = _painter(tester); - expect(before.clock.elapsedSeconds, closeTo(0.9, 1e-9)); - final angle = before.resolver.sample(0.9, 1).angleRadians; - - await tester.pumpWidget( - build( - const BeamTiming( - cycle: Duration(seconds: 4), - cycleGap: Duration(seconds: 1), - ), - ), - ); - final after = _painter(tester); - expect(after.config.cycleSeconds, closeTo(4, 1e-9)); - expect(after.config.gapSeconds, closeTo(1, 1e-9)); - expect( - after.clock.elapsedSeconds, - closeTo(1.8, 1e-9), - reason: 'elapsed is rescaled by the cycle ratio, gap and all', - ); - expect( - after.resolver.sample(after.clock.elapsedSeconds, 1).angleRadians, - closeTo(angle, 1e-6), - reason: 'the sweep is at the same fraction of its travel', - ); - }); - - testWidgets('changing only the gap needs no retime', (tester) async { Widget build(Duration gap) => _host( - BorderBeam.rotate( + BorderBeam( + effect: const BeamEffect.pulse(), timing: BeamTiming(cycle: const Duration(seconds: 2), cycleGap: gap), child: const SizedBox.expand(), ), ); - await tester.pumpWidget(build(const Duration(seconds: 1))); + await tester.pumpWidget(build(Duration.zero)); await tester.pump(); - await tester.pump(const Duration(milliseconds: 900)); - final before = _painter(tester); - final angle = before.resolver.sample(0.9, 1).angleRadians; - - await tester.pumpWidget(build(const Duration(seconds: 2))); - final after = _painter(tester); - expect(after.config.gapSeconds, closeTo(2, 1e-9)); - expect( - after.clock.elapsedSeconds, - closeTo(0.9, 1e-9), - reason: 'the timeline is untouched', - ); - expect( - after.resolver.sample(0.9, 1).angleRadians, - closeTo(angle, 1e-9), - reason: 'the sweep keeps its position; the rest appears later', - ); + await tester.pump(const Duration(milliseconds: 2500)); + final cycles = _now(tester).cycles; + await tester.pumpWidget(build(const Duration(seconds: 3))); + expect(_painter(tester).clock.elapsedSeconds, closeTo(2.5, 1e-9)); + expect(_now(tester).cycles, closeTo(cycles, 1e-9)); }); + }); - testWidgets('a phase-offset beam resting in the gap stays in the gap', ( - tester, - ) async { - Widget build(Duration cycle) => _host( - BorderBeam.rotate( - timing: BeamTiming( - cycle: cycle, - cycleGap: const Duration(seconds: 1), - phaseOffset: 0.5, - ), - child: const SizedBox.expand(), - ), - ); + group('changing timing mid-run', () { + Widget beam(BeamTiming timing, {bool active = true}) => _host( + BorderBeam( + active: active, + timing: timing, + child: const SizedBox.expand(), + ), + ); - // cycle 2 + gap 1 with a half-cycle offset: at 1.5s elapsed the beam is - // 2.5s into its own 3s period — parked half a second into the rest. - await tester.pumpWidget(build(const Duration(seconds: 2))); + Future runFor(WidgetTester tester, Duration duration) async { await tester.pump(); - await tester.pump(const Duration(milliseconds: 1500)); - final before = _painter(tester); - final resting = before.resolver.sample(1.5, 1); - expect(resting.fadeOpacity, closeTo(0, 1e-9)); - expect(resting.travelProgress, closeTo(1, 1e-9)); - - await tester.pumpWidget(build(const Duration(seconds: 4))); - final after = _painter(tester); - final phases = after.resolver.sample(after.clock.elapsedSeconds, 1); - expect( - phases.fadeOpacity, - closeTo(0, 1e-9), - reason: 'the raw timeline says mid-sweep; the shifted one says gap', - ); - expect(phases.travelProgress, closeTo(1, 1e-9)); - }); - - testWidgets('a follow hand-back survives a cycle change', (tester) async { - Widget build({required Duration cycle, Offset? follow}) => _host( - BorderBeam.rotate( - timing: BeamTiming(cycle: cycle), - follow: follow, - child: const SizedBox.expand(), - ), - ); + await tester.pump(duration); + } - const short = Duration(seconds: 4); - await tester.pumpWidget(build(cycle: short)); - await tester.pump(); + testWidgets('a gap change in the first sweep leaves it where it is', ( + tester, + ) async { + const cycle = Duration(seconds: 2); + await tester.pumpWidget(beam(const BeamTiming(cycle: cycle))); + await runFor(tester, const Duration(milliseconds: 900)); + final before = _now(tester); - // Hand the sweep to a pointer parked most of a cycle behind the clock, - // let it settle, then let go: the beam carries a large negative travel - // offset from here on, which puts the shifted timeline behind zero. await tester.pumpWidget( - build(cycle: short, follow: const Offset(0, 0.5)), - ); - for (var i = 0; i < 40; i++) { - await tester.pump(const Duration(milliseconds: 16)); - } - await tester.pumpWidget(build(cycle: short)); - final before = _painter(tester); - final offset = before.resolver.travelTimeOffset; - expect( - offset, - lessThan(-before.clock.elapsedSeconds), - reason: - 'the hand-back must outweigh elapsed for the shift to go ' - 'negative', - ); - final progress = before.resolver - .sample(before.clock.elapsedSeconds, 1) - .travelProgress; - - await tester.pumpWidget(build(cycle: const Duration(seconds: 16))); - final after = _painter(tester); - expect( - after.resolver.travelTimeOffset, - closeTo(offset, 1e-9), - reason: 'a rebuilt resolver keeps the hand-back', - ); - expect( - after.resolver.sample(after.clock.elapsedSeconds, 1).travelProgress, - closeTo(progress, 1e-6), - reason: 'the retime target is lifted by whole periods, not refused', + beam(const BeamTiming(cycle: cycle, cycleGap: Duration(seconds: 1))), ); + expect(_painter(tester).clock.elapsedSeconds, closeTo(0.9, 1e-9)); + final after = _now(tester); + expect(after.travelProgress, closeTo(before.travelProgress, 1e-9)); + expect(after.fadeOpacity, before.fadeOpacity); }); - testWidgets('the line breathe and spike tracks survive a retime', ( + testWidgets('a gap change in a later sweep leaves it where it is', ( tester, ) async { - Widget build(Duration cycle) => _host( - BorderBeam.line( - timing: BeamTiming( - cycle: cycle, - cycleGap: const Duration(seconds: 1), + // Two seconds of sweep + rest have passed: 0.5s into the second + // sweep. A new gap must not re-cut the elapsed time into periods. + await tester.pumpWidget(beam(oneAndOne)); + await runFor(tester, const Duration(milliseconds: 2500)); + final before = _now(tester); + expect(before.travelProgress, closeTo(0.5, 1e-9)); + + await tester.pumpWidget( + beam( + const BeamTiming( + cycle: Duration(seconds: 1), + cycleGap: Duration(seconds: 2), ), - child: const SizedBox.expand(), ), ); - - // A gap bends the retime target away from a pure ratio rescale, and - // these three tracks scale with the cycle, so only a rescaled timeline - // holds their phase. - await tester.pumpWidget(build(const Duration(seconds: 2))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 2500)); - final before = _painter(tester); - final was = before.resolver.sample(before.clock.elapsedSeconds, 1); - - await tester.pumpWidget(build(const Duration(seconds: 4))); - final after = _painter(tester); - final now = after.resolver.sample(after.clock.elapsedSeconds, 1); - - expect(now.lineH, closeTo(was.lineH, 1e-9)); - expect(now.spike, closeTo(was.spike, 1e-9)); - expect(now.spike2, closeTo(was.spike2, 1e-9)); + final after = _now(tester); + expect(after.travelProgress, closeTo(0.5, 1e-9)); + expect(after.fadeOpacity, 1); }); - testWidgets('a restart drops the timeline corrections a retime left', ( + testWidgets('a cycle change mid-sweep keeps the sweep position', ( tester, ) async { - Widget build({required Duration cycle, required bool active}) => _host( - BorderBeam.line( - active: active, - timing: BeamTiming( - cycle: cycle, - cycleGap: const Duration(seconds: 1), - ), - child: const SizedBox.expand(), - ), - ); - - await tester.pumpWidget( - build(cycle: const Duration(seconds: 2), active: true), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 2500)); + const gap = Duration(seconds: 1); await tester.pumpWidget( - build(cycle: const Duration(seconds: 4), active: true), + beam(const BeamTiming(cycle: Duration(seconds: 2), cycleGap: gap)), ); - final retimed = _painter(tester); - expect(retimed.resolver.hueTimeOffset, isNot(0)); - expect(retimed.resolver.breatheTimeOffset, isNot(0)); + // 3.9s: 0.9s into the second sweep of a 2s + 1s period. + await runFor(tester, const Duration(milliseconds: 3900)); + final before = _now(tester); + expect(before.travelProgress, closeTo(0.45, 1e-9)); - // Off, let the fade finish, then on: activate() puts elapsed back to - // zero, so every correction measured against the old timeline goes. - await tester.pumpWidget( - build(cycle: const Duration(seconds: 4), active: false), - ); - await tester.pump(const Duration(milliseconds: 600)); await tester.pumpWidget( - build(cycle: const Duration(seconds: 4), active: true), + beam(const BeamTiming(cycle: Duration(seconds: 4), cycleGap: gap)), ); - final restarted = _painter(tester); - expect(restarted.clock.elapsedSeconds, closeTo(0, 1e-9)); - expect(restarted.resolver.hueTimeOffset, 0); - expect(restarted.resolver.breatheTimeOffset, 0); - expect(restarted.resolver.travelTimeOffset, 0); - }); + final painter = _painter(tester); + expect(painter.config.cycleSeconds, closeTo(4, 1e-9)); + final after = _now(tester); + expect(after.travelProgress, closeTo(0.45, 1e-9)); + expect(after.fadeOpacity, 1); - testWidgets('a synced group restart drops its members corrections', ( - tester, - ) async { - Widget build({required Duration cycle, required bool active}) => _host( - BeamSync( - active: active, - child: BorderBeam.line( - timing: BeamTiming(cycle: cycle), - child: const SizedBox.expand(), - ), - ), - ); + // And it carries on at the new pace. + await tester.pump(const Duration(milliseconds: 400)); + expect(_now(tester).travelProgress, closeTo(0.55, 1e-9)); + }); + testWidgets('a cycle change mid-rest holds the rest', (tester) async { + const gap = Duration(seconds: 1); await tester.pumpWidget( - build(cycle: const Duration(seconds: 2), active: true), + beam(const BeamTiming(cycle: Duration(seconds: 2), cycleGap: gap)), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1500)); - await tester.pumpWidget( - build(cycle: const Duration(seconds: 4), active: true), - ); - expect(_painter(tester).resolver.hueTimeOffset, isNot(0)); + // 2.5s: half a second into the rest after the first sweep. + await runFor(tester, const Duration(milliseconds: 2500)); + expect(_now(tester).fadeOpacity, 0); - // The group owns the clock, so the member is never told to restart — - // it has to hear it from the clock itself. await tester.pumpWidget( - build(cycle: const Duration(seconds: 4), active: false), + beam(const BeamTiming(cycle: Duration(seconds: 4), cycleGap: gap)), ); + final resting = _now(tester); + expect(resting.fadeOpacity, 0); + expect(resting.travelProgress, 1); + + // The same half second of rest remains before the next sweep. await tester.pump(const Duration(milliseconds: 600)); - await tester.pumpWidget( - build(cycle: const Duration(seconds: 4), active: true), - ); - final restarted = _painter(tester); - expect(restarted.clock.elapsedSeconds, closeTo(0, 1e-9)); - expect(restarted.resolver.hueTimeOffset, 0); - expect(restarted.resolver.breatheTimeOffset, 0); + final next = _now(tester); + expect(next.travelProgress, closeTo(0.1 / 4, 1e-9)); + expect(next.fadeOpacity, 1); }); - testWidgets('a variant change rebuilds the clock and drops corrections', ( + testWidgets('a phase-offset beam resting in the gap stays in the gap', ( tester, ) async { - Widget build({ - required BeamVariant variant, - required Duration cycle, - bool active = true, - }) => _host( - BorderBeam( - variant: variant, - active: active, - timing: BeamTiming( - cycle: cycle, - cycleGap: const Duration(seconds: 1), - ), - child: const SizedBox.expand(), - ), + BeamTiming timing(Duration cycle) => BeamTiming( + cycle: cycle, + cycleGap: const Duration(seconds: 1), + phaseOffset: 0.5, ); - await tester.pumpWidget( - build(variant: BeamVariant.line, cycle: const Duration(seconds: 2)), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 2500)); - await tester.pumpWidget( - build(variant: BeamVariant.line, cycle: const Duration(seconds: 4)), - ); - final retimed = _painter(tester); - expect(retimed.resolver.hueTimeOffset, isNot(0)); - expect(retimed.resolver.breatheTimeOffset, isNot(0)); - - // The fps cap is variant-bound, so this swaps the clock out from under - // the beam — a new timeline at zero, and no reset the old clock could - // have announced. - await tester.pumpWidget( - build(variant: BeamVariant.rotate, cycle: const Duration(seconds: 4)), - ); - final swapped = _painter(tester); - expect(swapped.clock, isNot(same(retimed.clock))); - expect(swapped.clock.elapsedSeconds, closeTo(0, 1e-9)); - expect(swapped.resolver.hueTimeOffset, 0); - expect(swapped.resolver.breatheTimeOffset, 0); - expect(swapped.resolver.travelTimeOffset, 0); - - // The replacement clock is bound too, so a restart on *it* clears the - // corrections it accumulated after the swap. Retime again to put some - // there — the offsets are 0 right now, so a restart would prove - // nothing without this. From inside the gap, so the target is not a - // pure rescale and the breathe correction is non-zero as well. - await tester.pump(const Duration(milliseconds: 4500)); - await tester.pumpWidget( - build(variant: BeamVariant.rotate, cycle: const Duration(seconds: 8)), - ); - final again = _painter(tester); - expect(again.clock, same(swapped.clock)); - expect(again.resolver.hueTimeOffset, isNot(0)); - expect(again.resolver.breatheTimeOffset, isNot(0)); + // cycle 2 + gap 1 with a half-cycle offset: at 1.5s elapsed the beam is + // 2.5s into its own 3s period — half a second into the rest. + await tester.pumpWidget(beam(timing(const Duration(seconds: 2)))); + await runFor(tester, const Duration(milliseconds: 1500)); + expect(_now(tester).fadeOpacity, 0); - await tester.pumpWidget( - build( - variant: BeamVariant.rotate, - cycle: const Duration(seconds: 8), - active: false, - ), + await tester.pumpWidget(beam(timing(const Duration(seconds: 4)))); + final phases = _now(tester); + expect( + phases.fadeOpacity, + 0, + reason: 'the raw timeline says mid-sweep; the shifted one says rest', ); - await tester.pump(const Duration(milliseconds: 600)); - expect(again.clock.isVisible, isFalse); - expect(again.resolver.hueTimeOffset, 0); - expect(again.resolver.breatheTimeOffset, 0); + expect(phases.travelProgress, 1); }); - testWidgets('a reduced-motion variant swap clears them without a restart', ( + testWidgets('a restart drops the corrections a retime left', ( tester, ) async { - Widget build({ - required BeamVariant variant, - required Duration cycle, - bool reduced = false, - }) => _host( - disableAnimations: reduced, - BorderBeam( - variant: variant, - timing: BeamTiming( - cycle: cycle, - cycleGap: const Duration(seconds: 1), - ), - child: const SizedBox.expand(), - ), - ); - - // Accumulate the corrections while the beam is genuinely running: a - // beam that starts under reduced motion never activates its clock, so - // it never retimes either. - await tester.pumpWidget( - build(variant: BeamVariant.line, cycle: const Duration(seconds: 2)), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 2500)); - await tester.pumpWidget( - build(variant: BeamVariant.line, cycle: const Duration(seconds: 4)), - ); - expect(_painter(tester).resolver.breatheTimeOffset, isNot(0)); + const gap = Duration(seconds: 1); + const two = BeamTiming(cycle: Duration(seconds: 2), cycleGap: gap); + const four = BeamTiming(cycle: Duration(seconds: 4), cycleGap: gap); + await tester.pumpWidget(beam(two)); + // From inside the rest, so the retime is not a pure rescale. + await runFor(tester, const Duration(milliseconds: 2500)); + await tester.pumpWidget(beam(four)); + final retimed = _painter(tester).resolver; + expect(retimed.hueTimeOffset, isNot(0)); + expect(retimed.breatheTimeOffset, isNot(0)); + + await tester.pumpWidget(beam(four, active: false)); + await tester.pump(const Duration(milliseconds: 600)); + await tester.pumpWidget(beam(four)); + final restarted = _painter(tester); + expect(restarted.clock.elapsedSeconds, 0); + expect(restarted.resolver.hueTimeOffset, 0); + expect(restarted.resolver.breatheTimeOffset, 0); + expect(restarted.resolver.travelTimeOffset, 0); + }); + }); - // Now freeze it. The clock stays visible and the corrections stay - // valid for the clock they describe. + group('repeat', () { + testWidgets('a cycle counts its rest', (tester) async { await tester.pumpWidget( - build( - variant: BeamVariant.line, - cycle: const Duration(seconds: 4), - reduced: true, + _host( + const BorderBeam( + timing: oneAndOne, + playback: BeamPlayback(repeat: BeamRepeat.once()), + child: SizedBox.expand(), + ), ), ); - expect(_painter(tester).staticMode, isTrue); - - // The static frame samples the resolver, so a stale correction shows. - // Nothing restarts the replacement clock here — reduced motion keeps - // _start() out — so the clear has to happen when the clock is built. - await tester.pumpWidget( - build( - variant: BeamVariant.rotate, - cycle: const Duration(seconds: 4), - reduced: true, - ), + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1500)); + final clock = _painter(tester).clock; + expect( + clock.stage, + isNot(BeamFadeStage.fadingOut), + reason: 'the rest is part of the cycle', ); - final swapped = _painter(tester); - expect(swapped.staticMode, isTrue); - expect(swapped.resolver.breatheTimeOffset, 0); - expect(swapped.resolver.travelTimeOffset, 0); - expect(swapped.resolver.hueTimeOffset, 0); + await tester.pump(const Duration(milliseconds: 550)); + expect(clock.stage, BeamFadeStage.fadingOut); }); - testWidgets('changing a track period re-phases only that track', ( - tester, - ) async { - Widget build(double breatheFactor) => _host( - BorderBeam.line( - timing: BeamTiming( - cycle: const Duration(seconds: 2), - breatheFactor: breatheFactor, + testWidgets('count(2) runs two sweeps and their rests', (tester) async { + await tester.pumpWidget( + _host( + const BorderBeam( + timing: oneAndOne, + playback: BeamPlayback(repeat: BeamRepeat.count(2)), + child: SizedBox.expand(), ), - child: const SizedBox.expand(), ), ); - - await tester.pumpWidget(build(1.3)); await tester.pump(); - await tester.pump(const Duration(milliseconds: 900)); - final before = _painter(tester); - final was = before.resolver.sample(before.clock.elapsedSeconds, 1); - - // Documented contract: a period change re-phases its own track and - // leaves the timeline — and therefore every other track — alone. - await tester.pumpWidget(build(2.6)); - final after = _painter(tester); - expect(after.clock.elapsedSeconds, closeTo(0.9, 1e-9)); - final now = after.resolver.sample(after.clock.elapsedSeconds, 1); - expect(now.travelProgress, closeTo(was.travelProgress, 1e-9)); - expect(now.spike, closeTo(was.spike, 1e-9)); - expect(now.spike2, closeTo(was.spike2, 1e-9)); - expect(now.lineH, isNot(closeTo(was.lineH, 1e-6))); + await tester.pump(const Duration(milliseconds: 3950)); + final clock = _painter(tester).clock; + expect(clock.stage, isNot(BeamFadeStage.fadingOut)); + await tester.pump(const Duration(milliseconds: 100)); + expect(clock.stage, BeamFadeStage.fadingOut); + await tester.pump(const Duration(milliseconds: 600)); + expect(clock.isVisible, isFalse); + expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('adding a gap to a running beam needs no retime either', ( - tester, - ) async { - Widget build(Duration gap) => _host( - BorderBeam.rotate( - timing: BeamTiming(cycle: const Duration(seconds: 2), cycleGap: gap), - child: const SizedBox.expand(), + testWidgets('an ambient budget counts cycles alone', (tester) async { + await tester.pumpWidget( + _host( + const BorderBeam( + effect: BeamEffect.pulse(), + timing: oneAndOne, + playback: BeamPlayback(repeat: BeamRepeat.once()), + child: SizedBox.expand(), + ), ), ); - - await tester.pumpWidget(build(Duration.zero)); await tester.pump(); - await tester.pump(const Duration(milliseconds: 900)); - await tester.pumpWidget(build(const Duration(seconds: 1))); - expect(_painter(tester).clock.elapsedSeconds, closeTo(0.9, 1e-9)); - }); - }); - - group('the gap envelope', () { - // cycle 1s + gap 1s: the fade at each end is min(0.25, gap / 2) = 0.25s, - // and it is a smoothstep, so a quarter into the fade is 0.15625 and half - // way is exactly 0.5. - final resolver = _direct( - cycle: const Duration(seconds: 1), - gap: const Duration(seconds: 1), - ); - - test('it holds at 1 until the sweep ends', () { - expect(resolver.sample(0.999, 1).fadeOpacity, 1); - expect(resolver.sample(1, 1).fadeOpacity, closeTo(1, 1e-9)); - }); - - test('it eases 1 to 0 over the first quarter second of the rest', () { - expect(resolver.sample(1.0625, 1).fadeOpacity, closeTo(0.84375, 1e-9)); - expect(resolver.sample(1.125, 1).fadeOpacity, closeTo(0.5, 1e-9)); - expect(resolver.sample(1.1875, 1).fadeOpacity, closeTo(0.15625, 1e-9)); - expect(resolver.sample(1.25, 1).fadeOpacity, closeTo(0, 1e-9)); - }); - - test('it stays at 0 through the middle of the rest', () { - for (final t in [1.25, 1.4, 1.5, 1.6, 1.75]) { - expect(resolver.sample(t, 1).fadeOpacity, 0, reason: 't=$t'); - } - }); - - test('it eases 0 back to 1 over the last quarter second', () { - expect(resolver.sample(1.8125, 1).fadeOpacity, closeTo(0.15625, 1e-9)); - expect(resolver.sample(1.875, 1).fadeOpacity, closeTo(0.5, 1e-9)); - expect(resolver.sample(1.9375, 1).fadeOpacity, closeTo(0.84375, 1e-9)); - expect(resolver.sample(2, 1).fadeOpacity, closeTo(1, 1e-9)); - }); - - test('a 100ms gap fades for 50ms at each side', () { - final short = _direct( - cycle: const Duration(seconds: 1), - gap: const Duration(milliseconds: 100), - ); - expect(short.sample(1, 1).fadeOpacity, closeTo(1, 1e-9)); - expect(short.sample(1.025, 1).fadeOpacity, closeTo(0.5, 1e-9)); - expect( - short.sample(1.05, 1).fadeOpacity, - closeTo(0, 1e-9), - reason: 'the two fades meet in the middle, with no flat rest', - ); - expect(short.sample(1.075, 1).fadeOpacity, closeTo(0.5, 1e-9)); - expect(short.sample(1.1, 1).fadeOpacity, closeTo(1, 1e-9)); - }); - - test('it multiplies the beam own fade rather than replacing it', () { - expect(resolver.sample(1.125, 0.5).fadeOpacity, closeTo(0.25, 1e-9)); - expect(resolver.sample(0.5, 0.5).fadeOpacity, closeTo(0.5, 1e-9)); - }); - - test('the envelope repeats every cycle + gap', () { - for (final t in [0.3, 1.1, 1.5, 1.9]) { - expect( - resolver.sample(t + 2, 1).fadeOpacity, - closeTo(resolver.sample(t, 1).fadeOpacity, 1e-9), - reason: 't=$t', - ); - } + await tester.pump(const Duration(milliseconds: 1050)); + expect(_painter(tester).clock.stage, BeamFadeStage.fadingOut); }); }); - - group('the pulse variants ignore the gap', () { - for (final variant in [BeamVariant.pulseInside, BeamVariant.pulseOutside]) { - test('$variant breathes straight through it', () { - final gapped = _direct( - cycle: const Duration(seconds: 2), - gap: const Duration(seconds: 1), - variant: variant, - ); - final plain = _direct( - cycle: const Duration(seconds: 2), - gap: Duration.zero, - variant: variant, - ); - expect(gapped.config.gapSeconds, closeTo(1, 1e-9)); - - for (final t in [0.5, 2.0, 2.5, 3.0, 5.7]) { - final a = gapped.sample(t, 1); - final b = plain.sample(t, 1); - expect(a.fadeOpacity, 1, reason: 'no gap envelope at t=$t'); - expect(a.hueDegrees, closeTo(b.hueDegrees, 1e-9), reason: 't=$t'); - for (var i = 0; i < 3; i++) { - expect(a.pulse.bw[i], closeTo(b.pulse.bw[i], 1e-9), reason: 't=$t'); - expect(a.pulse.bh[i], closeTo(b.pulse.bh[i], 1e-9), reason: 't=$t'); - expect(a.pulse.bx[i], closeTo(b.pulse.bx[i], 1e-9), reason: 't=$t'); - expect(a.pulse.by[i], closeTo(b.pulse.by[i], 1e-9), reason: 't=$t'); - } - expect(a.pulse.bgh, closeTo(b.pulse.bgh, 1e-9), reason: 't=$t'); - expect(a.pulse.bopTl, closeTo(b.pulse.bopTl, 1e-9), reason: 't=$t'); - expect(a.pulse.bopBr, closeTo(b.pulse.bopBr, 1e-9), reason: 't=$t'); - } - }); - - test('$variant passes the beam fade straight through', () { - final gapped = _direct( - cycle: const Duration(seconds: 2), - gap: const Duration(seconds: 1), - variant: variant, - ); - expect(gapped.sample(2.5, 0.4).fadeOpacity, 0.4); - }); - } - }); } diff --git a/test/widget/border_beam_lifecycle_test.dart b/test/widget/border_beam_lifecycle_test.dart index e4fb865..f1dda84 100644 --- a/test/widget/border_beam_lifecycle_test.dart +++ b/test/widget/border_beam_lifecycle_test.dart @@ -1,78 +1,41 @@ -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -/// Lifecycle coverage for the widget's one-ticker-per-beam contract: every -/// path that ends a beam — disposal mid-fade, a variant swap that rebuilds -/// the clock, `TickerMode`, controller detach — must leave no scheduled -/// frame callback behind. -void main() { - Widget host(Widget child, {bool disableAnimations = false}) => MaterialApp( - theme: ThemeData(brightness: Brightness.dark), - builder: (context, app) => MediaQuery( - data: MediaQuery.of( - context, - ).copyWith(disableAnimations: disableAnimations), - child: app!, - ), - home: Scaffold( - body: Center(child: SizedBox(width: 350, height: 140, child: child)), - ), - ); +import 'test_utils.dart'; - Widget beamFor( - BeamVariant variant, { +/// The one-ticker-per-beam contract: every path that ends a beam — disposal +/// mid-fade, an effect swap, `TickerMode`, a controller that outlives its +/// beam, a pending start delay — must leave no frame callback behind. +void main() { + Widget beam( + BeamEffect effect, { bool active = true, - Widget child = const SizedBox.expand(), - VoidCallback? onActivate, BorderBeamController? controller, - }) => switch (variant) { - BeamVariant.rotate => BorderBeam.rotate( - active: active, - onActivate: onActivate, - controller: controller, - child: child, - ), - BeamVariant.small => BorderBeam.small( - active: active, - onActivate: onActivate, - controller: controller, - child: child, - ), - BeamVariant.line => BorderBeam.line( - active: active, - onActivate: onActivate, - controller: controller, - child: child, - ), - BeamVariant.pulseInside => BorderBeam.pulseInside( - active: active, - onActivate: onActivate, - controller: controller, - child: child, - ), - BeamVariant.pulseOutside => BorderBeam.pulseOutside( - active: active, - onActivate: onActivate, - controller: controller, - child: child, - ), - }; + VoidCallback? onActivate, + BeamPlayback? playback, + Widget child = const SizedBox.expand(), + }) => BorderBeam( + effect: effect, + active: active, + controller: controller, + onActivate: onActivate, + playback: playback, + child: child, + ); group('disposal', () { - // Pulse variants build their clock with an fps cap, so the tick path - // differs per family — every variant is checked. - for (final variant in BeamVariant.values) { - testWidgets('$variant disposed mid fade-in leaves no ticker', ( + for (final effect in BeamEffect.values) { + testWidgets('${effect.name} disposed mid fade-in leaves no ticker', ( tester, ) async { - await tester.pumpWidget(host(beamFor(variant))); + await tester.pumpWidget(beamHost(beam(effect))); await tester.pump(); // 200ms into the 600ms fade-in. await tester.pump(const Duration(milliseconds: 200)); expect( tester.binding.transientCallbackCount, - greaterThan(0), + 1, reason: 'the beam should be ticking here', ); @@ -81,84 +44,127 @@ void main() { expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('$variant disposed mid fade-out leaves no ticker', ( + testWidgets('${effect.name} disposed mid fade-out leaves no ticker', ( tester, ) async { - await tester.pumpWidget(host(beamFor(variant))); + await tester.pumpWidget(beamHost(beam(effect))); await tester.pump(); await tester.pump(const Duration(milliseconds: 700)); - await tester.pumpWidget(host(beamFor(variant, active: false))); + await tester.pumpWidget(beamHost(beam(effect, active: false))); // 200ms into the 500ms fade-out. await tester.pump(const Duration(milliseconds: 200)); - expect(tester.binding.transientCallbackCount, greaterThan(0)); + expect(beamPainterOf(tester).clock.isVisible, isTrue); + expect(tester.binding.transientCallbackCount, 1); await tester.pumpWidget(const SizedBox()); expect(tester.takeException(), isNull); expect(tester.binding.transientCallbackCount, 0); }); } + + testWidgets('a pending startAfter is cancelled with the beam', ( + tester, + ) async { + await tester.pumpWidget( + beamHost( + beam( + const BeamEffect.rotate(), + playback: const BeamPlayback(startAfter: Duration(seconds: 2)), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pumpWidget(const SizedBox()); + // Stay short of the 2s deadline: a timer the beam failed to cancel is + // still pending when the test ends, and the binding fails the test for + // it. Pumping past the deadline would let it fire into the State's + // `mounted` guard and pass whether or not it was cancelled. + await tester.pump(const Duration(milliseconds: 500)); + expect(tester.takeException(), isNull); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('a reduced-motion static frame disposes without a ticker', ( + tester, + ) async { + await tester.pumpWidget( + beamHost(beam(const BeamEffect.rotate()), disableAnimations: true), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 700)); + expect(tester.binding.transientCallbackCount, 0); + + await tester.pumpWidget(const SizedBox()); + expect(tester.takeException(), isNull); + expect(tester.binding.transientCallbackCount, 0); + }); }); - testWidgets('a variant swap rebuilds the clock without leaking the old one', ( - tester, - ) async { - // rotate runs uncapped, pulseInside caps at the source's ~30fps driver: - // the swap must replace the clock, not keep two of them running. - await tester.pumpWidget(host(beamFor(BeamVariant.rotate))); + testWidgets('an effect swap keeps exactly one ticker', (tester) async { + await tester.pumpWidget(beamHost(beam(const BeamEffect.rotate()))); await tester.pump(); await tester.pump(const Duration(milliseconds: 300)); - await tester.pumpWidget(host(beamFor(BeamVariant.pulseInside))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - expect(tester.takeException(), isNull); - expect( - tester.binding.transientCallbackCount, - 1, - reason: 'exactly one clock ticks after the swap', - ); + for (final effect in BeamEffect.values.reversed) { + await tester.pumpWidget(beamHost(beam(effect))); + await tester.pump(const Duration(milliseconds: 100)); + expect(tester.takeException(), isNull); + expect(beamPainterOf(tester).config.effect, effect); + expect(beamPainterOf(tester).clock.isRunning, isTrue); + expect( + tester.binding.transientCallbackCount, + 1, + reason: 'exactly one clock ticks after swapping to ${effect.name}', + ); + } await tester.pumpWidget(const SizedBox()); expect(tester.takeException(), isNull); expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('TickerMode pauses frames and resumes them', (tester) async { + testWidgets('TickerMode mutes frames and unmuting resumes them', ( + tester, + ) async { var activated = 0; - Widget build(bool enabled) => host( + Widget build(bool enabled) => beamHost( TickerMode( enabled: enabled, - child: beamFor(BeamVariant.rotate, onActivate: () => activated++), + child: beam(const BeamEffect.rotate(), onActivate: () => activated++), ), ); await tester.pumpWidget(build(false)); await tester.pump(const Duration(milliseconds: 800)); - expect(tester.binding.hasScheduledFrame, isFalse); + expect(tester.binding.transientCallbackCount, 0); expect(activated, 0, reason: 'a muted clock never completes its fade-in'); await tester.pumpWidget(build(true)); await tester.pump(); - expect(tester.binding.hasScheduledFrame, isTrue); + expect(tester.binding.transientCallbackCount, 1); await tester.pump(const Duration(milliseconds: 700)); expect(activated, 1); - // Still animating after the fade finished. - expect(tester.binding.hasScheduledFrame, isTrue); + expect(tester.binding.transientCallbackCount, 1, reason: 'still animating'); + + await tester.pumpWidget(build(false)); + expect(tester.binding.transientCallbackCount, 0); + await tester.pumpWidget(const SizedBox()); + expect(tester.takeException(), isNull); + expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('reduced-motion static frames dispose without a ticker', ( + testWidgets('a beam disposed under TickerMode leaves no ticker', ( tester, ) async { await tester.pumpWidget( - host(beamFor(BeamVariant.rotate), disableAnimations: true), + beamHost( + TickerMode(enabled: false, child: beam(const BeamEffect.pulse())), + ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - expect(tester.takeException(), isNull); - expect(tester.binding.transientCallbackCount, 0); - + await tester.pump(const Duration(milliseconds: 300)); await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(milliseconds: 100)); expect(tester.takeException(), isNull); expect(tester.binding.transientCallbackCount, 0); }); @@ -167,8 +173,9 @@ void main() { tester, ) async { final controller = BorderBeamController(); + addTearDown(controller.dispose); await tester.pumpWidget( - host(beamFor(BeamVariant.rotate, controller: controller)), + beamHost(beam(const BeamEffect.rotate(), controller: controller)), ); controller.start(); await tester.pump(); @@ -182,49 +189,96 @@ void main() { expect(controller.isAttached, isFalse); expect(controller.isActive, isFalse); expect(controller.isRunning, isFalse); + expect(tester.binding.transientCallbackCount, 0); - controller.start(); - controller.resume(); - controller.seek(const Duration(seconds: 1)); - controller.speed = 2; - controller.stop(); + controller + ..start() + ..pause() + ..resume() + ..seek(const Duration(seconds: 1)) + ..pulse() + ..flash() + ..speed = 2 + ..stop(); await tester.pump(const Duration(milliseconds: 100)); expect(tester.takeException(), isNull); expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('replacing the child keeps the beam painting', (tester) async { + testWidgets( + 'a controller handed to a new beam in the same frame follows it', + (tester) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + beamHost(beam(const BeamEffect.rotate(), controller: controller)), + ); + // A different parent: the old State is disposed and a new one mounted + // within the one frame. + await tester.pumpWidget( + beamHost( + Padding( + padding: EdgeInsets.zero, + child: beam(const BeamEffect.rotate(), controller: controller), + ), + ), + ); + expect(tester.takeException(), isNull); + controller.start(); + await tester.pump(); + expect(beamPainterOf(tester).clock.isVisible, isTrue); + }, + ); + + testWidgets('a controller moves to a new beam after the old one is gone', ( + tester, + ) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + beamHost(beam(const BeamEffect.rotate(), controller: controller)), + ); + controller.start(); + await tester.pump(); + await tester.pumpWidget(const SizedBox()); + expect(controller.isAttached, isFalse); + + await tester.pumpWidget( + beamHost(beam(const BeamEffect.pulse(), controller: controller)), + ); + expect(controller.isAttached, isTrue); + expect(controller.isActive, isFalse, reason: 'the new beam starts hidden'); + controller.start(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(beamPainterOf(tester).clock.isRunning, isTrue); + expect(tester.binding.transientCallbackCount, 1); + + await tester.pumpWidget(const SizedBox()); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('replacing the child keeps the beam running', (tester) async { Widget build(String label) => - host(beamFor(BeamVariant.rotate, child: Text(label))); + beamHost(beam(const BeamEffect.rotate(), child: Text(label))); await tester.pumpWidget(build('before')); await tester.pump(); await tester.pump(const Duration(milliseconds: 700)); + final clock = beamPainterOf(tester).clock; + final elapsed = clock.elapsedSeconds; await tester.pumpWidget(build('after')); await tester.pump(const Duration(milliseconds: 50)); expect(find.text('before'), findsNothing); expect(find.text('after'), findsOneWidget); expect(tester.takeException(), isNull); - // The clock survives a child swap: no restart, no stall. - expect(tester.binding.hasScheduledFrame, isTrue); - - // The child keeps its own repaint boundary, so beam frames never - // re-rasterize it: one boundary around the CustomPaint, one around the - // child itself. + expect(identical(beamPainterOf(tester).clock, clock), isTrue); expect( - find.descendant( - of: find.byType(BorderBeam), - matching: find.byType(RepaintBoundary), - ), - findsNWidgets(2), - ); - expect( - find.ancestor( - of: find.text('after'), - matching: find.byType(RepaintBoundary), - ), - findsAtLeastNWidgets(2), + clock.elapsedSeconds, + greaterThan(elapsed), + reason: 'no restart, no stall', ); + expect(tester.binding.transientCallbackCount, 1); }); } diff --git a/test/widget/border_beam_test.dart b/test/widget/border_beam_test.dart index e8b5012..d786324 100644 --- a/test/widget/border_beam_test.dart +++ b/test/widget/border_beam_test.dart @@ -1,261 +1,435 @@ -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/animation/beam_clock.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; import 'test_utils.dart'; -Widget _host(Widget child, {bool disableAnimations = false}) => MaterialApp( - theme: ThemeData(brightness: Brightness.dark), - builder: (context, app) => MediaQuery( - data: MediaQuery.of(context).copyWith(disableAnimations: disableAnimations), - child: app!, - ), - home: Scaffold( - body: Center(child: SizedBox(width: 350, height: 140, child: child)), - ), -); - +/// The widget's core contract: it wraps a child it never gets in the way of, +/// paints the effect it is given, starts by itself, and hands playback over +/// wholesale to a [BorderBeamController] when one is attached. void main() { - testWidgets('renders child and animates by default', (tester) async { - await tester.pumpWidget( - _host(const BorderBeam.rotate(child: Text('content'))), - ); - expect(find.text('content'), findsOneWidget); - // The beam is animating: frames keep being scheduled. - await tester.pump(const Duration(milliseconds: 50)); - expect(tester.binding.hasScheduledFrame, isTrue); - }); - - testWidgets('onActivate fires when the fade-in completes', (tester) async { - var activated = 0; - await tester.pumpWidget( - _host( - BorderBeam.rotate( - onActivate: () => activated++, - child: const SizedBox.expand(), - ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - expect(activated, 1); + // The pixel smoke test needs the shader; nothing else here reads pixels. + setUpAll(() async { + await BorderBeam.precache(); }); - testWidgets('active: false stays idle until toggled', (tester) async { - var activated = 0; - var deactivated = 0; - Widget build(bool active) => _host( - BorderBeam.rotate( - active: active, - onActivate: () => activated++, - onDeactivate: () => deactivated++, - child: const SizedBox.expand(), - ), - ); - - await tester.pumpWidget(build(false)); - await tester.pump(const Duration(seconds: 1)); - expect(activated, 0); - expect(tester.binding.hasScheduledFrame, isFalse); + group('rendering', () { + testWidgets('renders its child and animates by default', (tester) async { + await tester.pumpWidget( + beamHost(const BorderBeam(child: Text('content'))), + ); + expect(find.text('content'), findsOneWidget); + await tester.pump(const Duration(milliseconds: 50)); + final clock = beamPainterOf(tester).clock; + expect(clock.isVisible, isTrue); + expect(clock.isRunning, isTrue); + expect(tester.binding.transientCallbackCount, 1, reason: 'one ticker'); + }); - await tester.pumpWidget(build(true)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - expect(activated, 1); + testWidgets('with no effect anywhere it rotates', (tester) async { + await tester.pumpWidget(beamHost(const BorderBeam(child: SizedBox()))); + expect(beamPainterOf(tester).config.effect, const BeamEffect.rotate()); + }); - await tester.pumpWidget(build(false)); - await tester.pump(const Duration(milliseconds: 600)); - expect(deactivated, 1); - // Fade-out finished: animation halts. - await tester.pump(const Duration(milliseconds: 50)); - expect(tester.binding.hasScheduledFrame, isFalse); - }); + for (final effect in BeamEffect.values) { + testWidgets('${effect.name} reaches the painter config', (tester) async { + await tester.pumpWidget( + beamHost(BorderBeam(effect: effect, child: const SizedBox.expand())), + ); + final painter = beamPainterOf(tester); + expect(painter.config.effect, effect); + expect( + identical(painter.resolver.config, painter.config), + isTrue, + reason: 'the resolver samples the config the painter paints', + ); + }); + } - testWidgets('startAfter delays the start', (tester) async { - var activated = 0; - await tester.pumpWidget( - _host( - BorderBeam.rotate( - playback: const BeamPlayback(startAfter: Duration(seconds: 2)), - onActivate: () => activated++, - child: const SizedBox.expand(), + testWidgets('effect parameters reach the config', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeam( + effect: BeamEffect.rotate(count: 3, comet: true), + child: SizedBox.expand(), + ), ), - ), - ); - await tester.pump(const Duration(seconds: 1)); - expect(activated, 0); - expect(tester.binding.hasScheduledFrame, isFalse); - await tester.pump(const Duration(seconds: 1, milliseconds: 100)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - expect(activated, 1); - }); + ); + final config = beamPainterOf(tester).config; + expect(config.effect, const BeamEffect.rotate(count: 3, comet: true)); + expect(config.beamCount, 3); + }); - testWidgets('duration bounds total play time', (tester) async { - var deactivated = 0; - await tester.pumpWidget( - _host( - BorderBeam.rotate( - playback: const BeamPlayback(duration: Duration(seconds: 2)), - onDeactivate: () => deactivated++, - child: const SizedBox.expand(), + testWidgets('pointer events reach the child', (tester) async { + var taps = 0; + await tester.pumpWidget( + beamHost( + BorderBeam( + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => taps++, + child: const SizedBox.expand(), + ), + ), ), - ), - ); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - expect(deactivated, 0); - await tester.pump(const Duration(seconds: 1, milliseconds: 100)); - await tester.pump(const Duration(milliseconds: 600)); - expect(deactivated, 1); - await tester.pump(const Duration(milliseconds: 50)); - expect(tester.binding.hasScheduledFrame, isFalse); - }); + ); + // On the border, where the light is. + await tester.tapAt( + tester.getTopLeft(find.byType(BorderBeam)) + const Offset(2, 2), + ); + await tester.tap(find.byType(BorderBeam)); + expect(taps, 2); + }); - testWidgets('autoPlay: false never starts by itself', (tester) async { - await tester.pumpWidget( - _host( - const BorderBeam.pulseInside( - playback: BeamPlayback(autoPlay: false), - child: SizedBox.expand(), + testWidgets('the child sits behind its own repaint boundary', ( + tester, + ) async { + await tester.pumpWidget( + beamHost(const BorderBeam(child: Text('content'))), + ); + // One boundary around the beam, one around the child, so beam frames + // never re-rasterize the child. + expect( + find.descendant( + of: find.byType(BorderBeam), + matching: find.byType(RepaintBoundary), ), - ), - ); - await tester.pump(const Duration(seconds: 1)); - expect(tester.binding.hasScheduledFrame, isFalse); + findsNWidgets(2), + ); + final childBoundary = find + .ancestor( + of: find.text('content'), + matching: find.byType(RepaintBoundary), + ) + .first; + expect( + find.descendant(of: find.byType(CustomPaint), matching: childBoundary), + findsOneWidget, + reason: 'the child boundary sits inside the beam painter', + ); + }); }); - testWidgets('reduced motion paints a static frame without animating', ( - tester, - ) async { - var activated = 0; - await tester.pumpWidget( - _host( - disableAnimations: true, - BorderBeam.rotate( - onActivate: () => activated++, - child: const SizedBox.expand(), + group('BorderBeam.overlay', () { + testWidgets('is sized by its parent and traces its bounds', (tester) async { + await tester.pumpWidget( + beamHost( + const Stack( + children: [ + SizedBox(width: 300, height: 120, child: Text('content')), + Positioned.fill( + child: BorderBeam.overlay( + effect: BeamEffect.line(edge: BeamEdge.top), + colors: BeamColors.ocean, + borderRadius: 12, + ), + ), + ], + ), ), - ), - ); - await tester.pump(const Duration(seconds: 1)); - expect(tester.binding.hasScheduledFrame, isFalse); - expect(activated, 0); - expect(tester.takeException(), isNull); + ); + expect(find.text('content'), findsOneWidget); + expect(tester.getSize(find.byType(BorderBeam)), const Size(350, 140)); + final painter = beamPainterOf(tester); + expect(painter.config.effect, const BeamEffect.line(edge: BeamEdge.top)); + expect(painter.config.palette, BeamColors.ocean.resolve()); + expect(painter.config.borderRadius, BorderRadius.circular(12)); + await tester.pump(const Duration(milliseconds: 50)); + expect(painter.clock.isRunning, isTrue); + }); + + testWidgets('forwards its playback arguments', (tester) async { + await tester.pumpWidget( + beamHost(const BorderBeam.overlay(active: false)), + ); + await tester.pump(const Duration(milliseconds: 200)); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + expect(tester.binding.transientCallbackCount, 0); + }); }); - testWidgets('TickerMode disabled pauses the beam', (tester) async { - await tester.pumpWidget( - _host( - const TickerMode( - enabled: false, - child: BorderBeam.rotate(child: SizedBox.expand()), - ), + group('pixels', () { + const surface = Color(0xFF101010); + + Widget card({bool active = true}) => beamHost( + BorderBeam( + active: active, + child: const ColoredBox(color: surface, child: SizedBox.expand()), ), ); - await tester.pump(const Duration(milliseconds: 100)); - expect(tester.binding.hasScheduledFrame, isFalse); + + testWidgets('a running beam lights pixels over its child', (tester) async { + await tester.pumpWidget(card()); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1300)); + final pixels = await beamPixels(tester); + expect(pixels.width, 350); + expect(pixels.height, 140); + expect( + pixels.countDifferentFrom(surface), + greaterThan(100), + reason: 'the beam paints over the child', + ); + }); + + testWidgets('an inactive beam leaves the child untouched', (tester) async { + await tester.pumpWidget(card(active: false)); + await tester.pump(const Duration(milliseconds: 1300)); + final pixels = await beamPixels(tester); + expect(pixels.countDifferentFrom(surface), 0); + }); }); group('controller', () { - testWidgets('asserts when startAfter is set with a controller', ( - tester, - ) async { - final controller = BorderBeamController(); - addTearDown(controller.dispose); - await pumpExpectingAssertion( + for (final (name, playback) in [ + ('startAfter', const BeamPlayback(startAfter: Duration(seconds: 1))), + ('duration', const BeamPlayback(duration: Duration(seconds: 1))), + ]) { + testWidgets('asserts when $name is set with a controller', ( tester, - _host( - BorderBeam.rotate( - controller: controller, - playback: const BeamPlayback(startAfter: Duration(seconds: 1)), - child: const SizedBox.expand(), + ) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + await pumpExpectingAssertion( + tester, + beamHost( + BorderBeam( + controller: controller, + playback: playback, + child: const SizedBox.expand(), + ), ), - ), - message: 'When a BorderBeamController is attached it owns playback', - ); - }); + message: 'When a BorderBeamController is attached it owns playback', + ); + }); + } - testWidgets('asserts when duration is set with a controller', ( + testWidgets('asserts when one controller drives two beams at once', ( tester, ) async { + // A controller starts its beam hidden, so neither beam starts a ticker + // that could outlive the failed build. final controller = BorderBeamController(); addTearDown(controller.dispose); await pumpExpectingAssertion( tester, - _host( - BorderBeam.rotate( - controller: controller, - playback: const BeamPlayback(duration: Duration(seconds: 1)), - child: const SizedBox.expand(), + beamHost( + Column( + children: [ + for (var i = 0; i < 2; i++) + Expanded( + child: BorderBeam( + controller: controller, + child: const SizedBox.expand(), + ), + ), + ], ), ), - message: 'When a BorderBeamController is attached it owns playback', + message: 'already attached to another BorderBeam', ); }); - testWidgets('controller owns playback end to end', (tester) async { + testWidgets('owns playback end to end', (tester) async { final controller = BorderBeamController(); + addTearDown(controller.dispose); var activated = 0; var deactivated = 0; await tester.pumpWidget( - _host( - BorderBeam.pulseOutside( + beamHost( + BorderBeam( + effect: const BeamEffect.rotate(count: 2), controller: controller, onActivate: () => activated++, onDeactivate: () => deactivated++, - child: const ColoredBox(color: Color(0xFF1D1D1D)), + child: const SizedBox.expand(), ), ), ); - // With a controller the beam starts hidden, despite active default. + expect(controller.isAttached, isTrue); + // With a controller the beam starts hidden, despite `active` defaulting + // to true. await tester.pump(const Duration(milliseconds: 300)); expect(controller.isActive, isFalse); - expect(tester.binding.hasScheduledFrame, isFalse); + expect(tester.binding.transientCallbackCount, 0); controller.start(); expect(controller.isActive, isTrue); await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); + await tester.pump(pastFadeIn); expect(activated, 1); expect(controller.isRunning, isTrue); + final clock = beamPainterOf(tester).clock; controller.pause(); - await tester.pump(const Duration(milliseconds: 50)); + final held = clock.elapsedSeconds; + await tester.pump(const Duration(milliseconds: 200)); expect(controller.isRunning, isFalse); expect(controller.isActive, isTrue, reason: 'paused but still visible'); - expect(tester.binding.hasScheduledFrame, isFalse); + expect(clock.elapsedSeconds, held, reason: 'the frame is held'); + expect(tester.binding.transientCallbackCount, 0); + + controller.seek(const Duration(milliseconds: 1500)); + expect(clock.elapsedSeconds, closeTo(1.5, 1e-9)); controller.resume(); - await tester.pump(const Duration(milliseconds: 50)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); expect(controller.isRunning, isTrue); - - controller.speed = 3; - expect(controller.speed, 3); + expect( + clock.elapsedSeconds, + closeTo(1.6, 1e-9), + reason: 'the timeline carries on from the seek', + ); controller.stop(); - await tester.pump(const Duration(milliseconds: 600)); + await tester.pump(pastFadeOut); expect(deactivated, 1); expect(controller.isActive, isFalse); expect(controller.isRunning, isFalse); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('start resumes a paused beam from its held frame', ( + tester, + ) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + beamHost( + BorderBeam(controller: controller, child: const SizedBox.expand()), + ), + ); + controller.start(); + await tester.pump(); + await tester.pump(pastFadeIn); + controller.pause(); + final clock = beamPainterOf(tester).clock; + final held = clock.elapsedSeconds; + await tester.pump(const Duration(milliseconds: 200)); + expect(controller.isRunning, isFalse); + + controller.start(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(controller.isRunning, isTrue); + expect( + clock.elapsedSeconds, + closeTo(held + 0.1, 1e-9), + reason: 'the timeline carries on rather than restarting', + ); + expect(clock.fadeOpacity, 1, reason: 'no fade replays'); + + // On a running beam it changes nothing. + controller.start(); + await tester.pump(const Duration(milliseconds: 100)); + expect(clock.elapsedSeconds, closeTo(held + 0.2, 1e-9)); + }); + + testWidgets('ignores the active shorthand', (tester) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + Widget build(bool active) => beamHost( + BorderBeam( + controller: controller, + active: active, + child: const SizedBox.expand(), + ), + ); + + await tester.pumpWidget(build(true)); + await tester.pump(const Duration(milliseconds: 100)); + expect(controller.isActive, isFalse); + + controller.start(); + await tester.pump(); + await tester.pumpWidget(build(false)); + await tester.pump(pastFadeIn); + expect(controller.isActive, isTrue, reason: 'the controller owns it'); }); testWidgets('detaches cleanly on dispose', (tester) async { final controller = BorderBeamController(); + addTearDown(controller.dispose); await tester.pumpWidget( - _host( - BorderBeam.rotate( - controller: controller, - child: const SizedBox.expand(), - ), + beamHost( + BorderBeam(controller: controller, child: const SizedBox.expand()), ), ); expect(controller.isAttached, isTrue); await tester.pumpWidget(const SizedBox()); expect(controller.isAttached, isFalse); // Controls on a detached controller are safe no-ops. - controller.start(); - controller.stop(); + controller + ..start() + ..pause() + ..resume() + ..stop(); + await tester.pump(const Duration(milliseconds: 100)); + expect(controller.isActive, isFalse); + expect(tester.takeException(), isNull); + expect(tester.binding.transientCallbackCount, 0); }); + + testWidgets('notifies its listeners once per playback command', ( + tester, + ) async { + // It is a ChangeNotifier so play/pause UI can follow it with a + // ListenableBuilder: every command that changes playback says so. + final controller = BorderBeamController(); + addTearDown(controller.dispose); + var notifications = 0; + controller.addListener(() => notifications++); + await tester.pumpWidget( + beamHost( + BorderBeam(controller: controller, child: const SizedBox.expand()), + ), + ); + expect(notifications, 0, reason: 'attaching is not a command'); + + for (final (name, command) in <(String, VoidCallback)>[ + ('start', controller.start), + ('pulse', controller.pulse), + ('flash', controller.flash), + ('pause', controller.pause), + ('resume', controller.resume), + ('seek', () => controller.seek(const Duration(seconds: 1))), + ('speed', () => controller.speed = 2), + ('stop', controller.stop), + ]) { + final before = notifications; + command(); + expect(notifications, before + 1, reason: name); + await tester.pump(const Duration(milliseconds: 50)); + } + + await tester.pump(const Duration(seconds: 1)); + expect(controller.isActive, isFalse); + expect(tester.binding.transientCallbackCount, 0); + }); + }); + + testWidgets('the clock fades in over its documented window', (tester) async { + // The fade lengths are public API (BeamClock.fadeInSeconds), so this + // checks the widget wires the clock rather than restating the number. + var activated = 0; + await tester.pumpWidget( + beamHost( + BorderBeam( + onActivate: () => activated++, + child: const SizedBox.expand(), + ), + ), + ); + await tester.pump(); + final fadeIn = Duration( + microseconds: (BeamClock.fadeInSeconds * 1e6).round(), + ); + await tester.pump(fadeIn - const Duration(milliseconds: 20)); + expect(activated, 0); + expect(beamPainterOf(tester).clock.stage, BeamFadeStage.fadingIn); + await tester.pump(const Duration(milliseconds: 40)); + expect(activated, 1); }); } diff --git a/test/widget/border_beam_theme_test.dart b/test/widget/border_beam_theme_test.dart index 1262f70..54aec04 100644 --- a/test/widget/border_beam_theme_test.dart +++ b/test/widget/border_beam_theme_test.dart @@ -1,173 +1,416 @@ -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; -import 'package:flutter_border_beam/src/animation/beam_clock.dart'; -import 'package:flutter_border_beam/src/models/beam_config.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; import 'test_utils.dart'; -Widget _host(Widget child, {bool disableAnimations = false}) => MaterialApp( - theme: ThemeData(brightness: Brightness.dark), - builder: (context, app) => MediaQuery( - data: MediaQuery.of(context).copyWith(disableAnimations: disableAnimations), - child: app!, - ), - home: Scaffold( - body: Center(child: SizedBox(width: 350, height: 140, child: child)), - ), -); - -BeamPainter _painter(WidgetTester tester) => tester - .widgetList( - find.descendant( - of: find.byType(BorderBeam), - matching: find.byType(CustomPaint), - ), - ) - .expand((paint) => [paint.painter, paint.foregroundPainter]) - .whereType() - .first; - -BeamConfig _config(WidgetTester tester) => _painter(tester).config; - -BeamClock _clock(WidgetTester tester) => _painter(tester).clock; - /// A field left null on a beam falls through to the nearest -/// [BorderBeamTheme], then to the variant preset; a value set on the beam -/// always wins. +/// [BorderBeamTheme] (themes merged outside-in), then to the effect's +/// default; a value set on the beam always wins. void main() { - testWidgets('a theme supplies defaults the beam leaves null', (tester) async { - await tester.pumpWidget( - _host( - const BorderBeamTheme( - data: BorderBeamThemeData( - style: BeamStyle(colors: BeamColors.ocean, strength: 0.4), - shape: BeamShape(borderWidth: 3), - timing: BeamTiming(cycle: Duration(seconds: 4)), - ), - child: BorderBeam.rotate(child: SizedBox.expand()), - ), - ), + group('BorderBeamThemeData', () { + const full = BorderBeamThemeData( + effect: BeamEffect.pulse(), + style: BeamStyle(colors: BeamColors.ocean, strength: 0.5), + shape: BeamShape(borderWidth: 2), + timing: BeamTiming(cycle: Duration(seconds: 3)), + playback: BeamPlayback(autoPlay: false), ); - final config = _config(tester); - expect(identical(config.palette, BeamColors.ocean.resolve()), isTrue); - expect(config.strength, 0.4); - expect(config.borderWidth, 3); - expect(config.cycleSeconds, closeTo(4, 1e-9)); - }); - testWidgets('a shorthand on the beam wins over the theme', (tester) async { - await tester.pumpWidget( - _host( - const BorderBeamTheme( - data: BorderBeamThemeData(style: BeamStyle(colors: BeamColors.ocean)), - child: BorderBeam.rotate( - colors: BeamColors.sunset, - child: SizedBox.expand(), - ), + test('copyWith replaces the given slots and keeps the rest', () { + final copy = full.copyWith( + effect: const BeamEffect.rotate(count: 2), + shape: const BeamShape(superellipse: true), + ); + expect(copy.effect, const BeamEffect.rotate(count: 2)); + expect(copy.shape, const BeamShape(superellipse: true)); + expect(copy.style, full.style); + expect(copy.timing, full.timing); + expect(copy.playback, full.playback); + expect(full.copyWith(), full); + }); + + test('merge layers the other data over this one, field by field', () { + const over = BorderBeamThemeData( + style: BeamStyle(strength: 0.9), + shape: BeamShape(superellipse: true), + ); + final merged = full.merge(over); + expect(merged.effect, const BeamEffect.pulse(), reason: 'not set over'); + expect( + merged.style, + const BeamStyle(colors: BeamColors.ocean, strength: 0.9), + reason: 'value objects merge field by field', + ); + expect(merged.shape, const BeamShape(borderWidth: 2, superellipse: true)); + expect(merged.timing, full.timing); + expect(merged.playback, full.playback); + }); + + test('merge replaces the effect whole', () { + final merged = const BorderBeamThemeData( + effect: BeamEffect.rotate(count: 2, comet: true), + ).merge(const BorderBeamThemeData(effect: BeamEffect.rotate())); + expect(merged.effect, const BeamEffect.rotate()); + }); + + test('merge fills slots this data leaves empty', () { + final merged = const BorderBeamThemeData().merge(full); + expect(merged, full); + }); + + test('merging null is the identity', () { + expect(identical(full.merge(null), full), isTrue); + }); + + test('== and hashCode follow the slots', () { + // Every slot is built at run time, so each one's own `==` and + // `hashCode` run rather than an `identical` short-cut on a canonical + // const. + final same = BorderBeamThemeData( + effect: PulseEffect(), + style: BeamStyle( + colors: BeamColors.ocean, + strength: double.parse('0.5'), ), - ), - ); - expect( - identical(_config(tester).palette, BeamColors.sunset.resolve()), - isTrue, - ); + shape: BeamShape(borderWidth: double.parse('2')), + timing: BeamTiming(cycle: Duration(seconds: int.parse('3'))), + playback: BeamPlayback(autoPlay: bool.parse('false')), + ); + expect(identical(same.style, full.style), isFalse); + expect(same, full); + expect(same.hashCode, full.hashCode); + expect( + full.copyWith(effect: const BeamEffect.rotate(count: 2)), + isNot(full), + ); + expect( + full.copyWith(timing: const BeamTiming(cycle: Duration(seconds: 4))), + isNot(full), + ); + expect(const BorderBeamThemeData(), const BorderBeamThemeData()); + }); + + test('toString names every slot', () { + final text = full.toString(); + for (final slot in ['effect', 'style', 'shape', 'timing', 'playback']) { + expect(text, contains('$slot:')); + } + expect(text, contains('pulse')); + }); }); - testWidgets('nested themes merge, inner over outer', (tester) async { - await tester.pumpWidget( - _host( - const BorderBeamTheme( - data: BorderBeamThemeData( + group('lookup', () { + testWidgets('of is empty and maybeOf null without a theme', (tester) async { + late BorderBeamThemeData data; + late BorderBeamThemeData? maybe; + await tester.pumpWidget( + Builder( + builder: (context) { + data = BorderBeamTheme.of(context); + maybe = BorderBeamTheme.maybeOf(context); + return const SizedBox(); + }, + ), + ); + expect(data, const BorderBeamThemeData()); + expect(maybe, isNull); + }); + + testWidgets('nested themes merge outside-in', (tester) async { + late BorderBeamThemeData data; + await tester.pumpWidget( + BorderBeamTheme( + data: const BorderBeamThemeData( + effect: BeamEffect.pulse(), style: BeamStyle(colors: BeamColors.ocean, strength: 0.5), - shape: BeamShape(borderWidth: 2), ), child: BorderBeamTheme( - data: BorderBeamThemeData(style: BeamStyle(strength: 0.9)), - child: BorderBeam.rotate(child: SizedBox.expand()), + data: const BorderBeamThemeData(style: BeamStyle(strength: 0.8)), + child: BorderBeamTheme( + data: const BorderBeamThemeData( + effect: BeamEffect.rotate(count: 2), + ), + child: Builder( + builder: (context) { + data = BorderBeamTheme.of(context); + return const SizedBox(); + }, + ), + ), ), ), - ), - ); - final config = _config(tester); - expect( - identical(config.palette, BeamColors.ocean.resolve()), - isTrue, - reason: 'the outer theme still supplies colors', - ); - expect(config.strength, 0.9, reason: 'the inner theme wins'); - expect(config.borderWidth, 2, reason: 'slots the inner theme omits'); + ); + expect( + data.effect, + const BeamEffect.rotate(count: 2), + reason: 'innermost wins', + ); + expect( + data.style, + const BeamStyle(colors: BeamColors.ocean, strength: 0.8), + ); + }); }); - testWidgets('changing an outer theme rebuilds beams under an inner one', ( - tester, - ) async { - Widget build(BeamColors colors) => _host( - BorderBeamTheme( - data: BorderBeamThemeData(style: BeamStyle(colors: colors)), - child: const BorderBeamTheme( - data: BorderBeamThemeData(style: BeamStyle(strength: 0.7)), - child: BorderBeam.rotate(child: SizedBox.expand()), + group('inheritance through a beam', () { + testWidgets('a theme supplies the fields the beam leaves null', ( + tester, + ) async { + await tester.pumpWidget( + beamHost( + const BorderBeamTheme( + data: BorderBeamThemeData( + style: BeamStyle(colors: BeamColors.ocean, strength: 0.4), + shape: BeamShape(borderWidth: 3), + timing: BeamTiming(cycle: Duration(seconds: 4)), + ), + child: BorderBeam(child: SizedBox.expand()), + ), ), - ), - ); + ); + final config = beamPainterOf(tester).config; + expect(config.palette, BeamColors.ocean.resolve()); + expect(config.strength, 0.4); + expect(config.borderWidth, 3); + expect(config.cycleSeconds, closeTo(4, 1e-9)); + }); - await tester.pumpWidget(build(BeamColors.ocean)); - expect( - identical(_config(tester).palette, BeamColors.ocean.resolve()), - isTrue, - ); + testWidgets('a beam field wins over the theme, field by field', ( + tester, + ) async { + await tester.pumpWidget( + beamHost( + const BorderBeamTheme( + data: BorderBeamThemeData( + style: BeamStyle(colors: BeamColors.ocean, strength: 0.4), + timing: BeamTiming( + cycle: Duration(seconds: 4), + direction: BeamDirection.reverse, + ), + ), + child: BorderBeam( + style: BeamStyle(strength: 0.7), + timing: BeamTiming(cycle: Duration(seconds: 1)), + child: SizedBox.expand(), + ), + ), + ), + ); + final config = beamPainterOf(tester).config; + expect(config.strength, 0.7); + expect(config.palette, BeamColors.ocean.resolve()); + expect(config.cycleSeconds, closeTo(1, 1e-9)); + expect(config.direction, BeamDirection.reverse); + }); - await tester.pumpWidget(build(BeamColors.sunset)); - expect( - identical(_config(tester).palette, BeamColors.sunset.resolve()), - isTrue, - ); + testWidgets('nested themes merge, inner over outer', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeamTheme( + data: BorderBeamThemeData( + style: BeamStyle(colors: BeamColors.ocean, strength: 0.5), + shape: BeamShape(borderWidth: 2), + ), + child: BorderBeamTheme( + data: BorderBeamThemeData(style: BeamStyle(strength: 0.9)), + child: BorderBeam(child: SizedBox.expand()), + ), + ), + ), + ); + final config = beamPainterOf(tester).config; + expect( + config.palette, + BeamColors.ocean.resolve(), + reason: 'the outer theme still supplies colors', + ); + expect(config.strength, 0.9, reason: 'the inner theme wins'); + expect(config.borderWidth, 2, reason: 'slots the inner theme omits'); + }); + + testWidgets('changing an outer theme rebuilds beams under an inner one', ( + tester, + ) async { + Widget build(BeamColors colors) => beamHost( + BorderBeamTheme( + data: BorderBeamThemeData(style: BeamStyle(colors: colors)), + child: const BorderBeamTheme( + data: BorderBeamThemeData(style: BeamStyle(strength: 0.7)), + child: BorderBeam(child: SizedBox.expand()), + ), + ), + ); + + await tester.pumpWidget(build(BeamColors.ocean)); + final ocean = beamPainterOf(tester).config; + expect(ocean.palette, BeamColors.ocean.resolve()); + + await tester.pumpWidget(build(BeamColors.sunset)); + final sunset = beamPainterOf(tester).config; + expect(identical(sunset, ocean), isFalse); + expect(sunset.palette, BeamColors.sunset.resolve()); + expect(sunset.strength, 0.7); + }); }); - testWidgets('a theme playback keeps a beam idle', (tester) async { - await tester.pumpWidget( - _host( - const BorderBeamTheme( - data: BorderBeamThemeData(playback: BeamPlayback(autoPlay: false)), - child: BorderBeam.rotate(child: SizedBox.expand()), + group('effect', () { + testWidgets('a theme effect reaches a beam that sets none', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeamTheme( + data: BorderBeamThemeData(effect: BeamEffect.rotate(count: 2)), + child: BorderBeam(child: SizedBox.expand()), + ), ), - ), - ); - await tester.pump(const Duration(seconds: 1)); - expect(tester.binding.hasScheduledFrame, isFalse); + ); + expect( + beamPainterOf(tester).config.effect, + const BeamEffect.rotate(count: 2), + ); + }); + + testWidgets('a beam effect wins over the theme', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeamTheme( + data: BorderBeamThemeData(effect: BeamEffect.rotate(count: 2)), + child: BorderBeam( + effect: BeamEffect.line(edge: BeamEdge.top), + child: SizedBox.expand(), + ), + ), + ), + ); + expect( + beamPainterOf(tester).config.effect, + const BeamEffect.line(edge: BeamEdge.top), + ); + }); + + testWidgets('an inner theme effect wins, an outer one fills in', ( + tester, + ) async { + Widget build({BeamEffect? inner}) => beamHost( + BorderBeamTheme( + data: const BorderBeamThemeData(effect: BeamEffect.pulse()), + child: BorderBeamTheme( + data: BorderBeamThemeData( + effect: inner, + style: const BeamStyle(strength: 0.5), + ), + child: const BorderBeam(child: SizedBox.expand()), + ), + ), + ); + + await tester.pumpWidget(build(inner: const BeamEffect.rotate(count: 2))); + expect( + beamPainterOf(tester).config.effect, + const BeamEffect.rotate(count: 2), + ); + + await tester.pumpWidget(build()); + expect(beamPainterOf(tester).config.effect, const BeamEffect.pulse()); + }); + + testWidgets('a theme effect change rebuilds the config and resolver', ( + tester, + ) async { + Widget build(BeamEffect effect) => beamHost( + BorderBeamTheme( + data: BorderBeamThemeData(effect: effect), + child: const BorderBeam(child: SizedBox.expand()), + ), + ); + + await tester.pumpWidget(build(const BeamEffect.rotate())); + await tester.pump(const Duration(milliseconds: 100)); + final before = beamPainterOf(tester); + expect(before.config.effect, const BeamEffect.rotate()); + + await tester.pumpWidget(build(const BeamEffect.line())); + await tester.pump(const Duration(milliseconds: 100)); + final after = beamPainterOf(tester); + expect(after.config.effect, const BeamEffect.line()); + expect( + after.config.cycleSeconds, + closeTo( + const BeamEffect.line().defaultCycle.inMicroseconds / 1e6, + 1e-9, + ), + reason: 'the timing defaults follow the new effect', + ); + expect(identical(after.resolver, before.resolver), isFalse); + expect(identical(after.resolver.config, after.config), isTrue); + expect(tester.binding.transientCallbackCount, 1); + }); + + testWidgets('the effect default cycle applies under a theme effect', ( + tester, + ) async { + for (final effect in BeamEffect.values) { + await tester.pumpWidget( + beamHost( + BorderBeamTheme( + data: BorderBeamThemeData(effect: effect), + child: const BorderBeam(child: SizedBox.expand()), + ), + ), + ); + final config = beamPainterOf(tester).config; + expect( + config.cycleSeconds, + closeTo(effect.defaultCycle.inMicroseconds / 1e6, 1e-9), + reason: effect.name, + ); + } + }); }); group('playback through a theme', () { + testWidgets('a theme autoPlay: false keeps a beam idle', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeamTheme( + data: BorderBeamThemeData(playback: BeamPlayback(autoPlay: false)), + child: BorderBeam(child: SizedBox.expand()), + ), + ), + ); + await tester.pump(const Duration(seconds: 1)); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + expect(tester.binding.transientCallbackCount, 0); + }); + testWidgets('an active shorthand still respects a theme autoPlay: false', ( tester, ) async { await tester.pumpWidget( - _host( + beamHost( const BorderBeamTheme( data: BorderBeamThemeData(playback: BeamPlayback(autoPlay: false)), - child: BorderBeam.rotate(active: true, child: SizedBox.expand()), + child: BorderBeam(active: true, child: SizedBox.expand()), ), ), ); await tester.pump(const Duration(seconds: 1)); expect( - _clock(tester).isVisible, + beamPainterOf(tester).clock.isVisible, isFalse, reason: 'active says what to play, autoPlay says whether to start it', ); - expect(tester.binding.hasScheduledFrame, isFalse); + expect(tester.binding.transientCallbackCount, 0); }); testWidgets('a beam autoPlay: true overrides a theme autoPlay: false', ( tester, ) async { await tester.pumpWidget( - _host( + beamHost( const BorderBeamTheme( data: BorderBeamThemeData(playback: BeamPlayback(autoPlay: false)), - child: BorderBeam.rotate( + child: BorderBeam( playback: BeamPlayback(autoPlay: true), child: SizedBox.expand(), ), @@ -176,18 +419,18 @@ void main() { ); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); - expect(_clock(tester).isVisible, isTrue); + expect(beamPainterOf(tester).clock.isVisible, isTrue); }); testWidgets('a theme startAfter delays the start', (tester) async { var activated = 0; await tester.pumpWidget( - _host( + beamHost( BorderBeamTheme( data: const BorderBeamThemeData( playback: BeamPlayback(startAfter: Duration(seconds: 2)), ), - child: BorderBeam.rotate( + child: BorderBeam( onActivate: () => activated++, child: const SizedBox.expand(), ), @@ -196,24 +439,24 @@ void main() { ); await tester.pump(const Duration(seconds: 1)); expect(activated, 0); - expect(_clock(tester).isVisible, isFalse); - expect(tester.binding.hasScheduledFrame, isFalse); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + expect(tester.binding.transientCallbackCount, 0); await tester.pump(const Duration(seconds: 1, milliseconds: 100)); await tester.pump(); - expect(_clock(tester).isVisible, isTrue); + expect(beamPainterOf(tester).clock.isVisible, isTrue); await tester.pump(const Duration(milliseconds: 700)); expect(activated, 1); }); testWidgets('a beam startAfter overrides a theme one', (tester) async { await tester.pumpWidget( - _host( + beamHost( const BorderBeamTheme( data: BorderBeamThemeData( playback: BeamPlayback(startAfter: Duration(seconds: 5)), ), - child: BorderBeam.rotate( + child: BorderBeam( playback: BeamPlayback(startAfter: Duration(milliseconds: 100)), child: SizedBox.expand(), ), @@ -222,18 +465,40 @@ void main() { ); await tester.pump(const Duration(milliseconds: 150)); await tester.pump(); - expect(_clock(tester).isVisible, isTrue); + expect(beamPainterOf(tester).clock.isVisible, isTrue); + }); + + testWidgets('an outer theme startAfter reaches a beam under an inner ' + 'theme', (tester) async { + await tester.pumpWidget( + beamHost( + const BorderBeamTheme( + data: BorderBeamThemeData( + playback: BeamPlayback(startAfter: Duration(seconds: 2)), + ), + child: BorderBeamTheme( + data: BorderBeamThemeData(style: BeamStyle(strength: 0.5)), + child: BorderBeam(child: SizedBox.expand()), + ), + ), + ), + ); + await tester.pump(const Duration(seconds: 1)); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + await tester.pump(const Duration(seconds: 1, milliseconds: 100)); + await tester.pump(); + expect(beamPainterOf(tester).clock.isVisible, isTrue); }); testWidgets('a theme duration bounds the total play time', (tester) async { var deactivated = 0; await tester.pumpWidget( - _host( + beamHost( BorderBeamTheme( data: const BorderBeamThemeData( playback: BeamPlayback(duration: Duration(seconds: 1)), ), - child: BorderBeam.rotate( + child: BorderBeam( onDeactivate: () => deactivated++, child: const SizedBox.expand(), ), @@ -244,87 +509,64 @@ void main() { await tester.pump(const Duration(milliseconds: 1100)); await tester.pump(const Duration(milliseconds: 600)); expect(deactivated, 1); + expect(tester.binding.transientCallbackCount, 0); }); testWidgets('a theme reducedMotion: animate keeps the beam moving', ( tester, ) async { await tester.pumpWidget( - _host( + beamHost( disableAnimations: true, const BorderBeamTheme( data: BorderBeamThemeData( playback: BeamPlayback(reducedMotion: BeamReducedMotion.animate), ), - child: BorderBeam.rotate(child: SizedBox.expand()), + child: BorderBeam(child: SizedBox.expand()), ), ), ); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); - expect(_clock(tester).isRunning, isTrue); - }); - - testWidgets('a controller with a theme startAfter asserts', (tester) async { - final controller = BorderBeamController(); - addTearDown(controller.dispose); - await pumpExpectingAssertion( - tester, - _host( - BorderBeamTheme( - data: const BorderBeamThemeData( - playback: BeamPlayback(startAfter: Duration(seconds: 1)), - ), - child: BorderBeam.rotate( - controller: controller, - child: const SizedBox.expand(), - ), - ), - ), - message: 'When a BorderBeamController is attached it owns playback', - ); - }); - - testWidgets('a controller with a theme duration asserts', (tester) async { - final controller = BorderBeamController(); - addTearDown(controller.dispose); - await pumpExpectingAssertion( - tester, - _host( - BorderBeamTheme( - data: const BorderBeamThemeData( - playback: BeamPlayback(duration: Duration(seconds: 1)), - ), - child: BorderBeam.rotate( - controller: controller, - child: const SizedBox.expand(), - ), - ), - ), - message: 'When a BorderBeamController is attached it owns playback', - ); + expect(beamPainterOf(tester).clock.isRunning, isTrue); + expect(beamPainterOf(tester).staticMode, isFalse); }); - testWidgets('an outer theme startAfter reaches a beam under an inner ' - 'theme', (tester) async { + testWidgets('a theme fadeCurve reaches the clock', (tester) async { await tester.pumpWidget( - _host( + beamHost( const BorderBeamTheme( data: BorderBeamThemeData( - playback: BeamPlayback(startAfter: Duration(seconds: 2)), - ), - child: BorderBeamTheme( - data: BorderBeamThemeData(style: BeamStyle(strength: 0.5)), - child: BorderBeam.rotate(child: SizedBox.expand()), + playback: BeamPlayback(fadeCurve: Curves.linear), ), + child: BorderBeam(child: SizedBox.expand()), ), ), ); - await tester.pump(const Duration(seconds: 1)); - expect(_clock(tester).isVisible, isFalse); - await tester.pump(const Duration(seconds: 1, milliseconds: 100)); - await tester.pump(); - expect(_clock(tester).isVisible, isTrue); + expect(beamPainterOf(tester).clock.fadeCurve, Curves.linear); }); + + for (final (name, playback) in [ + ('startAfter', const BeamPlayback(startAfter: Duration(seconds: 1))), + ('duration', const BeamPlayback(duration: Duration(seconds: 1))), + ]) { + testWidgets('a controller with a theme $name asserts', (tester) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + await pumpExpectingAssertion( + tester, + beamHost( + BorderBeamTheme( + data: BorderBeamThemeData(playback: playback), + child: BorderBeam( + controller: controller, + child: const SizedBox.expand(), + ), + ), + ), + message: 'When a BorderBeamController is attached it owns playback', + ); + }); + } }); } diff --git a/test/widget/border_beam_update_test.dart b/test/widget/border_beam_update_test.dart index fb96cc0..4c636e4 100644 --- a/test/widget/border_beam_update_test.dart +++ b/test/widget/border_beam_update_test.dart @@ -1,35 +1,16 @@ -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_border_beam/src/animation/beam_clock.dart'; import 'package:flutter_border_beam/src/animation/beam_phases.dart'; -import 'package:flutter_border_beam/src/painting/beam_painter.dart'; +import 'package:flutter_border_beam/src/models/beam_config.dart'; +import 'package:flutter_border_beam/src/render/beam_painter.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; -Widget _host(Widget child, {bool disableAnimations = false}) => MaterialApp( - theme: ThemeData(brightness: Brightness.dark), - builder: (context, app) => MediaQuery( - data: MediaQuery.of(context).copyWith(disableAnimations: disableAnimations), - child: app!, - ), - home: Scaffold( - body: Center(child: SizedBox(width: 350, height: 140, child: child)), - ), -); - -BeamPainter _beamPainter(WidgetTester tester) => tester - .widgetList( - find.descendant( - of: find.byType(BorderBeam), - matching: find.byType(CustomPaint), - ), - ) - .expand((paint) => [paint.painter, paint.foregroundPainter]) - .whereType() - .first; +import 'test_utils.dart'; // The frame the painter would draw right now. ({BeamPainter painter, BeamFramePhases phases}) _frame(WidgetTester tester) { - final painter = _beamPainter(tester); + final painter = beamPainterOf(tester); return ( painter: painter, phases: painter.resolver.sample( @@ -39,345 +20,357 @@ BeamPainter _beamPainter(WidgetTester tester) => tester ); } +/// `didUpdateWidget` and dependency changes: what re-resolves the painted +/// config (and only that), what retimes the running clock, and how the +/// scheduling inputs take effect on a beam that is already mounted. void main() { - group('cycleDuration change', () { - testWidgets('retimes the rotate beam without a phase jump', (tester) async { - Widget build(Duration cycle) => _host( - BorderBeam.rotate( - timing: BeamTiming(cycle: cycle), - child: const SizedBox.expand(), - ), + group('config resolution', () { + testWidgets('an effect change rebuilds the config and the resolver', ( + tester, + ) async { + Widget build(BeamEffect effect) => + beamHost(BorderBeam(effect: effect, child: const SizedBox.expand())); + + await tester.pumpWidget(build(const BeamEffect.rotate())); + final before = beamPainterOf(tester); + + await tester.pumpWidget(build(const BeamEffect.line(edge: BeamEdge.top))); + final after = beamPainterOf(tester); + expect(after.config.effect, const BeamEffect.line(edge: BeamEdge.top)); + expect(identical(after.config, before.config), isFalse); + expect(identical(after.resolver, before.resolver), isFalse); + expect(identical(after.resolver.config, after.config), isTrue); + + // A parameter of the same effect is a different effect. + await tester.pumpWidget( + build(const BeamEffect.line(edge: BeamEdge.bottom)), ); - - await tester.pumpWidget(build(const Duration(seconds: 2))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 900)); - final before = _frame(tester); - expect(before.painter.clock.elapsedSeconds, closeTo(0.9, 1e-9)); - - await tester.pumpWidget(build(const Duration(seconds: 4))); - final after = _frame(tester); - expect( - after.painter.config.cycleSeconds, - closeTo(4, 1e-9), - reason: 'the new cycle is in effect', + beamPainterOf(tester).config.effect, + const BeamEffect.line(edge: BeamEdge.bottom), ); - expect( - after.painter.clock.elapsedSeconds, - closeTo(1.8, 1e-9), - reason: 'elapsed time is rescaled by the cycle ratio', + }); + + testWidgets('a style change re-resolves the config', (tester) async { + Widget build(BeamStyle style) => + beamHost(BorderBeam(style: style, child: const SizedBox.expand())); + + await tester.pumpWidget( + build(const BeamStyle(colors: BeamColors.ocean, strength: 0.4)), ); - expect( - after.phases.angleRadians, - closeTo(before.phases.angleRadians, 1e-6), + final ocean = beamPainterOf(tester).config; + expect(ocean.palette, BeamColors.ocean.resolve()); + expect(ocean.strength, 0.4); + + await tester.pumpWidget( + build(const BeamStyle(colors: BeamColors.sunset, strength: 0.8)), ); - expect(after.phases.hueDegrees, closeTo(before.phases.hueDegrees, 1e-6)); + final sunset = beamPainterOf(tester).config; + expect(identical(sunset, ocean), isFalse); + expect(sunset.palette, BeamColors.sunset.resolve()); + expect(sunset.strength, 0.8); }); - testWidgets('retimes the line beam without a phase jump', (tester) async { - Widget build(Duration cycle) => _host( - BorderBeam.line( - timing: BeamTiming(cycle: cycle), - child: const SizedBox.expand(), - ), + testWidgets('a shape change re-resolves the config', (tester) async { + Widget build(BeamShape shape) => + beamHost(BorderBeam(shape: shape, child: const SizedBox.expand())); + + await tester.pumpWidget(build(const BeamShape(borderWidth: 1))); + final thin = beamPainterOf(tester).config; + + await tester.pumpWidget( + build(const BeamShape(borderWidth: 3, superellipse: true)), ); + final thick = beamPainterOf(tester).config; + expect(identical(thick, thin), isFalse); + expect(thick.borderWidth, 3); + expect(thick.superellipse, isTrue); + }); - await tester.pumpWidget(build(const Duration(seconds: 3))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1400)); - final before = _frame(tester); + testWidgets('a timing change re-resolves the config', (tester) async { + Widget build(BeamTiming timing) => + beamHost(BorderBeam(timing: timing, child: const SizedBox.expand())); - await tester.pumpWidget(build(const Duration(milliseconds: 1500))); - final after = _frame(tester); + await tester.pumpWidget(build(const BeamTiming())); + final forward = beamPainterOf(tester).config; + expect(forward.direction, BeamDirection.forward); - expect(after.phases.lineX, closeTo(before.phases.lineX, 1e-6)); - expect(after.phases.lineW, closeTo(before.phases.lineW, 1e-6)); - expect(after.phases.lineH, closeTo(before.phases.lineH, 1e-6)); - expect(after.phases.spike, closeTo(before.phases.spike, 1e-6)); - expect(after.phases.edge, closeTo(before.phases.edge, 1e-6)); - expect(after.phases.hueDegrees, closeTo(before.phases.hueDegrees, 1e-6)); - expect( - after.phases.bloomHueDegrees, - closeTo(before.phases.bloomHueDegrees, 1e-6), + await tester.pumpWidget( + build( + const BeamTiming( + direction: BeamDirection.reverse, + huePeriod: Duration(seconds: 4), + ), + ), ); + final reverse = beamPainterOf(tester).config; + expect(identical(reverse, forward), isFalse); + expect(reverse.direction, BeamDirection.reverse); + expect(reverse.huePeriodSeconds, closeTo(4, 1e-9)); }); - testWidgets('keeps every pulse oscillator continuous', (tester) async { - Widget build(Duration cycle) => _host( - BorderBeam.pulseInside( - timing: BeamTiming(cycle: cycle), + testWidgets('equal but new value objects keep the resolved config', ( + tester, + ) async { + // Every argument is built at runtime, so each pump hands the widget + // fresh instances that are merely equal to the last ones. + Widget build(double strength, double radius, int cycleMs) => beamHost( + BorderBeam( + effect: BeamEffect.rotate(count: cycleMs ~/ 1000), + colors: BeamColors([Color(0xFF00AAFF + 0 * cycleMs), Colors.pink]), + style: BeamStyle(strength: strength, glow: strength * 2), + shape: BeamShape.circular(radius, borderWidth: radius / 8), + timing: BeamTiming( + cycle: Duration(milliseconds: cycleMs), + huePeriod: Duration(milliseconds: cycleMs * 4), + ), child: const SizedBox.expand(), ), ); - await tester.pumpWidget(build(const Duration(milliseconds: 2300))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1700)); - final before = _frame(tester); - - await tester.pumpWidget(build(const Duration(seconds: 5))); - final after = _frame(tester); + await tester.pumpWidget(build(0.5, 16, 2000)); + await tester.pump(const Duration(milliseconds: 100)); + final config = beamPainterOf(tester).config; + final resolver = beamPainterOf(tester).resolver; for (var i = 0; i < 3; i++) { - expect( - after.phases.pulse.bw[i], - closeTo(before.phases.pulse.bw[i], 1e-6), - ); - expect( - after.phases.pulse.bh[i], - closeTo(before.phases.pulse.bh[i], 1e-6), - ); - expect( - after.phases.pulse.bx[i], - closeTo(before.phases.pulse.bx[i], 1e-6), - ); - expect( - after.phases.pulse.by[i], - closeTo(before.phases.pulse.by[i], 1e-6), - ); + await tester.pumpWidget(build(0.5, 16, 2000)); + await tester.pump(const Duration(milliseconds: 100)); + expect(identical(beamPainterOf(tester).config, config), isTrue); + expect(identical(beamPainterOf(tester).resolver, resolver), isTrue); } - expect(after.phases.pulse.bgh, closeTo(before.phases.pulse.bgh, 1e-6)); - expect( - after.phases.pulse.bopTl, - closeTo(before.phases.pulse.bopTl, 1e-6), - ); - expect( - after.phases.pulse.bopBr, - closeTo(before.phases.pulse.bopBr, 1e-6), - ); - expect(after.phases.hueDegrees, closeTo(before.phases.hueDegrees, 1e-6)); + + // And a real change still lands. + await tester.pumpWidget(build(0.6, 16, 2000)); + expect(identical(beamPainterOf(tester).config, config), isFalse); + expect(beamPainterOf(tester).config.strength, 0.6); }); - testWidgets('keeps the fade envelope continuous mid fade-in', ( + testWidgets('an ambient brightness change re-resolves an auto beam', ( tester, ) async { - var activated = 0; - Widget build(Duration cycle) => _host( - BorderBeam.rotate( - timing: BeamTiming(cycle: cycle), - onActivate: () => activated++, + Widget build(Brightness brightness, {BeamTheme? theme}) => beamHost( + brightness: brightness, + BorderBeam( + style: BeamStyle(theme: theme), child: const SizedBox.expand(), ), ); - await tester.pumpWidget(build(const Duration(seconds: 2))); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 150)); - final before = _beamPainter(tester).clock; - final opacity = before.fadeOpacity; - expect(opacity, greaterThan(0)); - expect(opacity, lessThan(1)); - expect(before.stage, BeamFadeStage.fadingIn); - - await tester.pumpWidget(build(const Duration(seconds: 6))); - final after = _beamPainter(tester).clock; - expect(after.fadeOpacity, closeTo(opacity, 1e-6)); - expect(after.stage, BeamFadeStage.fadingIn); + await tester.pumpWidget(build(Brightness.dark)); + expect(beamPainterOf(tester).config.brightness, Brightness.dark); - // The remaining fade time is unchanged too: 0.45s left of the 0.6s - // fade-in, not 0.45s scaled by the cycle ratio. - await tester.pump(const Duration(milliseconds: 400)); - expect(activated, 0); - await tester.pump(const Duration(milliseconds: 100)); - expect(activated, 1); - expect(after.fadeOpacity, 1); - }); + // MaterialApp animates a theme change; let it land. + await tester.pumpWidget(build(Brightness.light)); + await tester.pump(const Duration(milliseconds: 300)); + expect(beamPainterOf(tester).config.brightness, Brightness.light); - testWidgets('an unchanged cycle leaves the timeline alone', (tester) async { - Widget build(double strength) => _host( - BorderBeam.rotate( - style: BeamStyle(strength: strength), - timing: const BeamTiming(cycle: Duration(seconds: 2)), - child: const SizedBox.expand(), - ), + await tester.pumpWidget(build(Brightness.light, theme: BeamTheme.dark)); + expect( + beamPainterOf(tester).config.brightness, + Brightness.dark, + reason: 'an explicit theme ignores the ambient brightness', ); - - await tester.pumpWidget(build(1)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 900)); - await tester.pumpWidget(build(0.5)); - expect(_beamPainter(tester).clock.elapsedSeconds, closeTo(0.9, 1e-9)); }); + }); - testWidgets('retiming during a gap preserves the gap phase', ( + group('cycle change', () { + testWidgets('retimes a travelling beam without snapping the sweep', ( tester, ) async { - Widget build(Duration cycle) => _host( - BorderBeam.rotate( - timing: BeamTiming( - cycle: cycle, - cycleGap: const Duration(seconds: 1), - ), + Widget build(Duration cycle) => beamHost( + BorderBeam( + timing: BeamTiming(cycle: cycle), child: const SizedBox.expand(), ), ); await tester.pumpWidget(build(const Duration(seconds: 2))); await tester.pump(); - await tester.pump(const Duration(milliseconds: 2500)); + await tester.pump(const Duration(milliseconds: 900)); final before = _frame(tester); - expect(before.phases.travelProgress, 1); - expect(before.phases.fadeOpacity, 0); + expect(before.painter.clock.elapsedSeconds, closeTo(0.9, 1e-9)); + expect(before.phases.travelProgress, closeTo(0.45, 1e-9)); await tester.pumpWidget(build(const Duration(seconds: 4))); final after = _frame(tester); - expect(after.painter.clock.elapsedSeconds, closeTo(4.5, 1e-9)); - expect(after.phases.travelProgress, 1); + expect(after.painter.config.cycleSeconds, closeTo(4, 1e-9)); + expect( + identical(after.painter.clock, before.painter.clock), + isTrue, + reason: 'the running clock is retimed, not replaced', + ); expect( - after.phases.fadeOpacity, - closeTo(before.phases.fadeOpacity, 1e-9), + after.phases.travelProgress, + closeTo(before.phases.travelProgress, 1e-9), ); + expect(after.phases.hueDegrees, closeTo(before.phases.hueDegrees, 1e-6)); + + // And from here it runs at the new rate: 0.4s more is a tenth of a + // 4s cycle. + await tester.pump(const Duration(milliseconds: 400)); + expect(_frame(tester).phases.travelProgress, closeTo(0.55, 1e-9)); }); - }); - group('reduced motion', () { - testWidgets('turning it off starts a beam that never got to start', ( - tester, - ) async { - Widget build(bool reduced) => _host( - disableAnimations: reduced, - const BorderBeam.rotate(child: SizedBox.expand()), - ); + // Rotate has its own test above; every other travelling effect here. + for (final effect in BeamEffect.values.where( + (e) => e.travels && e is! RotateEffect, + )) { + testWidgets('retimes ${effect.name} without snapping the sweep', ( + tester, + ) async { + Widget build(Duration cycle) => beamHost( + BorderBeam( + effect: effect, + timing: BeamTiming(cycle: cycle, cycleGap: Duration.zero), + child: const SizedBox.expand(), + ), + ); - await tester.pumpWidget(build(true)); - await tester.pump(const Duration(milliseconds: 100)); - expect(_beamPainter(tester).clock.isVisible, isFalse); - expect(tester.binding.hasScheduledFrame, isFalse); + await tester.pumpWidget(build(const Duration(seconds: 3))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1400)); + final before = _frame(tester); - await tester.pumpWidget(build(false)); - expect(_beamPainter(tester).clock.isVisible, isTrue); - await tester.pump(const Duration(milliseconds: 50)); - expect(tester.binding.hasScheduledFrame, isTrue); - expect(_beamPainter(tester).clock.isRunning, isTrue); - }); + await tester.pumpWidget(build(const Duration(milliseconds: 1500))); + final after = _frame(tester); + expect( + after.phases.travelProgress, + closeTo(before.phases.travelProgress, 1e-9), + ); + expect( + after.phases.fadeOpacity, + closeTo(before.phases.fadeOpacity, 1e-9), + ); + expect( + after.phases.hueDegrees, + closeTo(before.phases.hueDegrees, 1e-6), + ); + }); + } - testWidgets('turning it off respects a pending startAfter delay', ( - tester, - ) async { - Widget build(bool reduced) => _host( - disableAnimations: reduced, - const BorderBeam.rotate( - playback: BeamPlayback(startAfter: Duration(seconds: 2)), - child: SizedBox.expand(), + testWidgets('keeps an ambient beam breathing continuously', (tester) async { + Widget build(Duration cycle) => beamHost( + BorderBeam( + effect: const BeamEffect.pulse(), + timing: BeamTiming(cycle: cycle), + child: const SizedBox.expand(), ), ); - await tester.pumpWidget(build(true)); - await tester.pump(const Duration(milliseconds: 500)); - await tester.pumpWidget(build(false)); - expect(_beamPainter(tester).clock.isVisible, isFalse); - await tester.pump(const Duration(seconds: 2)); + await tester.pumpWidget(build(const Duration(milliseconds: 2300))); await tester.pump(); - expect(_beamPainter(tester).clock.isVisible, isTrue); + await tester.pump(const Duration(milliseconds: 1700)); + final before = _frame(tester); + + await tester.pumpWidget(build(const Duration(seconds: 5))); + final after = _frame(tester); + expect(after.phases.cycles, closeTo(before.phases.cycles, 1e-9)); + expect(after.phases.hueDegrees, closeTo(before.phases.hueDegrees, 1e-6)); }); - testWidgets('toggling it on pauses and off resumes a running beam', ( + testWidgets('keeps the fade envelope continuous mid fade-in', ( tester, ) async { - Widget build(bool reduced) => _host( - disableAnimations: reduced, - const BorderBeam.rotate(child: SizedBox.expand()), + var activated = 0; + Widget build(Duration cycle) => beamHost( + BorderBeam( + timing: BeamTiming(cycle: cycle), + onActivate: () => activated++, + child: const SizedBox.expand(), + ), ); - await tester.pumpWidget(build(false)); + await tester.pumpWidget(build(const Duration(seconds: 2))); await tester.pump(); - await tester.pump(const Duration(milliseconds: 800)); - final clock = _beamPainter(tester).clock; - expect(clock.isRunning, isTrue); - final frozenAt = clock.elapsedSeconds; + await tester.pump(const Duration(milliseconds: 150)); + final clock = beamPainterOf(tester).clock; + final opacity = clock.fadeOpacity; + expect(opacity, inExclusiveRange(0, 1)); + expect(clock.stage, BeamFadeStage.fadingIn); - await tester.pumpWidget(build(true)); - expect(clock.isRunning, isFalse); - await tester.pump(const Duration(milliseconds: 200)); - expect(tester.binding.hasScheduledFrame, isFalse); - expect(clock.elapsedSeconds, closeTo(frozenAt, 1e-9)); - expect(clock.isVisible, isTrue, reason: 'the frame stays on screen'); + await tester.pumpWidget(build(const Duration(seconds: 6))); + expect(clock.fadeOpacity, closeTo(opacity, 1e-9)); + expect(clock.stage, BeamFadeStage.fadingIn); - await tester.pumpWidget(build(false)); - expect(clock.isRunning, isTrue); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - expect( - clock.elapsedSeconds, - greaterThan(frozenAt), - reason: 'the timeline continues where it was frozen', + // The remaining fade time is unchanged too: the rest of the fade-in, + // not that rest scaled by the cycle ratio. + final left = Duration( + microseconds: ((BeamClock.fadeInSeconds - 0.15) * 1e6).round(), ); + await tester.pump(left - const Duration(milliseconds: 50)); + expect(activated, 0); + await tester.pump(const Duration(milliseconds: 100)); + expect(activated, 1); + expect(clock.fadeOpacity, 1); }); - testWidgets('turning it off does not replay a beam that already ran', ( + testWidgets('a cycle under the floor retimes on the cycle the beam runs', ( tester, ) async { - var deactivated = 0; - Widget build(bool reduced) => _host( - disableAnimations: reduced, - BorderBeam.rotate( - playback: const BeamPlayback(duration: Duration(seconds: 1)), - onDeactivate: () => deactivated++, + Widget build(Duration cycle) => beamHost( + BorderBeam( + timing: BeamTiming(cycle: cycle), child: const SizedBox.expand(), ), ); - await tester.pumpWidget(build(false)); + await tester.pumpWidget(build(const Duration(milliseconds: 10))); await tester.pump(); - await tester.pump(const Duration(milliseconds: 1100)); - await tester.pump(const Duration(milliseconds: 600)); - expect(deactivated, 1); - expect(_beamPainter(tester).clock.isVisible, isFalse); + await tester.pump(const Duration(milliseconds: 20)); + final before = _frame(tester); + expect( + before.painter.config.cycleSeconds, + BeamConfig.minCycleSeconds, + reason: 'a 10ms cycle runs at the floor', + ); - await tester.pumpWidget(build(true)); - await tester.pump(const Duration(milliseconds: 50)); - await tester.pumpWidget(build(false)); - await tester.pump(const Duration(milliseconds: 50)); + // 20ms is under the floor too: the beam runs the same cycle, so its + // timeline must not move. + await tester.pumpWidget(build(const Duration(milliseconds: 20))); + final same = _frame(tester); + expect( + same.painter.clock.elapsedSeconds, + closeTo(before.painter.clock.elapsedSeconds, 1e-12), + ); + expect( + same.phases.travelProgress, + closeTo(before.phases.travelProgress, 1e-9), + ); + + // Out of the floor, the sweep holds where the floored cycle had it. + await tester.pumpWidget(build(const Duration(milliseconds: 200))); + final after = _frame(tester); + expect(after.painter.config.cycleSeconds, closeTo(0.2, 1e-12)); expect( - _beamPainter(tester).clock.isVisible, - isFalse, - reason: 'its play time is spent', + after.phases.travelProgress, + closeTo(before.phases.travelProgress, 1e-9), ); - expect(tester.binding.hasScheduledFrame, isFalse); }); - testWidgets('turning it off does not resume a controller-paused beam', ( - tester, - ) async { - final controller = BorderBeamController(); - addTearDown(controller.dispose); - Widget build(bool reduced) => _host( - disableAnimations: reduced, - BorderBeam.rotate( - controller: controller, + testWidgets('an unchanged cycle leaves the timeline alone', (tester) async { + Widget build(double strength) => beamHost( + BorderBeam( + style: BeamStyle(strength: strength), + timing: const BeamTiming(cycle: Duration(seconds: 2)), child: const SizedBox.expand(), ), ); - await tester.pumpWidget(build(false)); - controller.start(); + await tester.pumpWidget(build(1)); await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - expect(controller.isRunning, isTrue); - controller.pause(); - await tester.pump(const Duration(milliseconds: 50)); - expect(controller.isRunning, isFalse); - - await tester.pumpWidget(build(true)); - await tester.pump(const Duration(milliseconds: 50)); - await tester.pumpWidget(build(false)); - await tester.pump(const Duration(milliseconds: 50)); - expect( - controller.isRunning, - isFalse, - reason: 'the controller owns the pause', - ); - expect(controller.isActive, isTrue); + await tester.pump(const Duration(milliseconds: 900)); + await tester.pumpWidget(build(0.5)); + expect(beamPainterOf(tester).clock.elapsedSeconds, closeTo(0.9, 1e-9)); }); }); - group('widget updates', () { + group('scheduling updates', () { testWidgets('enabling autoPlay applies startAfter from the new schedule', ( tester, ) async { - Widget build(bool autoPlay) => _host( - BorderBeam.rotate( + Widget build(bool autoPlay) => beamHost( + BorderBeam( playback: BeamPlayback( autoPlay: autoPlay, startAfter: const Duration(milliseconds: 500), @@ -388,20 +381,20 @@ void main() { await tester.pumpWidget(build(false)); await tester.pump(const Duration(seconds: 1)); - expect(_beamPainter(tester).clock.isVisible, isFalse); + expect(beamPainterOf(tester).clock.isVisible, isFalse); await tester.pumpWidget(build(true)); await tester.pump(const Duration(milliseconds: 400)); - expect(_beamPainter(tester).clock.isVisible, isFalse); + expect(beamPainterOf(tester).clock.isVisible, isFalse); await tester.pump(const Duration(milliseconds: 150)); - expect(_beamPainter(tester).clock.isVisible, isTrue); + expect(beamPainterOf(tester).clock.isVisible, isTrue); }); testWidgets('changing a pending startAfter reschedules the start', ( tester, ) async { - Widget build(Duration delay) => _host( - BorderBeam.rotate( + Widget build(Duration delay) => beamHost( + BorderBeam( playback: BeamPlayback(startAfter: delay), child: const SizedBox.expand(), ), @@ -411,14 +404,14 @@ void main() { await tester.pump(const Duration(milliseconds: 500)); await tester.pumpWidget(build(const Duration(milliseconds: 100))); await tester.pump(const Duration(milliseconds: 150)); - expect(_beamPainter(tester).clock.isVisible, isTrue); + expect(beamPainterOf(tester).clock.isVisible, isTrue); }); testWidgets('changing duration starts a fresh budget from the update', ( tester, ) async { - Widget build(Duration? duration) => _host( - BorderBeam.rotate( + Widget build(Duration? duration) => beamHost( + BorderBeam( playback: BeamPlayback(duration: duration), child: const SizedBox.expand(), ), @@ -427,7 +420,7 @@ void main() { await tester.pumpWidget(build(null)); await tester.pump(); await tester.pump(const Duration(milliseconds: 800)); - final clock = _beamPainter(tester).clock; + final clock = beamPainterOf(tester).clock; await tester.pumpWidget(build(const Duration(seconds: 1))); await tester.pump(const Duration(milliseconds: 900)); @@ -436,68 +429,13 @@ void main() { expect(clock.stage, BeamFadeStage.fadingOut); }); - testWidgets('a variant swap keeps visibility and restarts the clock', ( - tester, - ) async { - Widget build(bool pulse) => _host( - pulse - ? const BorderBeam.pulseInside(child: SizedBox.expand()) - : const BorderBeam.rotate(child: SizedBox.expand()), - ); - - await tester.pumpWidget(build(false)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 900)); - final first = _beamPainter(tester).clock; - expect(first.elapsedSeconds, closeTo(0.9, 1e-9)); - - await tester.pumpWidget(build(true)); - final second = _beamPainter(tester).clock; - expect(identical(second, first), isFalse, reason: 'a fresh clock'); - expect(second.isVisible, isTrue); - expect(second.elapsedSeconds, 0); - await tester.pump(const Duration(milliseconds: 50)); - expect(second.isRunning, isTrue); - }); - - testWidgets('a controller swap detaches the old and attaches the new', ( - tester, - ) async { - final first = BorderBeamController(); - final second = BorderBeamController(); - addTearDown(first.dispose); - addTearDown(second.dispose); - Widget build(BorderBeamController? controller) => _host( - BorderBeam.rotate( - controller: controller, - child: const SizedBox.expand(), - ), - ); - - await tester.pumpWidget(build(first)); - expect(first.isAttached, isTrue); - - await tester.pumpWidget(build(second)); - expect(first.isAttached, isFalse); - expect(second.isAttached, isTrue); - - second.start(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 700)); - expect(second.isActive, isTrue); - expect(_beamPainter(tester).clock.isVisible, isTrue); - - await tester.pumpWidget(build(null)); - expect(second.isAttached, isFalse); - }); - testWidgets('re-activating mid fade-out resumes from the current opacity', ( tester, ) async { var activated = 0; var deactivated = 0; - Widget build(bool active) => _host( - BorderBeam.rotate( + Widget build(bool active) => beamHost( + BorderBeam( active: active, onActivate: () => activated++, onDeactivate: () => deactivated++, @@ -508,15 +446,14 @@ void main() { await tester.pumpWidget(build(true)); await tester.pump(); await tester.pump(const Duration(milliseconds: 150)); - final clock = _beamPainter(tester).clock; + final clock = beamPainterOf(tester).clock; expect(clock.stage, BeamFadeStage.fadingIn); await tester.pumpWidget(build(false)); await tester.pump(const Duration(milliseconds: 80)); expect(clock.stage, BeamFadeStage.fadingOut); final mid = clock.fadeOpacity; - expect(mid, greaterThan(0)); - expect(mid, lessThan(1)); + expect(mid, inExclusiveRange(0, 1)); final elapsed = clock.elapsedSeconds; await tester.pumpWidget(build(true)); @@ -532,30 +469,76 @@ void main() { reason: 'a mid-fade re-activation keeps the timeline', ); - await tester.pump(const Duration(milliseconds: 700)); + await tester.pump(pastFadeIn); expect(activated, 1); expect(deactivated, 0); expect(clock.fadeOpacity, 1); }); - testWidgets('a colors change resolves a new config exactly once', ( + testWidgets('a controller swap detaches the old and attaches the new', ( tester, ) async { - Widget build(BeamColors colors) => _host( - BorderBeam.rotate(colors: colors, child: const SizedBox.expand()), + final first = BorderBeamController(); + final second = BorderBeamController(); + addTearDown(first.dispose); + addTearDown(second.dispose); + Widget build(BorderBeamController? controller) => beamHost( + BorderBeam(controller: controller, child: const SizedBox.expand()), ); - await tester.pumpWidget(build(BeamColors.ocean)); - final ocean = _beamPainter(tester).config; + await tester.pumpWidget(build(first)); + expect(first.isAttached, isTrue); + expect(second.isAttached, isFalse); - await tester.pumpWidget(build(BeamColors.sunset)); - final sunset = _beamPainter(tester).config; - expect(identical(sunset, ocean), isFalse); - expect(identical(sunset.palette, BeamColors.sunset.resolve()), isTrue); + await tester.pumpWidget(build(second)); + expect(first.isAttached, isFalse); + expect(second.isAttached, isTrue); + + // The detached controller no longer reaches the beam. + first.start(); + await tester.pump(const Duration(milliseconds: 100)); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + + second.start(); + await tester.pump(); + await tester.pump(pastFadeIn); + expect(second.isActive, isTrue); + expect(beamPainterOf(tester).clock.isVisible, isTrue); + + await tester.pumpWidget(build(null)); + expect(second.isAttached, isFalse); + }); + + testWidgets('dropping the controller hands playback back to the widget', ( + tester, + ) async { + final controller = BorderBeamController(); + addTearDown(controller.dispose); + Widget build(BorderBeamController? controller, {bool active = true}) => + beamHost( + BorderBeam( + controller: controller, + active: active, + child: const SizedBox.expand(), + ), + ); + + await tester.pumpWidget(build(controller)); + await tester.pump(const Duration(milliseconds: 100)); + expect(beamPainterOf(tester).clock.isVisible, isFalse); + + await tester.pumpWidget(build(null)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect( + beamPainterOf(tester).clock.isVisible, + isTrue, + reason: 'autoPlay takes over the beam that never started', + ); - // Rebuilding with the same colors reuses the resolved config. - await tester.pumpWidget(build(BeamColors.sunset)); - expect(identical(_beamPainter(tester).config, sunset), isTrue); + await tester.pumpWidget(build(null, active: false)); + await tester.pump(pastFadeOut); + expect(beamPainterOf(tester).clock.isVisible, isFalse); }); }); } diff --git a/test/widget/test_utils.dart b/test/widget/test_utils.dart index cc885a5..242946c 100644 --- a/test/widget/test_utils.dart +++ b/test/widget/test_utils.dart @@ -1,5 +1,25 @@ -import 'package:flutter/widgets.dart'; +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter/rendering.dart'; +import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/animation/beam_clock.dart'; +import 'package:flutter_border_beam/src/render/beam_painter.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Long enough for a fade-in to finish: [BeamClock.fadeInSeconds] plus a +/// margin. A test that waits out a fade waits this long instead of a number +/// of its own, so retuning the fade cannot leave it caught mid-fade. +final Duration pastFadeIn = _pastFade(BeamClock.fadeInSeconds); + +/// Long enough for a fade-out to finish: [BeamClock.fadeOutSeconds] plus the +/// same margin as [pastFadeIn]. +final Duration pastFadeOut = _pastFade(BeamClock.fadeOutSeconds); + +Duration _pastFade(double seconds) => + Duration(microseconds: (seconds * Duration.microsecondsPerSecond).ceil()) + + const Duration(milliseconds: 100); /// Pumps [app] and expects the framework to report an [AssertionError] whose /// message contains [message]. @@ -47,3 +67,131 @@ Future pumpExpectingAssertion( 'reported: $reported', ); } + +/// A [MaterialApp] hosting [child] centred in a [size] box. +/// +/// [disableAnimations] sets `MediaQuery.disableAnimations` (the platform's +/// reduced-motion request); [textDirection], when given, wraps [child] in a +/// [Directionality]. +Widget beamHost( + Widget child, { + bool disableAnimations = false, + Brightness brightness = Brightness.dark, + TextDirection? textDirection, + Size size = const Size(350, 140), +}) => MaterialApp( + debugShowCheckedModeBanner: false, + theme: ThemeData(brightness: brightness), + builder: (context, app) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: disableAnimations), + child: app!, + ), + home: Scaffold( + body: Center( + child: SizedBox( + width: size.width, + height: size.height, + child: textDirection == null + ? child + : Directionality(textDirection: textDirection, child: child), + ), + ), + ), +); + +/// The painter of the first [BorderBeam] under [within] (default: any beam +/// in the tree), or null when it paints nothing at all +/// (`BeamReducedMotion.hide`). +/// +/// Offstage widgets are included: a row parked in a scrollable's cache extent +/// is laid out but never painted, and the default finders would skip it. +BeamPainter? maybeBeamPainterOf(WidgetTester tester, {Finder? within}) => tester + .widgetList( + find.descendant( + of: within ?? find.byType(BorderBeam, skipOffstage: false), + matching: find.byType(CustomPaint, skipOffstage: false), + ), + ) + .map((paint) => paint.foregroundPainter) + .whereType() + .firstOrNull; + +/// The painter of the first [BorderBeam] under [within]; see +/// [maybeBeamPainterOf]. +BeamPainter beamPainterOf(WidgetTester tester, {Finder? within}) { + final painter = maybeBeamPainterOf(tester, within: within); + expect(painter, isNotNull, reason: 'no BeamPainter in the tree'); + return painter!; +} + +/// Rasterizes the [RepaintBoundary] the first [BorderBeam] (or [of]) builds +/// around itself — the beam over its child — as raw RGBA. +/// +/// Run on the real event loop: `toImage` never completes under a widget +/// test's fake async. The beam paints nothing until its shader has loaded, so +/// a test that reads pixels awaits `BorderBeam.precache()` in `setUpAll`. +Future beamPixels(WidgetTester tester, {Finder? of}) async { + final boundary = tester.renderObject( + of ?? find.byType(BorderBeam).first, + ); + final pixels = await tester.runAsync(() async { + final image = await boundary.toImage(); + final data = await image.toByteData(format: ui.ImageByteFormat.rawRgba); + final result = BeamPixels( + data!.buffer.asUint8List(), + image.width, + image.height, + ); + image.dispose(); + return result; + }); + return pixels!; +} + +/// One rasterized frame, as raw RGBA bytes. +class BeamPixels { + /// Wraps [bytes] of a [width]×[height] image. + BeamPixels(this.bytes, this.width, this.height); + + /// Row-major RGBA, four bytes per pixel. + final Uint8List bytes; + + /// Width in pixels. + final int width; + + /// Height in pixels. + final int height; + + /// The alpha (0–255) of the pixel at ([x], [y]). + int alphaAt(int x, int y) => bytes[(y * width + x) * 4 + 3]; + + /// Total alpha over the whole image, in whole-pixel units. + double get totalAlpha { + var sum = 0; + for (var i = 3; i < bytes.length; i += 4) { + sum += bytes[i]; + } + return sum / 255; + } + + /// How many pixels differ from [color] by more than [tolerance] in any + /// channel. + int countDifferentFrom(Color color, {int tolerance = 2}) { + final target = [ + (color.r * 255).round(), + (color.g * 255).round(), + (color.b * 255).round(), + (color.a * 255).round(), + ]; + var count = 0; + for (var i = 0; i < bytes.length; i += 4) { + for (var c = 0; c < 4; c++) { + if ((bytes[i + c] - target[c]).abs() > tolerance) { + count++; + break; + } + } + } + return count; + } +} diff --git a/test/widgets/beam_decoration_test.dart b/test/widgets/beam_decoration_test.dart index f78d09b..ee61efd 100644 --- a/test/widgets/beam_decoration_test.dart +++ b/test/widgets/beam_decoration_test.dart @@ -1,113 +1,205 @@ import 'dart:ui' as ui; -import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; /// [BeamDecoration] runs the beam engine from a [BoxPainter] instead of a -/// widget: it owns a raw [Ticker], repaints its box through `onChanged`, and -/// must give that ticker back when the render object drops it. +/// widget: it owns a raw `Ticker`, repaints its box through `onChanged`, and +/// must give that ticker (and any scheduling timer) back when the render +/// object drops it. +/// +/// Pending timers and running tickers that outlive the tree also fail a test +/// through the binding's own post-test invariants, so every test here doubles +/// as a leak check. void main() { + // Without the shader program a beam paints nothing; load it up front so + // the pixel assertions do not depend on asset-load timing. + setUpAll(() async { + await BorderBeam.precache(); + }); + const boundaryKey = ValueKey('boundary'); + const frozen = BeamPlayback(debugFrozenAt: Duration(milliseconds: 1300)); - Widget scene(Decoration decoration, {bool foreground = true}) => MaterialApp( + Widget scene({Decoration? foreground, Decoration? background}) => MaterialApp( debugShowCheckedModeBanner: false, - theme: ThemeData(brightness: Brightness.dark), home: Center( child: RepaintBoundary( key: boundaryKey, child: Container( - width: 350, - height: 140, - foregroundDecoration: foreground ? decoration : null, - decoration: foreground ? null : decoration, + width: 240, + height: 120, + foregroundDecoration: foreground, + decoration: background, ), ), ), ); - // Non-transparent pixels inside the boundary. Nothing else in the scene - // paints, so a count above zero is the beam and only the beam. - Future paintedPixels(WidgetTester tester) async { + // The boundary's RGBA bytes. Nothing else in the scene paints, so any + // non-transparent pixel is the beam. + Future capture(WidgetTester tester) async { final boundary = tester.renderObject( find.byKey(boundaryKey), ); - var painted = 0; + late Uint8List rgba; await tester.runAsync(() async { final image = await boundary.toImage(); final bytes = await image.toByteData(format: ui.ImageByteFormat.rawRgba); image.dispose(); - for (var i = 3; i < bytes!.lengthInBytes; i += 4) { - if (bytes.getUint8(i) != 0) painted++; - } + rgba = bytes!.buffer.asUint8List(); }); - return painted; + return rgba; + } + + int litPixels(Uint8List rgba) { + var lit = 0; + for (var i = 3; i < rgba.length; i += 4) { + if (rgba[i] != 0) lit++; + } + return lit; } + Future frame( + WidgetTester tester, + BeamDecoration decoration, + ) async { + await tester.pumpWidget(scene(foreground: decoration)); + await tester.pump(); + return capture(tester); + } + + // The properties the decoration reports, with the shorthands and theme + // already folded in — the values its painter resolves. + T resolved(BeamDecoration decoration, String name) => + decoration + .toDiagnosticsNode() + .getProperties() + .singleWhere((p) => p.name == name) + .value + as T; + group('painting', () { - testWidgets('paints the beam through a DecoratedBox', (tester) async { - await tester.pumpWidget( - scene( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - borderRadius: 16, - ), - ), + testWidgets('paints over the box in either decoration slot', ( + tester, + ) async { + const beam = BeamDecoration( + brightness: Brightness.dark, + borderRadius: 16, ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1300)); + for (final foreground in [true, false]) { + await tester.pumpWidget( + foreground ? scene(foreground: beam) : scene(background: beam), + ); + // The first tick after Ticker.start() reports elapsed 0. + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1300)); - expect(await paintedPixels(tester), greaterThan(0)); + expect( + litPixels(await capture(tester)), + greaterThan(0), + reason: foreground ? 'foregroundDecoration' : 'decoration', + ); + await tester.pumpWidget(const SizedBox()); + expect(tester.binding.transientCallbackCount, 0); + } }); - testWidgets('paints nothing while inactive', (tester) async { - await tester.pumpWidget( - scene( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - active: false, - ), - ), + testWidgets('paints every effect, in both brightnesses', (tester) async { + for (final effect in BeamEffect.values) { + for (final brightness in Brightness.values) { + await tester.pumpWidget( + scene( + foreground: BeamDecoration( + effect: effect, + brightness: brightness, + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1300)); + + final reason = '$effect on ${brightness.name}'; + expect(tester.takeException(), isNull, reason: reason); + expect( + litPixels(await capture(tester)), + greaterThan(0), + reason: reason, + ); + await tester.pumpWidget(const SizedBox()); + expect(tester.binding.transientCallbackCount, 0, reason: reason); + } + } + }); + + testWidgets('debugFrozenAt paints one fixed frame and never ticks', ( + tester, + ) async { + final first = await frame( + tester, + const BeamDecoration(brightness: Brightness.dark, playback: frozen), ); + expect(litPixels(first), greaterThan(0)); + expect(tester.binding.transientCallbackCount, 0); + + // Let time pass, then force the painter to paint again. + await tester.pump(const Duration(milliseconds: 700)); + tester + .renderObject(find.byType(DecoratedBox)) + .markNeedsPaint(); await tester.pump(); - await tester.pump(const Duration(milliseconds: 1300)); + final again = await capture(tester); + expect(listEquals(first, again), isTrue, reason: 'same instant twice'); + expect(tester.binding.transientCallbackCount, 0); - expect(await paintedPixels(tester), 0); + // A different instant is a different frame: the freeze picks the time. + final later = await frame( + tester, + const BeamDecoration( + brightness: Brightness.dark, + playback: BeamPlayback(debugFrozenAt: Duration(milliseconds: 2000)), + ), + ); + expect(listEquals(first, later), isFalse); + expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('paints every variant, in the slot its docs name', ( + testWidgets('autoPlay false or active false: no ticker, no pixels', ( tester, ) async { - for (final variant in BeamVariant.values) { - // pulse-outside blooms behind the child; every other variant paints - // over it. Both land in whichever slot the decoration is given. - final foreground = variant != BeamVariant.pulseOutside; - await tester.pumpWidget( - scene( - BeamDecoration(variant: variant, brightness: Brightness.dark), - foreground: foreground, - ), - ); + const idle = [ + BeamDecoration( + brightness: Brightness.dark, + playback: BeamPlayback(autoPlay: false), + ), + BeamDecoration(brightness: Brightness.dark, active: false), + BeamDecoration( + brightness: Brightness.dark, + playback: BeamPlayback(active: false), + ), + ]; + for (final decoration in idle) { + await tester.pumpWidget(scene(foreground: decoration)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1300)); - expect( - await paintedPixels(tester), - greaterThan(0), - reason: '$variant painted nothing', - ); + expect(tester.binding.transientCallbackCount, 0); + expect(litPixels(await capture(tester)), 0); await tester.pumpWidget(const SizedBox()); } }); + }); - testWidgets('holds the beam back until startAfter elapses', (tester) async { + group('scheduling', () { + testWidgets('startAfter holds the start back until it elapses', ( + tester, + ) async { await tester.pumpWidget( scene( - const BeamDecoration( - variant: BeamVariant.rotate, + foreground: const BeamDecoration( brightness: Brightness.dark, playback: BeamPlayback(startAfter: Duration(seconds: 1)), ), @@ -115,262 +207,370 @@ void main() { ); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); - expect(await paintedPixels(tester), 0); + expect(tester.binding.transientCallbackCount, 0); + expect(litPixels(await capture(tester)), 0); await tester.pump(const Duration(milliseconds: 600)); - await tester.pump(const Duration(milliseconds: 600)); - expect(await paintedPixels(tester), greaterThan(0)); + expect(tester.binding.transientCallbackCount, greaterThan(0)); + await tester.pump(const Duration(milliseconds: 1000)); + expect(litPixels(await capture(tester)), greaterThan(0)); + + await tester.pumpWidget(const SizedBox()); + expect(tester.binding.transientCallbackCount, 0); }); - }); - group('ticking', () { - testWidgets('calls onChanged on every clock tick', (tester) async { - var changes = 0; - final painter = const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - ).createBoxPainter(() => changes++); + testWidgets('duration ends the beam and stops its ticker', (tester) async { + await tester.pumpWidget( + scene( + foreground: const BeamDecoration( + brightness: Brightness.dark, + playback: BeamPlayback(duration: Duration(seconds: 1)), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 700)); + expect(litPixels(await capture(tester)), greaterThan(0)); + + // Past the duration, and past the fade-out it starts + // (BeamClock.fadeOutSeconds), with room to spare. + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(tester.binding.transientCallbackCount, 0); + expect(litPixels(await capture(tester)), 0); + }); - // The first tick after Ticker.start() reports elapsed 0; pump once - // before pumping durations. + testWidgets('repeat ends the beam after its cycles', (tester) async { + await tester.pumpWidget( + scene( + foreground: const BeamDecoration( + brightness: Brightness.dark, + timing: BeamTiming(cycle: Duration(seconds: 1)), + playback: BeamPlayback(repeat: BeamRepeat.once()), + ), + ), + ); await tester.pump(); - expect(changes, greaterThan(0)); + await tester.pump(const Duration(milliseconds: 700)); + expect(litPixels(await capture(tester)), greaterThan(0)); - final afterFirst = changes; - await tester.pump(const Duration(milliseconds: 16)); - await tester.pump(const Duration(milliseconds: 16)); - expect(changes, greaterThan(afterFirst)); - painter.dispose(); + // Past the one cycle, and past the fade-out it starts. + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(tester.binding.transientCallbackCount, 0); + expect(litPixels(await capture(tester)), 0); }); - testWidgets('an inactive decoration never ticks', (tester) async { - var changes = 0; - final painter = const BeamDecoration( - variant: BeamVariant.rotate, + testWidgets('repeat runs out even while there is nothing to paint', ( + tester, + ) async { + // The same decoration throughout, so the box keeps one painter: it + // ticks at zero size, then is given room once its cycle is spent. + const beam = BeamDecoration( brightness: Brightness.dark, - playback: BeamPlayback(autoPlay: false), - ).createBoxPainter(() => changes++); + timing: BeamTiming(cycle: Duration(seconds: 1)), + playback: BeamPlayback(repeat: BeamRepeat.once()), + ); + Widget sized(double width, double height) => MaterialApp( + debugShowCheckedModeBanner: false, + home: Center( + child: RepaintBoundary( + key: boundaryKey, + child: SizedBox( + width: 240, + height: 120, + child: Align( + alignment: Alignment.topLeft, + child: Container( + width: width, + height: height, + foregroundDecoration: beam, + ), + ), + ), + ), + ), + ); + await tester.pumpWidget(sized(0, 0)); await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); - expect(changes, 0); + expect(tester.binding.transientCallbackCount, greaterThan(0)); + // Past the one cycle, and past the fade-out it starts. + for (var i = 0; i < 20; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect( + tester.binding.transientCallbackCount, + 0, + reason: 'the budget ran out with no frame painted', + ); + + await tester.pumpWidget(sized(240, 120)); + await tester.pump(); + expect(litPixels(await capture(tester)), 0, reason: 'no spent beam'); expect(tester.binding.transientCallbackCount, 0); - painter.dispose(); }); - testWidgets('gives its ticker back when the render object goes', ( - tester, - ) async { + testWidgets('removal cancels a pending startAfter timer', (tester) async { await tester.pumpWidget( scene( - const BeamDecoration( - variant: BeamVariant.rotate, + foreground: const BeamDecoration( + brightness: Brightness.dark, + playback: BeamPlayback(startAfter: Duration(seconds: 5)), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 100)); + + await tester.pumpWidget(const SizedBox()); + expect(tester.binding.transientCallbackCount, 0); + // Ending here, before the 5s mark: a timer the painter failed to + // cancel fails the binding's no-pending-timers invariant. + }); + + testWidgets('removal cancels a running duration timer', (tester) async { + await tester.pumpWidget( + scene( + foreground: const BeamDecoration( brightness: Brightness.dark, + playback: BeamPlayback(duration: Duration(seconds: 5)), ), ), ); await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); expect(tester.binding.transientCallbackCount, greaterThan(0)); await tester.pumpWidget(const SizedBox()); expect(tester.binding.transientCallbackCount, 0); }); + }); + + group('ticking', () { + // A painter from [decoration] and the way to dispose it. Each test + // disposes its painter itself — flutter_test checks for live tickers + // before tear-downs run — and the tear-down only catches one that a + // failed expectation left behind. + VoidCallback paintWith(BeamDecoration decoration, VoidCallback onChanged) { + final painter = decoration.createBoxPainter(onChanged); + var disposed = false; + void dispose() { + if (disposed) return; + disposed = true; + painter.dispose(); + } + + addTearDown(dispose); + return dispose; + } + + testWidgets('calls onChanged on every clock tick', (tester) async { + var changes = 0; + final disposePainter = paintWith( + const BeamDecoration(brightness: Brightness.dark), + () => changes++, + ); + + await tester.pump(); + final afterFirst = changes; + await tester.pump(const Duration(milliseconds: 16)); + await tester.pump(const Duration(milliseconds: 16)); + expect(changes, greaterThan(afterFirst)); + + disposePainter(); + expect(tester.binding.transientCallbackCount, 0); + }); testWidgets('disposing the painter mid-fade leaves no ticker', ( tester, ) async { - final painter = const BeamDecoration( - variant: BeamVariant.pulseInside, - brightness: Brightness.light, - ).createBoxPainter(() {}); + final disposePainter = paintWith( + const BeamDecoration( + effect: BeamEffect.pulse(), + brightness: Brightness.light, + ), + () {}, + ); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(tester.binding.transientCallbackCount, greaterThan(0)); - painter.dispose(); + disposePainter(); expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('swapping decorations keeps exactly one ticker', ( + testWidgets('replacing the decoration disposes the old ticker', ( tester, ) async { await tester.pumpWidget( - scene( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - ), - ), + scene(foreground: const BeamDecoration(brightness: Brightness.dark)), ); await tester.pump(); - final before = tester.binding.transientCallbackCount; - - await tester.pumpWidget( - scene( - const BeamDecoration( - variant: BeamVariant.line, - brightness: Brightness.dark, + final running = tester.binding.transientCallbackCount; + expect(running, greaterThan(0)); + + for (final effect in [ + const BeamEffect.line(), + const BeamEffect.pulse(), + const BeamEffect.rotate(comet: true), + ]) { + await tester.pumpWidget( + scene( + foreground: BeamDecoration( + effect: effect, + brightness: Brightness.dark, + ), ), - ), - ); - await tester.pump(); + ); + await tester.pump(); + expect( + tester.binding.transientCallbackCount, + running, + reason: '$effect', + ); + } await tester.pump(const Duration(milliseconds: 1300)); + expect(litPixels(await capture(tester)), greaterThan(0)); - expect(tester.binding.transientCallbackCount, before); - expect(await paintedPixels(tester), greaterThan(0)); + await tester.pumpWidget(const SizedBox()); + expect(tester.binding.transientCallbackCount, 0); }); }); group('value semantics', () { const base = BeamDecoration( - variant: BeamVariant.rotate, + effect: BeamEffect.rotate(), brightness: Brightness.dark, colors: BeamColors.ocean, borderRadius: 16, ); test('equal field-for-field', () { - const same = BeamDecoration( - variant: BeamVariant.rotate, + // Built at run time: an equal const would be the same canonical + // instance, and `==` would never get past `identical`. + final same = BeamDecoration( + effect: const BeamEffect.rotate(), brightness: Brightness.dark, colors: BeamColors.ocean, - borderRadius: 16, + borderRadius: double.parse('16'), ); + expect(identical(base, same), isFalse); expect(base, equals(same)); expect(base.hashCode, same.hashCode); }); test('each field participates', () { - expect( - base, - isNot( - const BeamDecoration( - variant: BeamVariant.line, - brightness: Brightness.dark, - colors: BeamColors.ocean, - borderRadius: 16, - ), + const variants = { + 'effect': BeamDecoration( + effect: BeamEffect.line(), + brightness: Brightness.dark, + colors: BeamColors.ocean, + borderRadius: 16, ), - ); - expect( - base, - isNot( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.light, - colors: BeamColors.ocean, - borderRadius: 16, - ), + 'effect (unset)': BeamDecoration( + brightness: Brightness.dark, + colors: BeamColors.ocean, + borderRadius: 16, ), - ); - expect( - base, - isNot( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - colors: BeamColors.sunset, - borderRadius: 16, - ), + 'effect parameters': BeamDecoration( + effect: BeamEffect.rotate(count: 2), + brightness: Brightness.dark, + colors: BeamColors.ocean, + borderRadius: 16, ), - ); - expect( - base, - isNot( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - colors: BeamColors.ocean, - borderRadius: 24, - ), + 'brightness': BeamDecoration( + effect: BeamEffect.rotate(), + brightness: Brightness.light, + colors: BeamColors.ocean, + borderRadius: 16, ), - ); - expect( - base, - isNot( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - colors: BeamColors.ocean, - borderRadius: 16, - timing: BeamTiming(speed: 2), - ), + 'colors': BeamDecoration( + effect: BeamEffect.rotate(), + brightness: Brightness.dark, + colors: BeamColors.sunset, + borderRadius: 16, ), - ); - expect( - base, - isNot( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - colors: BeamColors.ocean, - borderRadius: 16, - theme: BorderBeamThemeData(style: BeamStyle(strength: 0.5)), - ), + 'borderRadius': BeamDecoration( + effect: BeamEffect.rotate(), + brightness: Brightness.dark, + colors: BeamColors.ocean, + borderRadius: 24, ), - ); - expect( - base, - isNot( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - colors: BeamColors.ocean, - borderRadius: 16, - active: false, - ), + 'active': BeamDecoration( + effect: BeamEffect.rotate(), + brightness: Brightness.dark, + colors: BeamColors.ocean, + borderRadius: 16, + active: false, ), - ); - expect( - base, - isNot( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - colors: BeamColors.ocean, - borderRadius: 16, - style: BeamStyle(sparkle: 0.5), - ), + 'theme': BeamDecoration( + effect: BeamEffect.rotate(), + brightness: Brightness.dark, + colors: BeamColors.ocean, + borderRadius: 16, + theme: BorderBeamThemeData(effect: BeamEffect.pulse()), ), - ); - expect( - base, - isNot( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - colors: BeamColors.ocean, - borderRadius: 16, - shape: BeamShape(borderWidth: 2), - ), + 'style': BeamDecoration( + effect: BeamEffect.rotate(), + brightness: Brightness.dark, + colors: BeamColors.ocean, + borderRadius: 16, + style: BeamStyle(strength: 0.5), ), - ); - expect( - base, - isNot( - const BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - colors: BeamColors.ocean, - borderRadius: 16, - playback: BeamPlayback(autoPlay: false), - ), + 'shape': BeamDecoration( + effect: BeamEffect.rotate(), + brightness: Brightness.dark, + colors: BeamColors.ocean, + borderRadius: 16, + shape: BeamShape(borderWidth: 2), ), - ); + 'timing': BeamDecoration( + effect: BeamEffect.rotate(), + brightness: Brightness.dark, + colors: BeamColors.ocean, + borderRadius: 16, + timing: BeamTiming(speed: 2), + ), + 'playback': BeamDecoration( + effect: BeamEffect.rotate(), + brightness: Brightness.dark, + colors: BeamColors.ocean, + borderRadius: 16, + playback: BeamPlayback(autoPlay: false), + ), + }; + for (final MapEntry(:key, :value) in variants.entries) { + expect(base, isNot(equals(value)), reason: key); + expect(base.hashCode, isNot(value.hashCode), reason: key); + } }); test('does not interpolate between two beam decorations', () { const other = BeamDecoration( - variant: BeamVariant.line, + effect: BeamEffect.line(), brightness: Brightness.dark, ); - // lerp falls back to the halfway snap Decoration.lerp does when - // neither side can interpolate. + // Decoration.lerp falls back to a halfway snap when neither side can + // interpolate. expect(Decoration.lerp(base, other, 0.25), same(base)); expect(Decoration.lerp(base, other, 0.75), same(other)); }); - testWidgets('never absorbs a pointer', (tester) async { + test('hitTest is always false', () { + const size = Size(200, 80); + for (final position in const [ + Offset(100, 40), + Offset.zero, + Offset(199, 79), + Offset(-10, 300), + ]) { + expect(base.hitTest(size, position), isFalse, reason: '$position'); + } + }); + + testWidgets('taps reach the widget beneath', (tester) async { var taps = 0; await tester.pumpWidget( MaterialApp( @@ -384,14 +584,11 @@ void main() { behavior: HitTestBehavior.opaque, onTap: () => taps++, ), - // Laid over the target. A Decoration whose hitTest returns - // true would swallow the tap here. + // Laid over the target. A decoration whose hitTest + // returned true would swallow the tap here. const Positioned.fill( child: DecoratedBox( - decoration: BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - ), + decoration: BeamDecoration(brightness: Brightness.dark), ), ), ], @@ -405,45 +602,199 @@ void main() { expect(taps, 1); }); - test('shorthands fold into the value objects for diagnostics', () { + test('describes its resolved values for diagnostics', () { final description = base.toDiagnosticsNode().toStringDeep(); - expect(description, contains('variant: rotate')); + expect(description, contains('effect: BeamEffect.rotate(')); expect(description, contains('brightness: dark')); expect(description, contains('BeamStyle(colors:')); expect(description, contains('BorderRadius.circular(16.0)')); }); }); - group('theme inheritance', () { - testWidgets('takes its defaults from the BorderBeamThemeData passed in', ( + group('theme slot', () { + test('value objects merge under the decoration\'s own', () { + const theme = BorderBeamThemeData( + style: BeamStyle(colors: BeamColors.sunset, strength: 0.5, glow: 0.8), + shape: BeamShape(borderWidth: 2, superellipse: true), + timing: BeamTiming(cycle: Duration(seconds: 3), speed: 2), + playback: BeamPlayback( + autoPlay: false, + startAfter: Duration(seconds: 2), + ), + ); + const decoration = BeamDecoration( + brightness: Brightness.dark, + theme: theme, + colors: BeamColors.ocean, + style: BeamStyle(colors: BeamColors.candy, glow: 0.2), + borderRadius: 24, + shape: BeamShape(borderWidth: 3), + timing: BeamTiming(speed: 4), + active: false, + playback: BeamPlayback(autoPlay: true), + ); + + // Own fields win (the shorthands over their value objects), every + // field left null falls through to the theme. + expect( + resolved(decoration, 'style'), + const BeamStyle(colors: BeamColors.ocean, strength: 0.5, glow: 0.2), + ); + expect( + resolved(decoration, 'shape'), + const BeamShape.all(24, borderWidth: 3, superellipse: true), + ); + expect( + resolved(decoration, 'timing'), + const BeamTiming(cycle: Duration(seconds: 3), speed: 4), + ); + expect( + resolved(decoration, 'playback'), + const BeamPlayback( + active: false, + autoPlay: true, + startAfter: Duration(seconds: 2), + ), + ); + }); + + test('the theme\'s effect is inherited; the decoration\'s own wins', () { + const theme = BorderBeamThemeData(effect: BeamEffect.pulse()); + expect( + resolved( + const BeamDecoration(brightness: Brightness.dark, theme: theme), + 'effect', + ), + const BeamEffect.pulse(), + ); + expect( + resolved( + const BeamDecoration( + effect: BeamEffect.line(edge: BeamEdge.top), + brightness: Brightness.dark, + theme: theme, + ), + 'effect', + ), + const BeamEffect.line(edge: BeamEdge.top), + ); + expect( + resolved( + const BeamDecoration(brightness: Brightness.dark), + 'effect', + ), + const BeamEffect.rotate(), + ); + }); + + testWidgets('the painter draws the effect the theme resolves to', ( tester, ) async { - const themed = BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - theme: BorderBeamThemeData(playback: BeamPlayback(active: false)), + const lineTheme = BorderBeamThemeData(effect: BeamEffect.line()); + final inherited = await frame( + tester, + const BeamDecoration( + brightness: Brightness.dark, + theme: lineTheme, + playback: frozen, + ), + ); + final explicit = await frame( + tester, + const BeamDecoration( + effect: BeamEffect.line(), + brightness: Brightness.dark, + playback: frozen, + ), + ); + final rotate = await frame( + tester, + const BeamDecoration(brightness: Brightness.dark, playback: frozen), + ); + final overridden = await frame( + tester, + const BeamDecoration( + effect: BeamEffect.rotate(), + brightness: Brightness.dark, + theme: lineTheme, + playback: frozen, + ), ); - await tester.pumpWidget(scene(themed)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1300)); - expect(await paintedPixels(tester), 0); + expect(litPixels(inherited), greaterThan(0)); + expect(listEquals(inherited, explicit), isTrue); + expect(listEquals(overridden, rotate), isTrue); + expect(listEquals(inherited, rotate), isFalse); }); - testWidgets('a decoration value wins over the theme it was given', ( + testWidgets('theme playback is inherited; the own active wins', ( tester, ) async { - const themed = BeamDecoration( - variant: BeamVariant.rotate, - brightness: Brightness.dark, - active: true, - theme: BorderBeamThemeData(playback: BeamPlayback(active: false)), + const dormant = BorderBeamThemeData( + playback: BeamPlayback(active: false), + ); + for (final (active, lit) in [(null, false), (true, true)]) { + await tester.pumpWidget( + scene( + foreground: BeamDecoration( + brightness: Brightness.dark, + active: active, + theme: dormant, + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1300)); + + final pixels = litPixels(await capture(tester)); + expect(pixels, lit ? greaterThan(0) : 0, reason: 'active: $active'); + await tester.pumpWidget(const SizedBox()); + } + }); + }); + + group('brightness', () { + testWidgets('style.theme overrides the ambient brightness', (tester) async { + final dark = await frame( + tester, + const BeamDecoration(brightness: Brightness.dark, playback: frozen), + ); + final light = await frame( + tester, + const BeamDecoration(brightness: Brightness.light, playback: frozen), + ); + final forcedLight = await frame( + tester, + const BeamDecoration( + brightness: Brightness.dark, + style: BeamStyle(theme: BeamTheme.light), + playback: frozen, + ), + ); + final forcedDark = await frame( + tester, + const BeamDecoration( + brightness: Brightness.light, + style: BeamStyle(theme: BeamTheme.dark), + playback: frozen, + ), + ); + final auto = await frame( + tester, + const BeamDecoration( + brightness: Brightness.light, + style: BeamStyle(theme: BeamTheme.auto), + playback: frozen, + ), ); - await tester.pumpWidget(scene(themed)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1300)); - expect(await paintedPixels(tester), greaterThan(0)); + // The two surfaces really do render differently... + expect(listEquals(dark, light), isFalse); + // ...and an explicit theme picks one regardless of the ambient value, + // while auto follows it. + expect(listEquals(forcedLight, light), isTrue); + expect(listEquals(forcedDark, dark), isTrue); + expect(listEquals(auto, light), isTrue); }); }); } diff --git a/test/widgets/beam_focus_ring_test.dart b/test/widgets/beam_focus_ring_test.dart index a6d6581..f8c8ed0 100644 --- a/test/widgets/beam_focus_ring_test.dart +++ b/test/widgets/beam_focus_ring_test.dart @@ -1,6 +1,9 @@ -import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +import '../widget/test_utils.dart' show beamPainterOf; /// [BeamFocusRing] is a thin composition: it only decides `active` on the /// [BorderBeam] it wraps, from focus plus [FocusManager.highlightMode]. Every @@ -8,8 +11,8 @@ import 'package:flutter_test/flutter_test.dart'; void main() { // The test binding reports the Android platform, whose automatic highlight // mode is `touch` — the mode under which the ring deliberately stays dark. - // Focus tracking is asserted under traditional highlighting; the - // highlight-mode group sets its own. + // Focus tracking is asserted under traditional highlighting; the groups + // that care about the mode set their own. setUp(() { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; @@ -19,8 +22,22 @@ void main() { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.automatic; }); - bool? ringActive(WidgetTester tester) => - tester.widget(find.byType(BorderBeam)).active; + BorderBeam beamOf(WidgetTester tester) => + tester.widget(find.byType(BorderBeam)); + + bool? ringActive(WidgetTester tester) => beamOf(tester).active; + + // The Focus the ring inserts around its child when given no node. + FocusNode internalNode(WidgetTester tester) => tester + .widget( + find + .descendant( + of: find.byType(BeamFocusRing), + matching: find.byType(Focus), + ) + .first, + ) + .focusNode!; // A focus change lands over two frames: the manager applies it during the // first, and the node's notification rebuilds the ring in the second. @@ -34,8 +51,10 @@ void main() { home: Scaffold(body: Center(child: child)), ); + Widget box() => const SizedBox(width: 200, height: 60); + group('focus tracking', () { - testWidgets('lights while the wrapped subtree holds focus', (tester) async { + testWidgets('focus lights the ring and blur darkens it', (tester) async { final node = FocusNode(); addTearDown(node.dispose); @@ -51,6 +70,8 @@ void main() { ), ); expect(ringActive(tester), isFalse); + // An unfocused ring costs nothing: its beam never started a clock. + expect(tester.binding.transientCallbackCount, 0); node.requestFocus(); await settleFocus(tester); @@ -61,60 +82,182 @@ void main() { expect(ringActive(tester), isFalse); }); - testWidgets('follows an explicitly given node instead', (tester) async { - final node = FocusNode(); - final other = FocusNode(); - addTearDown(node.dispose); - addTearDown(other.dispose); + testWidgets('lights for focus anywhere inside its subtree', (tester) async { + final deep = FocusNode(); + addTearDown(deep.dispose); + + await tester.pumpWidget( + scene( + BeamFocusRing( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(height: 20), + Padding( + padding: const EdgeInsets.all(4), + child: Focus(focusNode: deep, child: box()), + ), + ], + ), + ), + ), + ); + deep.requestFocus(); + await settleFocus(tester); + expect(ringActive(tester), isTrue); + }); + + testWidgets('keyboard traversal moves the ring with focus', (tester) async { + // Automatic highlighting, as in an app: the key presses themselves + // switch the highlight mode to traditional. + FocusManager.instance.highlightStrategy = + FocusHighlightStrategy.automatic; + final inside = FocusNode(debugLabel: 'inside'); + final outside = FocusNode(debugLabel: 'outside'); + addTearDown(inside.dispose); + addTearDown(outside.dispose); await tester.pumpWidget( scene( Column( mainAxisSize: MainAxisSize.min, children: [ - Focus(focusNode: other, child: const SizedBox(height: 20)), BeamFocusRing( - focusNode: node, - child: Focus( - focusNode: node, - child: const SizedBox(width: 200, height: 60), - ), + child: Focus(focusNode: inside, child: box()), ), + Focus(focusNode: outside, child: box()), ], ), ), ); expect(ringActive(tester), isFalse); - other.requestFocus(); + // The ring's own Focus is skipped by traversal, so the first Tab lands + // on the field inside it, not on the ring. + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await settleFocus(tester); + expect(inside.hasPrimaryFocus, isTrue); + expect( + FocusManager.instance.highlightMode, + FocusHighlightMode.traditional, + ); + expect(ringActive(tester), isTrue); + + await tester.sendKeyEvent(LogicalKeyboardKey.tab); await settleFocus(tester); + expect(outside.hasPrimaryFocus, isTrue); expect(ringActive(tester), isFalse); - node.requestFocus(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); await settleFocus(tester); + expect(inside.hasPrimaryFocus, isTrue); expect(ringActive(tester), isTrue); }); - testWidgets('an explicit node adds no Focus of its own', (tester) async { + testWidgets('disposal with focus held leaves no ticker behind', ( + tester, + ) async { final node = FocusNode(); addTearDown(node.dispose); await tester.pumpWidget( scene( BeamFocusRing( - focusNode: node, - child: const SizedBox(width: 200, height: 60), + child: Focus(focusNode: node, child: box()), ), ), ); + node.requestFocus(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(tester.binding.transientCallbackCount, greaterThan(0)); + + await tester.pumpWidget(const SizedBox()); + expect(tester.binding.transientCallbackCount, 0); + }); + }); + group('focus node ownership', () { + testWidgets('without a node it inserts a non-focusable Focus it owns', ( + tester, + ) async { + await tester.pumpWidget(scene(BeamFocusRing(child: box()))); + + final internal = internalNode(tester); + expect(internal.canRequestFocus, isFalse); + expect(internal.skipTraversal, isTrue); + + await tester.pumpWidget(const SizedBox()); + // Disposed with the ring: a disposed node rejects new listeners. + expect(() => internal.addListener(() {}), throwsFlutterError); + }); + + testWidgets('follows an explicitly given node instead', (tester) async { + final node = FocusNode(); + final other = FocusNode(); + addTearDown(node.dispose); + addTearDown(other.dispose); + + await tester.pumpWidget( + scene( + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Focus(focusNode: other, child: const SizedBox(height: 20)), + // The followed node lives outside the ring's subtree. + Focus(focusNode: node, child: const SizedBox(height: 20)), + BeamFocusRing(focusNode: node, child: box()), + ], + ), + ), + ); + expect(ringActive(tester), isFalse); expect( find.descendant( of: find.byType(BeamFocusRing), matching: find.byType(Focus), ), findsNothing, + reason: 'an explicit node adds no Focus of its own', ); + + other.requestFocus(); + await settleFocus(tester); + expect(ringActive(tester), isFalse); + + node.requestFocus(); + await settleFocus(tester); + expect(ringActive(tester), isTrue); + }); + + testWidgets('never disposes a node it was given', (tester) async { + final node = FocusNode(); + addTearDown(node.dispose); + + await tester.pumpWidget( + scene( + BeamFocusRing( + focusNode: node, + child: Focus(focusNode: node, child: box()), + ), + ), + ); + node.requestFocus(); + await settleFocus(tester); + expect(ringActive(tester), isTrue); + + await tester.pumpWidget(const SizedBox()); + // Still alive: it takes listeners and can be focused again elsewhere. + void listener() {} + expect(() => node.addListener(listener), returnsNormally); + node.removeListener(listener); + + await tester.pumpWidget(scene(Focus(focusNode: node, child: box()))); + node.requestFocus(); + await settleFocus(tester); + expect(node.hasPrimaryFocus, isTrue); }); testWidgets('swapping the node moves the ring with it', (tester) async { @@ -129,10 +272,7 @@ void main() { children: [ Focus(focusNode: first, child: const SizedBox(height: 20)), Focus(focusNode: second, child: const SizedBox(height: 20)), - BeamFocusRing( - focusNode: node, - child: const SizedBox(width: 200, height: 60), - ), + BeamFocusRing(focusNode: node, child: box()), ], ), ); @@ -151,29 +291,37 @@ void main() { expect(ringActive(tester), isTrue); }); - testWidgets('disposal with focus held leaves no ticker behind', ( + testWidgets('switching to a given node disposes the internal one', ( tester, ) async { - final node = FocusNode(); - addTearDown(node.dispose); + final given = FocusNode(); + addTearDown(given.dispose); - await tester.pumpWidget( - scene( - BeamFocusRing( - child: Focus( - focusNode: node, - child: const SizedBox(width: 200, height: 60), - ), - ), + Widget build({FocusNode? node}) => scene( + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Focus(focusNode: given, child: const SizedBox(height: 20)), + BeamFocusRing(focusNode: node, child: box()), + ], ), ); - node.requestFocus(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 300)); - expect(tester.binding.transientCallbackCount, greaterThan(0)); - await tester.pumpWidget(const SizedBox()); - expect(tester.binding.transientCallbackCount, 0); + await tester.pumpWidget(build()); + final internal = internalNode(tester); + + await tester.pumpWidget(build(node: given)); + expect(() => internal.addListener(() {}), throwsFlutterError); + + given.requestFocus(); + await settleFocus(tester); + expect(ringActive(tester), isTrue); + + // And back: a fresh internal node takes over. + await tester.pumpWidget(build()); + await settleFocus(tester); + expect(internalNode(tester), isNot(same(internal))); + expect(ringActive(tester), isFalse); }); }); @@ -187,16 +335,14 @@ void main() { await tester.pumpWidget( scene( BeamFocusRing( - child: Focus( - focusNode: node, - child: const SizedBox(width: 200, height: 60), - ), + child: Focus(focusNode: node, child: box()), ), ), ); node.requestFocus(); await settleFocus(tester); + expect(node.hasFocus, isTrue); expect(ringActive(tester), isFalse); }); @@ -212,16 +358,18 @@ void main() { scene( BeamFocusRing( alwaysShow: true, - child: Focus( - focusNode: node, - child: const SizedBox(width: 200, height: 60), - ), + child: Focus(focusNode: node, child: box()), ), ), ); + expect( + ringActive(tester), + isFalse, + reason: 'alwaysShow still needs focus', + ); + node.requestFocus(); await settleFocus(tester); - expect(ringActive(tester), isTrue); }); @@ -234,10 +382,7 @@ void main() { await tester.pumpWidget( scene( BeamFocusRing( - child: Focus( - focusNode: node, - child: const SizedBox(width: 200, height: 60), - ), + child: Focus(focusNode: node, child: box()), ), ), ); @@ -249,17 +394,81 @@ void main() { FocusHighlightStrategy.alwaysTraditional; await settleFocus(tester); expect(ringActive(tester), isTrue); + + FocusManager.instance.highlightStrategy = + FocusHighlightStrategy.alwaysTouch; + await settleFocus(tester); + expect(ringActive(tester), isFalse); }); }); group('pass-through', () { - testWidgets('hands its style, shape and timing to the beam', ( + testWidgets('defaults to an ocean rotating beam', (tester) async { + await tester.pumpWidget(scene(BeamFocusRing(child: box()))); + + final beam = beamOf(tester); + expect(beam.effect, const BeamEffect.rotate()); + expect(beam.colors, BeamColors.ocean); + }); + + testWidgets('style colours win over the ocean default', (tester) async { + await tester.pumpWidget( + scene( + BeamFocusRing( + alwaysShow: true, + style: const BeamStyle(colors: BeamColors.sunset), + child: box(), + ), + ), + ); + + expect(beamOf(tester).colors, isNull); + expect(beamPainterOf(tester).config.palette, BeamColors.sunset.resolve()); + }); + + testWidgets('theme colours win over the ocean default', (tester) async { + await tester.pumpWidget( + scene( + BorderBeamTheme( + data: const BorderBeamThemeData( + style: BeamStyle(colors: BeamColors.sunset), + ), + child: BeamFocusRing(alwaysShow: true, child: box()), + ), + ), + ); + + expect(beamOf(tester).colors, isNull); + expect(beamPainterOf(tester).config.palette, BeamColors.sunset.resolve()); + }); + + testWidgets('its own colors win over style and theme', (tester) async { + await tester.pumpWidget( + scene( + BorderBeamTheme( + data: const BorderBeamThemeData( + style: BeamStyle(colors: BeamColors.sunset), + ), + child: BeamFocusRing( + alwaysShow: true, + colors: BeamColors.forest, + style: const BeamStyle(colors: BeamColors.sunset), + child: box(), + ), + ), + ), + ); + + expect(beamPainterOf(tester).config.palette, BeamColors.forest.resolve()); + }); + + testWidgets('hands its effect, style, shape and timing to the beam', ( tester, ) async { await tester.pumpWidget( scene( const BeamFocusRing( - variant: BeamVariant.line, + effect: BeamEffect.line(edge: BeamEdge.top), colors: BeamColors.sunset, borderRadius: 12, style: BeamStyle(strength: 0.5), @@ -270,8 +479,8 @@ void main() { ), ); - final beam = tester.widget(find.byType(BorderBeam)); - expect(beam.variant, BeamVariant.line); + final beam = beamOf(tester); + expect(beam.effect, const BeamEffect.line(edge: BeamEdge.top)); expect(beam.colors, BeamColors.sunset); expect(beam.borderRadius, 12); expect(beam.style, const BeamStyle(strength: 0.5)); @@ -279,24 +488,9 @@ void main() { expect(beam.timing, const BeamTiming(speed: 2)); }); - testWidgets('defaults to the compact ocean ring', (tester) async { - await tester.pumpWidget( - scene(const BeamFocusRing(child: SizedBox(width: 200, height: 60))), - ); - - final beam = tester.widget(find.byType(BorderBeam)); - expect(beam.variant, BeamVariant.small); - expect(beam.colors, BeamColors.ocean); - }); - testWidgets('describes itself for the inspector', (tester) async { await tester.pumpWidget( - scene( - const BeamFocusRing( - alwaysShow: true, - child: SizedBox(width: 200, height: 60), - ), - ), + scene(BeamFocusRing(alwaysShow: true, child: box())), ); final description = tester @@ -304,7 +498,7 @@ void main() { .toDiagnosticsNode() .toStringDeep(); expect(description, contains('alwaysShow')); - expect(description, contains('variant: small')); + expect(description, contains('effect: ${const BeamEffect.rotate()}')); }); }); } diff --git a/test/widgets/beam_hover_test.dart b/test/widgets/beam_hover_test.dart index b3c3df4..55fe81c 100644 --- a/test/widgets/beam_hover_test.dart +++ b/test/widgets/beam_hover_test.dart @@ -1,7 +1,8 @@ import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; +import 'package:flutter_border_beam/src/render/beam_painter.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; /// [BeamHover] turns a [MouseRegion] into two values on the [BorderBeam] it /// wraps: `active` (lit while hovered, held for `holdAfterExit` after) and @@ -12,6 +13,19 @@ void main() { BorderBeam beamOf(WidgetTester tester) => tester.widget(find.byType(BorderBeam)); + BeamPainter painterOf(WidgetTester tester) => + tester + .widget( + find + .descendant( + of: find.byType(BorderBeam), + matching: find.byType(CustomPaint), + ) + .first, + ) + .foregroundPainter! + as BeamPainter; + Widget scene({ bool followPointer = true, Duration holdAfterExit = const Duration(milliseconds: 300), @@ -28,13 +42,16 @@ void main() { ), ); - Future hoverGesture(WidgetTester tester) async { + Future mouse(WidgetTester tester) async { final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); addTearDown(gesture.removePointer); return gesture; } + // A point well clear of the hovered box. + const away = Offset(5, 5); + group('hover tracking', () { testWidgets('entering lights the beam and follows the cursor', ( tester, @@ -42,8 +59,9 @@ void main() { await tester.pumpWidget(scene()); expect(beamOf(tester).active, isFalse); expect(beamOf(tester).follow, isNull); + expect(tester.binding.transientCallbackCount, 0); - final gesture = await hoverGesture(tester); + final gesture = await mouse(tester); await gesture.moveTo(tester.getCenter(find.byType(BeamHover))); await tester.pump(); @@ -53,7 +71,7 @@ void main() { testWidgets('moving inside re-aims the follow point', (tester) async { await tester.pumpWidget(scene()); - final gesture = await hoverGesture(tester); + final gesture = await mouse(tester); final topLeft = tester.getTopLeft(find.byType(BeamHover)); await gesture.moveTo(topLeft + const Offset(50, 20)); @@ -65,28 +83,89 @@ void main() { expect(beamOf(tester).follow, const Offset(0.75, 0.75)); }); - testWidgets('the follow point stays inside the box at the edges', ( + testWidgets('the follow point is normalized to 0–1 on both axes', ( tester, ) async { await tester.pumpWidget(scene()); - final gesture = await hoverGesture(tester); - final topLeft = tester.getTopLeft(find.byType(BeamHover)); + final gesture = await mouse(tester); + final rect = tester.getRect(find.byType(BeamHover)); + + for (final point in [ + rect.topLeft, + rect.bottomRight - const Offset(0.5, 0.5), + rect.centerLeft, + rect.topCenter, + ]) { + await gesture.moveTo(point); + await tester.pump(); + final follow = beamOf(tester).follow!; + expect(follow.dx, inInclusiveRange(0, 1), reason: '$point'); + expect(follow.dy, inInclusiveRange(0, 1), reason: '$point'); + } + await gesture.moveTo(rect.topLeft); + await tester.pump(); + expect(beamOf(tester).follow, Offset.zero); + }); - await gesture.moveTo(topLeft); + testWidgets('the follow reaches the painter as a driven sweep', ( + tester, + ) async { + await tester.pumpWidget(scene()); + expect(painterOf(tester).progress?.value, isNull); + + final gesture = await mouse(tester); + // Just inside the right edge's centre: a quarter of the way round from + // top-centre, where the sweep settles once it has eased over. + final rect = tester.getRect(find.byType(BeamHover)); + await gesture.moveTo(rect.centerRight - const Offset(1, 0)); await tester.pump(); - final follow = beamOf(tester).follow!; - expect(follow.dx, inInclusiveRange(0, 1)); - expect(follow.dy, inInclusiveRange(0, 1)); + for (var i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 16)); + } + final early = painterOf(tester).progress?.value; + expect(early, isNotNull); + expect(early, inInclusiveRange(0, 0.25)); + for (var i = 0; i < 40; i++) { + await tester.pump(const Duration(milliseconds: 16)); + } + expect(painterOf(tester).progress?.value, closeTo(0.25, 0.01)); + + // Leaving hands the sweep straight back to the clock. + await gesture.moveTo(away); + await tester.pump(); + expect(painterOf(tester).progress?.value, isNull); }); - testWidgets('followPointer false lights without steering', (tester) async { + testWidgets('followPointer false lights without ever steering', ( + tester, + ) async { await tester.pumpWidget(scene(followPointer: false)); - final gesture = await hoverGesture(tester); + final gesture = await mouse(tester); + final rect = tester.getRect(find.byType(BeamHover)); + + for (final point in [rect.center, rect.topLeft, rect.centerRight]) { + await gesture.moveTo(point); + await tester.pump(); + expect(beamOf(tester).active, isTrue); + expect(beamOf(tester).follow, isNull, reason: '$point'); + } + await gesture.moveTo(away); + await tester.pump(); + expect(beamOf(tester).follow, isNull); + }); + + testWidgets('turning followPointer off mid-hover releases the follow', ( + tester, + ) async { + await tester.pumpWidget(scene()); + final gesture = await mouse(tester); await gesture.moveTo(tester.getCenter(find.byType(BeamHover))); await tester.pump(); + expect(beamOf(tester).follow, isNotNull); - expect(beamOf(tester).active, isTrue); + await tester.pumpWidget(scene(followPointer: false)); expect(beamOf(tester).follow, isNull); + expect(beamOf(tester).active, isTrue); }); }); @@ -95,11 +174,11 @@ void main() { tester, ) async { await tester.pumpWidget(scene()); - final gesture = await hoverGesture(tester); + final gesture = await mouse(tester); await gesture.moveTo(tester.getCenter(find.byType(BeamHover))); await tester.pump(); - await gesture.moveTo(const Offset(5, 5)); + await gesture.moveTo(away); await tester.pump(); expect(beamOf(tester).follow, isNull, reason: 'released on exit'); expect(beamOf(tester).active, isTrue, reason: 'still inside the hold'); @@ -111,57 +190,80 @@ void main() { expect(beamOf(tester).active, isFalse); }); - testWidgets('re-entering within the hold keeps the beam lit', ( - tester, - ) async { + testWidgets('a zero hold deactivates on exit', (tester) async { + await tester.pumpWidget(scene(holdAfterExit: Duration.zero)); + final gesture = await mouse(tester); + await gesture.moveTo(tester.getCenter(find.byType(BeamHover))); + await tester.pump(); + + await gesture.moveTo(away); + await tester.pump(); + expect(beamOf(tester).active, isFalse); + expect(beamOf(tester).follow, isNull); + }); + + testWidgets('re-entering within the hold cancels the fade', (tester) async { await tester.pumpWidget(scene()); - final gesture = await hoverGesture(tester); + final gesture = await mouse(tester); final center = tester.getCenter(find.byType(BeamHover)); await gesture.moveTo(center); await tester.pump(); - await gesture.moveTo(const Offset(5, 5)); + await gesture.moveTo(away); await tester.pump(const Duration(milliseconds: 200)); await gesture.moveTo(center); + await tester.pump(); + // Well past where the first exit's hold would have ended. await tester.pump(const Duration(milliseconds: 400)); expect(beamOf(tester).active, isTrue); expect(beamOf(tester).follow, const Offset(0.5, 0.5)); }); - testWidgets('a zero hold fades out on exit', (tester) async { - await tester.pumpWidget(scene(holdAfterExit: Duration.zero)); - final gesture = await hoverGesture(tester); + testWidgets('the beam winds down to no ticker after the fade', ( + tester, + ) async { + await tester.pumpWidget(scene()); + final gesture = await mouse(tester); await gesture.moveTo(tester.getCenter(find.byType(BeamHover))); await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(tester.binding.transientCallbackCount, greaterThan(0)); - await gesture.moveTo(const Offset(5, 5)); + await gesture.moveTo(away); await tester.pump(); + // Past the 300ms hold, then past the beam's fade-out + // (BeamClock.fadeOutSeconds), with room to spare. + for (var i = 0; i < 12; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } expect(beamOf(tester).active, isFalse); - expect(beamOf(tester).follow, isNull); + expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('unmounting during the hold leaves no timer or ticker', ( - tester, - ) async { + testWidgets('unmounting during the hold cancels the timer', (tester) async { await tester.pumpWidget(scene()); - final gesture = await hoverGesture(tester); + final gesture = await mouse(tester); await gesture.moveTo(tester.getCenter(find.byType(BeamHover))); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); - expect(tester.binding.transientCallbackCount, greaterThan(0)); - await gesture.moveTo(const Offset(5, 5)); + await gesture.moveTo(away); await tester.pump(); await tester.pumpWidget(const SizedBox()); - await tester.pump(const Duration(seconds: 1)); - expect(tester.binding.transientCallbackCount, 0); + // Ending inside the hold: a timer dispose failed to cancel fails the + // binding's no-pending-timers invariant. }); }); group('pass-through', () { - testWidgets('hands its style, shape and timing to the beam', ( + testWidgets('defaults to a rotating beam', (tester) async { + await tester.pumpWidget(scene()); + expect(beamOf(tester).effect, const BeamEffect.rotate()); + }); + + testWidgets('hands its effect, style, shape and timing to the beam', ( tester, ) async { await tester.pumpWidget( @@ -169,7 +271,7 @@ void main() { home: Scaffold( body: Center( child: BeamHover( - variant: BeamVariant.small, + effect: BeamEffect.rotate(count: 2, comet: true), colors: BeamColors.sunset, borderRadius: 18, style: BeamStyle(strength: 0.7), @@ -183,7 +285,7 @@ void main() { ); final beam = beamOf(tester); - expect(beam.variant, BeamVariant.small); + expect(beam.effect, const BeamEffect.rotate(count: 2, comet: true)); expect(beam.colors, BeamColors.sunset); expect(beam.borderRadius, 18); expect(beam.style, const BeamStyle(strength: 0.7)); @@ -198,7 +300,7 @@ void main() { .toDiagnosticsNode() .toStringDeep(); expect(description, contains('does not follow the pointer')); - expect(description, contains('variant: rotate')); + expect(description, contains('effect: BeamEffect.rotate(')); }); }); } diff --git a/test/widgets/beam_press_test.dart b/test/widgets/beam_press_test.dart index c35f567..9783e5c 100644 --- a/test/widgets/beam_press_test.dart +++ b/test/widgets/beam_press_test.dart @@ -1,14 +1,16 @@ -import 'package:flutter/material.dart'; import 'package:flutter_border_beam/flutter_border_beam.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; /// [BeamPress] observes raw pointers and only flips `active` on the /// [BorderBeam] it wraps. The two things it must never get wrong: a tap /// shorter than [BeamPress.minimumDuration] still shows a full pulse, and the /// child's own gestures keep working. void main() { - bool? pressActive(WidgetTester tester) => - tester.widget(find.byType(BorderBeam)).active; + BorderBeam beamOf(WidgetTester tester) => + tester.widget(find.byType(BorderBeam)); + + bool? pressActive(WidgetTester tester) => beamOf(tester).active; Widget scene(Widget child) => MaterialApp( debugShowCheckedModeBanner: false, @@ -23,32 +25,51 @@ void main() { BeamPress(onTap: onTap, minimumDuration: minimumDuration, child: child), ); + Future pressDown(WidgetTester tester) async { + final gesture = await tester.startGesture( + tester.getCenter(find.byType(BeamPress)), + ); + await tester.pump(); + return gesture; + } + + Widget pressableList(ScrollController controller) => scene( + SizedBox( + height: 300, + child: ListView( + controller: controller, + children: [ + for (var i = 0; i < 12; i++) + const BeamPress(child: SizedBox(height: 80)), + ], + ), + ), + ); + group('press lifecycle', () { testWidgets('lights on pointer down', (tester) async { await tester.pumpWidget(press()); expect(pressActive(tester), isFalse); + expect(tester.binding.transientCallbackCount, 0); - final gesture = await tester.startGesture( - tester.getCenter(find.byType(BeamPress)), - ); - await tester.pump(); + final gesture = await pressDown(tester); expect(pressActive(tester), isTrue); await gesture.up(); await tester.pump(const Duration(seconds: 1)); }); - testWidgets('a quick tap still holds the minimum duration', (tester) async { + testWidgets('a quick tap stays lit until the minimum since the press', ( + tester, + ) async { await tester.pumpWidget(press()); - final gesture = await tester.startGesture( - tester.getCenter(find.byType(BeamPress)), - ); - await tester.pump(); + final gesture = await pressDown(tester); await tester.pump(const Duration(milliseconds: 50)); await gesture.up(); await tester.pump(); expect(pressActive(tester), isTrue, reason: 'released before minimum'); + // 50ms + 500ms: the minimum runs from the press, not the release. await tester.pump(const Duration(milliseconds: 500)); expect(pressActive(tester), isTrue, reason: 'still inside minimum'); @@ -60,12 +81,9 @@ void main() { tester, ) async { await tester.pumpWidget(press()); - final gesture = await tester.startGesture( - tester.getCenter(find.byType(BeamPress)), - ); - await tester.pump(); + final gesture = await pressDown(tester); await tester.pump(const Duration(seconds: 2)); - expect(pressActive(tester), isTrue); + expect(pressActive(tester), isTrue, reason: 'held past the minimum'); await gesture.up(); await tester.pump(); @@ -74,10 +92,7 @@ void main() { testWidgets('a zero minimum releases on pointer up', (tester) async { await tester.pumpWidget(press(minimumDuration: Duration.zero)); - final gesture = await tester.startGesture( - tester.getCenter(find.byType(BeamPress)), - ); - await tester.pump(); + final gesture = await pressDown(tester); expect(pressActive(tester), isTrue); await gesture.up(); @@ -89,15 +104,16 @@ void main() { tester, ) async { await tester.pumpWidget(press()); - final gesture = await tester.startGesture( - tester.getCenter(find.byType(BeamPress)), - ); - await tester.pump(); + final gesture = await pressDown(tester); expect(pressActive(tester), isTrue); await gesture.cancel(); await tester.pump(); expect(pressActive(tester), isFalse); + + // And the cancelled hold's timer does not resurrect or re-drop it. + await tester.pump(const Duration(seconds: 1)); + expect(pressActive(tester), isFalse); }); testWidgets('a second finger does not restart the hold', (tester) async { @@ -119,21 +135,38 @@ void main() { await tester.pump(const Duration(seconds: 1)); }); - testWidgets('disposal mid-hold leaves no ticker and no pending timer', ( + testWidgets('the beam winds down to no ticker after release', ( tester, ) async { await tester.pumpWidget(press()); - final gesture = await tester.startGesture( - tester.getCenter(find.byType(BeamPress)), - ); - await tester.pump(); + final gesture = await pressDown(tester); await tester.pump(const Duration(milliseconds: 100)); expect(tester.binding.transientCallbackCount, greaterThan(0)); - await tester.pumpWidget(const SizedBox()); await gesture.up(); + // Past the 600ms minimum, then past the beam's 0.5s fade-out. + for (var i = 0; i < 12; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(pressActive(tester), isFalse); expect(tester.binding.transientCallbackCount, 0); }); + + testWidgets('disposal mid-hold leaves no ticker and no pending timer', ( + tester, + ) async { + await tester.pumpWidget(press()); + final gesture = await pressDown(tester); + await tester.pump(const Duration(milliseconds: 100)); + await gesture.up(); + await tester.pump(); + expect(pressActive(tester), isTrue, reason: 'held by the minimum timer'); + + await tester.pumpWidget(const SizedBox()); + expect(tester.binding.transientCallbackCount, 0); + // Ending inside the minimum: a timer dispose failed to cancel fails + // the binding's no-pending-timers invariant. + }); }); group('gestures', () { @@ -142,8 +175,8 @@ void main() { await tester.pumpWidget(press(onTap: () => taps++)); await tester.tap(find.byType(BeamPress)); - await tester.pump(const Duration(seconds: 1)); expect(taps, 1); + await tester.pump(const Duration(seconds: 1)); }); testWidgets('onTap does not fire when the pointer lifts outside', ( @@ -152,10 +185,7 @@ void main() { var taps = 0; await tester.pumpWidget(press(onTap: () => taps++)); - final gesture = await tester.startGesture( - tester.getCenter(find.byType(BeamPress)), - ); - await tester.pump(); + final gesture = await pressDown(tester); await gesture.moveTo(const Offset(5, 5)); await gesture.up(); await tester.pump(const Duration(seconds: 1)); @@ -163,6 +193,17 @@ void main() { expect(taps, 0); }); + testWidgets('a cancelled press does not tap', (tester) async { + var taps = 0; + await tester.pumpWidget(press(onTap: () => taps++)); + + final gesture = await pressDown(tester); + await gesture.cancel(); + await tester.pump(const Duration(seconds: 1)); + + expect(taps, 0); + }); + testWidgets('the child keeps receiving its own taps', (tester) async { var childTaps = 0; var pressTaps = 0; @@ -192,21 +233,7 @@ void main() { ) async { final controller = ScrollController(); addTearDown(controller.dispose); - - await tester.pumpWidget( - scene( - SizedBox( - height: 300, - child: ListView( - controller: controller, - children: [ - for (var i = 0; i < 12; i++) - const BeamPress(child: SizedBox(height: 80)), - ], - ), - ), - ), - ); + await tester.pumpWidget(pressableList(controller)); await tester.drag(find.byType(BeamPress).first, const Offset(0, -200)); await tester.pumpAndSettle(); @@ -214,40 +241,25 @@ void main() { expect(controller.offset, greaterThan(0)); }); - testWidgets('a stolen gesture cancels the press', (tester) async { + testWidgets('a scroll that steals the gesture cancels the press', ( + tester, + ) async { final controller = ScrollController(); addTearDown(controller.dispose); + await tester.pumpWidget(pressableList(controller)); - await tester.pumpWidget( - scene( - SizedBox( - height: 300, - child: ListView( - controller: controller, - children: [ - for (var i = 0; i < 12; i++) - const BeamPress(child: SizedBox(height: 80)), - ], - ), - ), - ), - ); + bool? firstActive() => + tester.widget(find.byType(BorderBeam).first).active; final gesture = await tester.startGesture( tester.getCenter(find.byType(BeamPress).first), ); await tester.pump(); - expect( - tester.widget(find.byType(BorderBeam).first).active, - isTrue, - ); + expect(firstActive(), isTrue); await gesture.moveBy(const Offset(0, -120)); await tester.pump(); - expect( - tester.widget(find.byType(BorderBeam).first).active, - isFalse, - ); + expect(firstActive(), isFalse); await gesture.up(); await tester.pumpAndSettle(); @@ -255,13 +267,18 @@ void main() { }); group('pass-through', () { - testWidgets('hands its style, shape and timing to the beam', ( + testWidgets('defaults to a pulse', (tester) async { + await tester.pumpWidget(press()); + expect(beamOf(tester).effect, const BeamEffect.pulse()); + }); + + testWidgets('hands its effect, style, shape and timing to the beam', ( tester, ) async { await tester.pumpWidget( scene( const BeamPress( - variant: BeamVariant.rotate, + effect: BeamEffect.rotate(count: 2), colors: BeamColors.sunset, borderRadius: 20, style: BeamStyle(strength: 0.4), @@ -272,8 +289,8 @@ void main() { ), ); - final beam = tester.widget(find.byType(BorderBeam)); - expect(beam.variant, BeamVariant.rotate); + final beam = beamOf(tester); + expect(beam.effect, const BeamEffect.rotate(count: 2)); expect(beam.colors, BeamColors.sunset); expect(beam.borderRadius, 20); expect(beam.style, const BeamStyle(strength: 0.4)); @@ -281,14 +298,6 @@ void main() { expect(beam.timing, const BeamTiming(speed: 2)); }); - testWidgets('defaults to the contained breathing glow', (tester) async { - await tester.pumpWidget(press()); - expect( - tester.widget(find.byType(BorderBeam)).variant, - BeamVariant.pulseInside, - ); - }); - testWidgets('is translucent to hit testing', (tester) async { await tester.pumpWidget(press()); final listener = tester.widget( @@ -309,7 +318,7 @@ void main() { .toDiagnosticsNode() .toStringDeep(); expect(description, contains('tappable')); - expect(description, contains('variant: pulseInside')); + expect(description, contains('effect: BeamEffect.pulse()')); }); }); } diff --git a/tool/record_demo.sh b/tool/record_demo.sh index 4710bec..aacde9b 100755 --- a/tool/record_demo.sh +++ b/tool/record_demo.sh @@ -24,7 +24,7 @@ # during the still gaps. True 120 fps needs a physical ProMotion device. # # Usage: -# tool/record_demo.sh --target lib/multiline_demo.dart --prefix MULTILINE +# tool/record_demo.sh --target lib/showcase.dart --prefix SHOWCASE --contact # # Options: # --target PATH Dart entrypoint, relative to example/ (required) @@ -38,6 +38,8 @@ # --crop-height PX crop to a centered band PX pixels tall (default: ~40% of the screen height) # --scale-width PX downscale to this width (default: 0 = keep native res) # --no-crop keep the full screen instead of cropping to the beam zone +# --display ID simulator display to record, for multi-display devices +# (passed to `simctl io recordVideo --display`) # --lead SEC seconds of lead-in to trim (default: auto — 1s before the # first scene, computed from the marker timing) # --contact also write a _contact.png contact sheet to eyeball it @@ -46,7 +48,7 @@ set -euo pipefail # ---- args ---------------------------------------------------------------- -TARGET="" PREFIX="" OUT="" DEVICE="" FPS=60 CRF=16 PRESET=slow +TARGET="" PREFIX="" OUT="" DEVICE="" DISPLAY_ID="" FPS=60 CRF=16 PRESET=slow CROP_H="" CROP_FRAC=0.40 SCALE_W=0 NOCROP=false LEAD="" CONTACT=false KEEP=false die() { echo "error: $*" >&2; exit 1; } usage() { sed -n '2,/^set -euo/p' "$0" | sed 's/^# \{0,1\}//; s/^#$//' | sed '$d'; exit "${1:-0}"; } @@ -56,6 +58,7 @@ while [[ $# -gt 0 ]]; do --prefix) PREFIX="$2"; shift 2;; --out) OUT="$2"; shift 2;; --device) DEVICE="$2"; shift 2;; + --display) DISPLAY_ID="$2"; shift 2;; --fps) FPS="$2"; shift 2;; --crf) CRF="$2"; shift 2;; --preset) PRESET="$2"; shift 2;; @@ -155,7 +158,7 @@ wait_done 1 600 "waiting for first $PREFIX:DONE" # ---- record + replay ----------------------------------------------------- echo "▶ recording…" -xcrun simctl io "$DEVICE" recordVideo --codec=h264 --force "$RAW" >"$RECLOG" 2>&1 & +xcrun simctl io "$DEVICE" recordVideo --codec=h264 ${DISPLAY_ID:+--display="$DISPLAY_ID"} --force "$RAW" >"$RECLOG" 2>&1 & REC_PID=$! for _ in $(seq 1 40); do grep -q "Recording started" "$RECLOG" && break; sleep 0.1; done REC_T0="$(now)" @@ -176,7 +179,7 @@ wait "$REC_PID" 2>/dev/null || true REC_PID="" # ---- encode -------------------------------------------------------------- -# auto lead-trim: start ~1s before the first toast appeared +# auto lead-trim: start ~1s before the first scene appeared if [[ -z "$LEAD" ]]; then if [[ -n "$FIRST_START_AT" ]]; then LEAD="$(calc "max(0.0, $FIRST_START_AT-1.0)")"; else LEAD=4.0; fi fi @@ -200,7 +203,7 @@ if [[ "$CONTACT" == true ]]; then fi # ---- report -------------------------------------------------------------- -read -r W H FR DUR < <(ffprobe -v error -select_streams v:0 \ +read -r W H _ DUR < <(ffprobe -v error -select_streams v:0 \ -show_entries stream=width,height,r_frame_rate -show_entries format=duration \ -of csv=p=0 "$OUT" | tr ',\n' ' ') || true # read exits 1 at EOF (no newline) SRC_MED="$(ffprobe -v error -select_streams v:0 -show_entries frame=pts_time -of csv=p=0 "$RAW" 2>/dev/null \ diff --git a/tool/spec/README.md b/tool/spec/README.md deleted file mode 100644 index b684dd7..0000000 --- a/tool/spec/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# Upstream spec vendoring - -The React [border-beam](https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam) -library publishes `spec/beam-spec.json`, a machine-readable dump of every -table its `src/styles.ts` builds its CSS from. This package's -`lib/src/constants/` is a hand transcription of those same tables, so the spec -is the only thing that can prove the transcription is still right. - -- `test/fixtures/beam-spec.json` — the vendored spec. -- `test/fixtures/UPSTREAM` — the commit, versions, and `styles.ts` hash it was - fetched at. -- `test/constants/spec_parity_test.dart` — asserts our constants against it. -- `.github/workflows/upstream_drift.yaml` — weekly alarm when upstream moves. - -## Refreshing - -```bash -tool/spec/refresh.sh # from main -tool/spec/refresh.sh v1.4.0 # from a tag/branch/sha -``` - -Then re-check `lib/src/constants/upstream.dart` (its version strings are hand -maintained) and run: - -```bash -flutter test test/constants/spec_parity_test.dart -``` - -A parity failure after a refresh means upstream changed a value. **Re-audit -the constants against `src/styles.ts` before touching anything** — the hard -rule in `CLAUDE.md` still stands: constants are never tweaked to make a test -pass. diff --git a/tool/spec/refresh.sh b/tool/spec/refresh.sh deleted file mode 100755 index 1804e73..0000000 --- a/tool/spec/refresh.sh +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env bash -# -# Re-vendors the upstream border-beam spec into `test/fixtures/`. -# -# The React library ships a machine-readable `spec/beam-spec.json` generated -# from its `src/styles.ts`. `test/constants/spec_parity_test.dart` reads the -# vendored copy and asserts every table in `lib/src/constants/` against it, so -# the fixture is the parity test's ground truth and must be refreshed whenever -# upstream moves. -# -# Writes (idempotent — re-running on an unchanged upstream leaves the tree -# untouched): -# test/fixtures/beam-spec.json the spec, byte for byte as upstream has it -# test/fixtures/UPSTREAM commit=, version=, package_version=, -# spec_version=, styles_sha256= -# -# `styles_sha256` hashes the upstream `src/styles.ts` the spec was generated -# from; `.github/workflows/upstream_drift.yaml` compares against it so a -# styles change that never reached the spec generator still raises the alarm. -# -# Usage: -# tool/spec/refresh.sh # fetch from main -# tool/spec/refresh.sh # fetch from a tag/branch/sha -# -# Needs `curl`, `jq`, and `shasum`. After running, re-read -# `lib/src/constants/upstream.dart` (its version strings are hand-maintained), -# then run: -# flutter test test/constants/spec_parity_test.dart -set -euo pipefail - -REPO="Jakubantalik/Libraries" -PKG="packages/border-beam" -REF="${1:-main}" - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" -fixtures="$repo_root/test/fixtures" -mkdir -p "$fixtures" - -work="$(mktemp -d)" -trap 'rm -rf "$work"' EXIT - -# Downloads $2 from the package at commit $1 into $work/$3, preserving the -# bytes exactly — command substitution would eat the trailing newline and -# change the styles.ts hash. -raw() { - curl -fsSL "https://raw.githubusercontent.com/$REPO/$1/$PKG/$2" -o "$work/$3" -} - -echo "Fetching $REPO@$REF …" - -# Resolve the ref to a concrete commit so the fixture records exactly what was -# fetched, even when REF is a moving branch. -commit="$(curl -fsSL \ - -H 'Accept: application/vnd.github+json' \ - "https://api.github.com/repos/$REPO/commits/$REF" | jq -r .sha)" -if [ -z "$commit" ] || [ "$commit" = "null" ]; then - echo "error: could not resolve $REPO@$REF to a commit" >&2 - exit 1 -fi - -raw "$commit" "spec/beam-spec.json" spec.json -raw "$commit" "src/styles.ts" styles.ts -raw "$commit" "package.json" package.json - -jq empty < "$work/spec.json" # reject a truncated or non-JSON download - -version="$(jq -r .sourceLibrary.version < "$work/spec.json")" -spec_version="$(jq -r .specVersion < "$work/spec.json")" -package_version="$(jq -r .version < "$work/package.json")" -styles_sha256="$(shasum -a 256 < "$work/styles.ts" | cut -d' ' -f1)" - -cp "$work/spec.json" "$fixtures/beam-spec.json" - -cat > "$fixtures/UPSTREAM" <