diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index ae76b5a..86ba2b6 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -10,7 +10,7 @@ body: round trip. Security issues do **not** belong here — see - [SECURITY.md](https://github.com/SimplifyJobs/flutter_border_beam/blob/main/SECURITY.md). + [SECURITY.md](https://github.com/SimplifyJobs/prismatic/blob/main/SECURITY.md). - type: textarea id: description @@ -72,8 +72,8 @@ body: - type: input id: package-version attributes: - label: flutter_border_beam version - placeholder: "0.2.0" + label: prismatic version + placeholder: "0.3.0" validations: required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index fb49ce4..d4832f8 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,11 +1,11 @@ blank_issues_enabled: false contact_links: - name: Question or idea - url: https://github.com/SimplifyJobs/flutter_border_beam/discussions + url: https://github.com/SimplifyJobs/prismatic/discussions about: Ask how to do something, or float an idea before it becomes a proposal. - name: Live demo - url: https://simplifyjobs.github.io/flutter_border_beam/ + url: https://simplifyjobs.github.io/prismatic/ about: See every effect and palette in the browser. - name: Security vulnerability - url: https://github.com/SimplifyJobs/flutter_border_beam/security/advisories/new + url: https://github.com/SimplifyJobs/prismatic/security/advisories/new about: Report privately. Never in a public issue. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 5e9f3ee..26b62c2 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. @@ -40,17 +40,21 @@ touched, with `--plain-name`. **Frame budget** — still one draw, no `saveLayer` / clip / image or mask filter: ## Checklist -- [ ] `BeamOutline` and `color_math.dart` still mirror the shader (if either - side changed) +- [ ] `BeamOutline` still mirrors `shaders/common/outline.glsl`, and + `BeamFrameData.tableAt` the shader's `TABLE_LOOKUP` (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 -- [ ] README updated if this changes what a user reaches for first +- [ ] `doc/` updated for any user-facing change (README only if it changes what a user reaches for first) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ac884f5..9d9ffb6 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -1,9 +1,9 @@ -# CI for flutter_border_beam. +# CI for prismatic. # # Three things about this workflow are deliberate and easy to get wrong: # # 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 +# The golden files under `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, diff --git a/.github/workflows/pages.yaml b/.github/workflows/pages.yaml index fb312f1..e7822d7 100644 --- a/.github/workflows/pages.yaml +++ b/.github/workflows/pages.yaml @@ -3,10 +3,10 @@ # The site is `example/` — the one-screen effect showcase — built for web and # served at # -# https://simplifyjobs.github.io/flutter_border_beam/ +# https://simplifyjobs.github.io/prismatic/ # # 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/`. +# repo name, so the `--base-href` below must stay `/prismatic/`. # # ── ONE-TIME SETUP THE MAINTAINER MUST DO ──────────────────────────────────── # @@ -81,7 +81,7 @@ jobs: # `https://.github.io//`, not from the domain root. - name: Build web working-directory: example - run: flutter build web --release --base-href /flutter_border_beam/ + run: flutter build web --release --base-href /prismatic/ - name: Add the SPA fallback working-directory: example diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 5900f15..2dd14bf 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -1,4 +1,4 @@ -# Publish flutter_border_beam to pub.dev and cut a GitHub Release. +# Publish prismatic to pub.dev and cut a GitHub Release. # # Trigger: pushing a `vX.Y.Z` tag (a `-suffix` prerelease tag is allowed). # @@ -13,10 +13,10 @@ # 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 +# https://pub.dev/packages/prismatic/admin # → "Automated publishing" → "Enable publishing from GitHub Actions", and # set: -# Repository: SimplifyJobs/flutter_border_beam +# Repository: SimplifyJobs/prismatic # Tag pattern: v{{version}} # (You must be an uploader on the package to see the Admin tab.) # 3. Nothing else. There is no PUB_CREDENTIALS / CREDENTIAL_JSON secret to diff --git a/.pubignore b/.pubignore index eb3300c..c27c678 100644 --- a/.pubignore +++ b/.pubignore @@ -10,8 +10,9 @@ # # `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. +# `shaders/` must stay in the archive too: the `.frag` files are declared under +# `flutter: shaders:` and compiled into every consuming app, with the +# `shaders/common/*.glsl` they include. Never ignore it. # ── Mirrors of the root .gitignore ────────────────────────────────────────── *.class @@ -29,9 +30,10 @@ coverage/ # ── Repo-only sources and tooling ─────────────────────────────────────────── assets/ tool/ +AGENTS.md CLAUDE.md # 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/ +test/**/golden/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..fcdc2b5 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,188 @@ +# prismatic — agent guide + +Flutter package of shader effects built for Impeller, with two effects: + +- **`BorderBeam`** — 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. Its look is that of + the [border-beam](https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam) + React library (MIT, by Jakub Antalik), drawn by a native renderer of its + own that does not track upstream. +- **`DistortionWave`** — a refractive wave that opens from a button, edge or + avatar and carries one view into another, in place or between routes + (`DistortionWaveRoute`). It reimplements the look of Jakub Antalik's SwiftUI + [Distortion waves](https://github.com/Jakubantalik/Libraries.dev/tree/main/packages/distortion-waves) + (MIT): both views are drawn from GPU pictures of themselves by **one shader + draw plus at most one atlas draw per frame** while the wave bends them. + +Code shared by both lives in `lib/src/core/` (`ShaderProgram`) and +`shaders/common/` (the rounded-superellipse `outline()`); `lib/src/core/` +also holds `Oklab`, which only the wave uses. + +This file is the one agent guide: Codex reads `AGENTS.md`, and Claude Code +reads `CLAUDE.md`, which only imports this file (`@AGENTS.md`). Edit this +file, never `CLAUDE.md`. + +## Docs + +- **`doc/` is the agent-facing reference** — complete, precise, checked + against the code. Start at **[doc/README.md](doc/README.md)**, the index + of which file answers which question. Usage references: + [doc/border_beam_usage.md](doc/border_beam_usage.md) and + [doc/distortion_wave_usage.md](doc/distortion_wave_usage.md); internals: + [doc/architecture.md](doc/architecture.md) (beam) and + [doc/distortion_wave.md](doc/distortion_wave.md) (wave); topic guides for + the beam (`effects`, `palettes`, `shape`, `motion`, `theming`) and both + effects (`accessibility`, `performance`). +- **`README.md` is for humans** on pub.dev and GitHub: what the package is, + where to use it, demo videos, install, two tiny quick starts, links. Short, + friendly sentences. Reference material does not go there — it goes in + `doc/`. +- `CONTRIBUTING.md` is for human contributors (setup, rules in brief, PR + checklist). `CHANGELOG.md` carries history. +- When public API or behaviour changes, update the matching `doc/*_usage.md` + in the same change; when a pipeline, uniform layout or module moves, update + the internals doc and the map below. +- Docs describe how the code works now — no change-history prose ("no longer", + "previously"). Name constants and getters instead of quoting tuned values + (hard rule 8 below). + +## Commands + +- `flutter analyze` — must stay at zero issues, infos included (CI runs `--fatal-infos`; lints include `public_member_api_docs`). +- `flutter test` — full suite (unit + widget + render + goldens). +- `flutter test --exclude-tags golden` — everything except goldens (use on non-macOS). +- **After editing only `shaders/common/*.glsl`**, `rm -rf build && touch shaders/*.frag` before testing: `flutter test` can reuse shaders compiled before an include changed, and run stale. +- `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 (CI: `dart format --output=none --set-exit-if-changed .`). +- `cd example && flutter run` — the showcase app (also the live demo, https://simplifyjobs.github.io/prismatic/, deployed by `pages.yaml`): swipe between the three beam effects, each on its own mock surface with continuous (superellipse) corners; palette swatches and a theme toggle (tokens in `example/lib/src/tokens.dart`); the distortion-wave page (`example/lib/src/wave_page.dart`) opens on a `DistortionWaveRoute`; `example/lib/src/display_corners.dart` supplies iOS display corners. `--dart-define`s `START`, `PALETTE`, `THEME` set the opening state for captures. No tests — CI's `example` job gates it on `flutter analyze --fatal-infos` and a web build. +- `tool/record_demo.sh --target lib/wave_reel.dart --prefix WAVE --no-crop --contact` — the distortion-wave reel (full screen: the default crop cuts its scenes). +- `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. `shaders/*.frag` and `shaders/common/*.glsl` must be in the archive (`.pubignore` must never exclude `shaders/`). The `.glsl` includes are not listed under `flutter: shaders:`; impellerc gets `shaders/` as an include path. +- **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/prismatic` 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 + +### BorderBeam + +Everything animated is a **pure function of elapsed time** — one `Ticker` per +widget (`BeamClock`), or one per `BeamSync` group. No `AnimationController`s. +A frame: + +```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/border_beam/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 `Φ`. + +### DistortionWave + +Everything is a **pure function of one progress value, 0–1** — +`WaveFrame.at(progress, source, size, spec, focus)` — so the wave scrubs, +reverses and freezes for goldens. One `Ticker` per wave (`WaveClock`), or the +route's own animation. A frame: + +```text +WaveClock / route animation → RenderWaveStage → WaveFrame.at → phase → WaveFrameData → wave.frag (one drawRect) + DotAtlas (one drawRawAtlas) +``` + +`RenderWaveStage` picks a **phase** per frame: `rest` (the visible side as +itself, nothing else), `distorting` (both sides from `WaveSideImages` through +`wave.frag`), `glowing` (the revealed side as itself under +`wave_glow.frag`, once the front has crossed and bends nothing), or +`crossfading` (reduced motion, or a side that cannot be rasterised). A side is +pictured — painted into a detached `OffsetLayer` and `toImageSync`ed, as +`SnapshotWidget` does — when first needed and again only when its content +repaints (`RenderWaveSide.markNeedsPaint` flags it), or every frame with +`WaveSnapshots.everyFrame`; each picture bakes two small blurred copies +once, on its first frame with blur to show — near (`waveNearBlur`, capped at +the spec's blur) and far (the spec's blur), each an `ImageFilter.blur` draw +into its own offscreen `Picture`, never a filter on the stage's canvas. The +shader mixes sharp/near/far by the blur radius each pixel should have — +Swift's stacked blurred copies, in one pass. Pictures are released when the +phase leaves `distorting`. Each stage owns and disposes its `DotAtlas`. + +The look (timeline, field, colour model, palettes, per-type tuned styles) is +the reference's; `WaveSpec.resolve` settles widget style ⊕ theme ⊕ type +defaults into seconds and pixels, and settles every value to a finite one +in release builds too (NaN → the field's floor, ranges clamped, +`returnSpeed` 0.01–100). It was calibrated by building +DistortionWavesKit in a throwaway SwiftUI harness and rendering both at the +same progress over the same mock screens (mean difference ≈ 1/255); the +goldens pin those scenes. + +Full pipeline, layer model, design data, uniform layout, and invariants in +prose: +**[doc/architecture.md](doc/architecture.md)** (the beam) and +**[doc/distortion_wave.md](doc/distortion_wave.md)** (the wave) — update them +when the layout moves. The map below is the index. + +- `lib/src/core/` — `shader_program.dart` (`ShaderProgram`: one instance per `.frag`, loaded once per process, per-zone load sharing, retry after a failed load, `ready`), `oklab.dart` (`Oklab`). +- `lib/distortion_wave.dart` — the wave's library: `DistortionWave`, `DistortionWaveRoute`, `DistortionWaveController`, `DistortionWaveTheme`/`DistortionWaveThemeData`, `DistortionWaveAnchor`/`DistortionWaveAnchorState`, `WaveSource`, `WaveStyle` and its groups (`WaveTiming`, `WaveMotion`, `WaveLens`, `WaveGlow`, `WaveDots`), `WavePalette`/`maxWavePaletteColors`, `WaveType`, `WaveSnapshots`. Nothing in `render/`, `timeline/` or `look/` is exported. +- `lib/src/distortion_wave/` — `distortion_wave.dart` (the widget + its state: clock, controller binding, one `WaveAnchorRegistry` with a `WaveAnchorScope` per side, theme/shorthand resolution, `maintainState`/`TickerMode` for the hidden side, `ExcludeFocus` for the side off screen — at rest or held at either end; also the `WaveStage` slotted widget and `WaveSide`/`RenderWaveSide`), `distortion_wave_route.dart` (`DistortionWaveRoute`: pictures the previous route's page `RepaintBoundary` after the push's first frame and again on pop; `canTransitionFrom` false; its `CurvedAnimation` — linear forward, `spec.easing.flipped` in reverse — made once and disposed with the route; spec resolved once against the navigator's theme), `distortion_wave_controller.dart` (+ the unexported `WaveDriver`/binding), `distortion_wave_theme.dart`, `wave_source.dart` (`WaveSource.rect/key/of`, `DistortionWaveAnchor` — registers as pressed on pointer-down or when focus lands inside it, a keyboard focus dropping its stale touch; `WaveAnchorRegistry.sourceFor`: last pressed on the side on screen → the only anchor there → last pressed on the other side → none; `WaveAnchorScope`, `defaultWaveSource`). +- `lib/src/distortion_wave/models/` — the public value objects (all-nullable, `const`, `copyWith`/`merge`/`==`), `wave_palette.dart`, `wave_type.dart`, `wave_snapshots.dart`, and the internal `wave_spec.dart` (`WaveSpec`: everything settled, value-equal, `duration`/`returnDuration`). +- `lib/src/distortion_wave/look/wave_defaults.dart` — the per-type tuned styles (owned and tunable; goldens move when it does). +- `lib/src/distortion_wave/timeline/` — `wave_frame.dart` (`WaveFrame.at`, `waveCoverZone`, `waveSmooth`), `wave_particles.dart` (`WaveParticle.all`, cached for the last few specs), `wave_rim.dart` (`WaveRim.lumps`/`thickness`), `wave_clock.dart` (`WaveClock`: runs from wherever it is at a full run's speed; interruptible). +- `lib/src/distortion_wave/render/` — `render_wave_stage.dart` (`RenderWaveStage`, `WaveSlot`, `WavePhase`; touches go to the side at rest, and mid-reveal to the revealed side once the phase is `glowing`; semantics visits the side at rest or being headed for), `wave_snapshot.dart` (`WaveSideImages`), `wave_frame_data.dart` (`WaveFrameData`, `waveUniformFloats` = 124 — 31 vec4s, the last `uRadii`, the per-corner radii the edges follow — `wavePaletteSlots` = 8, `waveNearBlur`), `wave_programs.dart` (`waveProgram`, `waveGlowProgram`), `dot_atlas.dart` (`DotAtlas`: one cached AA disc sprite per pixel size; each stage owns one and disposes it), `wave_warm_up.dart` (`warmUpWaveRendering`, run by `DistortionWave.precache`: draws both shaders, a blur bake and an atlas into a 4 × 4 image so pipelines exist before the first wave). +- `shaders/wave.frag`, `shaders/wave_glow.frag`, `shaders/common/wave_uniforms.glsl` (the block both declare — a contract with `wave_frame_data.dart`), `wave_field.glsl`, `wave_colour.glsl`, `outline.glsl`. +- `lib/prismatic.dart` — the package barrel; it re-exports each effect's library. `lib/border_beam.dart` — the beam's library; 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/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/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/border_beam/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/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/border_beam/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 ≤ `compactMaxExtent` (`look/rotate_look.dart`), 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/border_beam/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/border_beam/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` (`beamProgram`, the beam's `ShaderProgram` from `lib/src/core/shader_program.dart`, 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/border_beam/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 a pulse's rise (a flash has none); `BeamClock.fadeInSeconds`/`fadeOutSeconds` are their settling times), `beam_phases.dart` (`BeamFramePhases` + `BeamPhaseResolver`: fade incl. gap envelope, hue, travellers, `reversedNow`, ambient `cycles`, `driven`). +- `lib/src/border_beam/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/border_beam/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 + +### BorderBeam + +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/border_beam/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/border_beam/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/border_beam/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 shaders' `outline()` (`shaders/common/outline.glsl`, included by every shader) 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 goldens in `test/border_beam/golden/goldens/` pin the calibrated look: when retuning rotate/line/pulse, render the change beside them and beside the border-beam reference, and regenerate only once it matches. +8. **Don't quote or hard-code look values in docs** — tuning lives in `lib/src/border_beam/look/` and the emitters (and `lib/src/distortion_wave/look/` for the wave) and changes; docs describe behaviour. + +### DistortionWave + +1. **Distortion window: one shader `drawRect` plus at most one `drawRawAtlas` per frame; zero `saveLayer`, clip, `ImageFilter`, `BackdropFilter`, `MaskFilter`, image draws on the stage's canvas.** At rest the wave paints the visible child and nothing else; in the glow phase, the revealed child plus one `drawRect` and at most one atlas. (Picturing a side is separate offscreen work — one `toImageSync` plus two `ImageFilter.blur` bakes — and happens only per rule 2.) `test/distortion_wave/render/wave_frame_budget_test.dart` asserts this per phase × type. Never reach for `ImageFilter.shader`/`BackdropFilter`: they are Impeller-only, need a new filter object every frame, and hit open engine bugs (flutter#185175, #187820). +2. **A side is pictured only when its content changed** (or every frame under `WaveSnapshots.everyFrame`), and pictures are released when the phase leaves `distorting`. The snapshot-count and lifecycle tests pin both. +3. **The uniform block is a contract.** `shaders/common/wave_uniforms.glsl` (declared once, included by both wave shaders) and `WaveFrameData`'s offsets change together, in one commit; vec4s only, samplers after it in `wave.frag` in the order the renderer binds them (out sharp/near/far, in sharp/near/far). `test/distortion_wave/render/wave_uniform_layout_test.dart` checks both shaders through `test/support/shader_source.dart`, which inlines `#include`s. +4. **`WaveFrame` stays a pure function of progress.** Scrubbing, reversing, the route and the goldens depend on it; anything per-frame that is not (a ticker, an image) lives in the clock or the stage. +5. **Parity with the reference look is checked by rendering both, then pinned by goldens.** When retuning, rebuild the SwiftUI harness (DistortionWavesKit + `ImageRenderer` at fixed `scrub:`, built with `xcodebuild`, which needs the Metal Toolchain) and compare at the golden scenes' progress values. +6. **SkSL strict ES2 in every shader** — loops with constant bounds, arrays indexed by constants or loop indices — so the wave also runs on Skia and the web. + +## Testing conventions + +- **Directories** — `test/core/` (code shared by every effect: `ShaderProgram`, `Oklab`); `test/support/` (helpers shared by both effects' tests: `shader_source.dart`); the wave's under `test/distortion_wave/`: `models/` (value objects, `WaveSpec` resolution, palettes), `timeline/` (`WaveFrame` — ports of every `WaveFrontTests` case — particles, rim, clock, seeded property sweep), `render/` (uniform layout, frame budget + snapshot counts, `wave_paint_structure_test.dart` for where pixels land in real frames), `widget/` (behaviour, lifecycle, route, theme; helpers in `wave_test_utils.dart`), `golden/` (`wave_golden_test.dart`: each type at its telling moments, palettes; scenes held with `progress:`); the beam's tests under `test/border_beam/`: `test/border_beam/models/` (value objects, config resolution, colours/palettes, effects, segments), `test/border_beam/animation/` (clock, spring, phases, travel, seeded property test), `test/border_beam/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/border_beam/widget/` (`BorderBeam` itself: lifecycle, updates, shorthands, theming, sync, speed, progress, follow, motion, playback, cycle gap, shape), `test/border_beam/widgets/` (the four widgets), `test/border_beam/golden/`. +- **Leak tracking.** `test/distortion_wave/widget/distortion_wave_lifecycle_test.dart` and `distortion_wave_route_test.dart` call `LeakTesting.enable()` (`leak_tracker_flutter_testing`, a dev dependency pinned by `flutter_test` through `any`): any image, `ChangeNotifier`, `CurvedAnimation` or controller the code or the test creates must be disposed (`addTearDown(controller.dispose)`). Call `LeakTesting.enable()` in new lifecycle-style test files. +- **Pixel tests need the shader.** Anything that reads pixels or counts draws awaits `BorderBeam.precache()` (or `DistortionWave.precache()`) in `setUpAll`; before it resolves a beam paints nothing and a wave shows its sides plainly. +- **Beam golden families** (one file each, `@Tags(['golden'])`, staged by `test/border_beam/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. The wave's goldens are one file, `test/distortion_wave/golden/wave_golden_test.dart`, each scene held with `progress:`. +- **Goldens are macOS-generated on Flutter 3.50.0** (the `ci.yaml` pin) and run with `--tags golden`. Beam 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/border_beam/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/border_beam/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/border_beam/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/border_beam/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. `test/distortion_wave/widget/distortion_wave_lifecycle_test.dart` does the same for a wave disposed mid-run, `TickerMode`, a controller outliving or moving between waves, and the release of the sides' pictures. +- 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/CHANGELOG.md b/CHANGELOG.md index 122a786..4ce96cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,300 +3,43 @@ All notable changes to this package are documented here, following [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). -## 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 - -#### Renderer - -- `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. - -#### Effects - -- `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 - -- 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. - -### Changed - -- **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 - -- `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 - -- **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 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 - -- 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 - -Initial release — a faithful Flutter port of the [border-beam](https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam) React library by Jakub Antalik. - -### Features - -- **Five beam variants** via named constructors, pixel-matched to the source: - - `BorderBeam.rotate` — full border traveling beam (React `md`) - - `BorderBeam.small` — compact traveling beam for buttons (React `sm`) - - `BorderBeam.line` — bottom-edge traveling beam (React `line`) - - `BorderBeam.pulseInside` — contained breathing glow (React `pulse-inner`) - - `BorderBeam.pulseOutside` — outward-blooming halo (React `pulse-outside`) -- **Color system**: the four source presets (`colorful`, `mono`, `ocean`, `sunset`), `BeamColors.custom(List)` auto-distributed over the preset geometry, and an advanced `BeamColors.spec` for per-blob control. -- **Superellipse borders**: `useSuperellipse: true` shapes the beam as an Apple-style squircle (`RoundedSuperellipseBorder`, Flutter ≥ 3.35). -- **Playback control**: optional `BorderBeamController` (`start` / `stop` / `pause` / `resume` / `seek` / `speed`) with exclusive ownership, or declarative `active` + `autoPlay` / `startAfter` / `duration` scheduling. -- **Theming**: dark / light presets per variant, `BeamTheme.auto` follows `Theme.of(context)`. -- **Tuning hooks** ported from the source's CSS custom properties: `strength`, `brightness`, `saturation`, `hueRange`, `hueBase`, `staticColors`, layer opacity factors, and pulse glow overrides (`glowBoost`, `coreBlur`, `bloomBlur`, `glowBrightness`, `glowSaturation`). -- **Accessibility & performance**: honors `MediaQuery.disableAnimations`, pauses under `TickerMode`, spring-eased fades (`sprung`), single-`Ticker` engine with a ~30fps cap for pulse variants, `RepaintBoundary`-isolated painting (the child never re-rasterizes), and CPU hue folding to keep `saveLayer` counts low. +## 0.3.0 + +The first release on pub.dev. Two shader effects for Flutter, built for +Impeller. + +### `BorderBeam` + +Light that travels or breathes around a widget's border. + +- Three effects: `rotate` laps the border, `line` rides one edge, and + `pulse` breathes in from the whole border. +- 19 palettes. Or bring your own colours, a seed colour, or a + `ColorScheme`. +- Rounded, squircle and stadium shapes, plus partial segments and dashes. +- A theme, a controller, synchronised groups, driven progress and pointer + follow. +- `BeamDecoration`, `BorderBeam.overlay`, and focus, hover and press + wrappers. +- One shader draw per frame. No layers, blurs or clips. + +### `DistortionWave` + +A colourful wave that bends one screen into the next. + +- Three types: `vertical`, `horizontal` and `center`, each tuned on its own. +- Use it in place with `DistortionWave`, or between pages with + `DistortionWaveRoute`. +- `DistortionWaveAnchor` finds the button and the touch by itself. It works + from the keyboard too, and with a screen reader when the screen has one + anchor. +- Five palettes, a one-colour palette, your own colours, or any + `BorderBeam` palette. +- A controller, a theme, `progress:` to hold the wave at any moment, and a + short crossfade when the system asks for reduced motion. +- When it fills the screen, its light follows the display's own corners. +- One shader draw plus at most one atlas draw per frame. Runs on Impeller, + Skia and the web. + +Earlier versions (0.1.0 and 0.2.0) were developed as `flutter_border_beam` +and never published. Their notes are in the git history. diff --git a/CLAUDE.md b/CLAUDE.md index 5012c6f..43c994c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,87 +1 @@ -# flutter_border_beam — agent guide - -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 (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 + render + goldens). -- `flutter test --exclude-tags golden` — everything except goldens (use on non-macOS). -- `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` — 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. `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. No `AnimationController`s. -A frame: - -```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`, `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/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. **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 - -- **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). +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 88c5ef3..f15d6f6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,11 +1,14 @@ -# Contributing to flutter_border_beam +# Contributing to prismatic 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 +shader in a single draw call, and every frame of a distortion wave with one +shader draw plus one atlas draw; most of its rules exist to keep them 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. +anything under `lib/src/border_beam/render/`, `lib/src/border_beam/effects/`, +`lib/src/distortion_wave/render/`, or `shaders/` — they are what a reviewer +will check first. [doc/architecture.md](doc/architecture.md) explains how a +beam's frame is built, [doc/distortion_wave.md](doc/distortion_wave.md) a +wave's; [doc/README.md](doc/README.md) indexes the rest of the reference. ## Setup @@ -14,8 +17,8 @@ by `material_ui`; CI tests that exact version in its `min-sdk` job) and, for gol 3.50.0 on macOS**. ```bash -git clone https://github.com/SimplifyJobs/flutter_border_beam.git -cd flutter_border_beam +git clone https://github.com/SimplifyJobs/prismatic.git +cd prismatic flutter pub get # The one-screen showcase. It consumes the package by path, so it picks up @@ -24,7 +27,7 @@ cd example && flutter pub get && flutter run ``` The showcase is also live at - — useful for comparing + — useful for comparing your build against `main`. ## Commands @@ -77,7 +80,7 @@ see the actual/expected/diff triple. 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, +`test/border_beam/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 @@ -86,20 +89,21 @@ 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 +`lib/src/border_beam/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` +each layer has its own blob array. `test/border_beam/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 total, and the order — every `BeamFrameData` writer must land in the +uniform the shader declares at its offset, so a uniform reordered on one side +only fails the test instead of shifting 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 +- **`BeamOutline`** (`lib/src/border_beam/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 @@ -121,14 +125,31 @@ Two pieces of shader maths also run in Dart, and must match exactly: scratch lists, oscillator banks are cached per tuning, and derived tables are memoized per palette. +### The distortion wave + +The wave keeps its own budget: while it bends content, one shader `drawRect` +plus at most one `drawRawAtlas` per frame on its canvas, with no layer, clip, +filter or `BackdropFilter` (`test/distortion_wave/render/wave_frame_budget_test.dart`), +and a side is pictured only when its content changed. `WaveFrame` stays a +pure function of progress, and the uniform block in +`shaders/common/wave_uniforms.glsl` changes with `WaveFrameData` +(`waveUniformFloats`) in one commit — +`test/distortion_wave/render/wave_uniform_layout_test.dart` checks both +shaders, the samplers and the order. When retuning its look +(`lib/src/distortion_wave/look/wave_defaults.dart`), compare against the +reference as [doc/distortion_wave.md](doc/distortion_wave.md#calibration) +describes, then regenerate only the affected goldens. +[AGENTS.md](AGENTS.md) lists the full rules. + ## Where things go **Adding an effect** — a `final class` extending `BeamEffect` in -`lib/src/effects/beam_effect.dart` (with a `const factory` on `BeamEffect`, a +`lib/src/border_beam/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.values`, the export in `lib/border_beam.dart` (each effect has +its own library; `lib/prismatic.dart` re-exports both), and an +emitter in `lib/src/border_beam/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 @@ -146,15 +167,17 @@ 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)`), +`lib/src/border_beam/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. +Anything public also needs a doc comment, a `CHANGELOG.md` entry, and an +update to the matching usage reference (`doc/border_beam_usage.md` or +`doc/distortion_wave_usage.md`). The root README is a short introduction; +touch it only if the change alters what a user would reach for first. ## Tests @@ -162,19 +185,28 @@ Tests are grouped by what they protect. Put a new test with its family: | directory | covers | | --- | --- | -| `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/golden/*_golden_test.dart` | pixel scenes (macOS only, `@Tags(['golden'])`) | +| `test/border_beam/models/` | value objects, `BeamConfig.resolve`, palettes, effects, segments, equality | +| `test/border_beam/animation/` | the clock, the spring, phase sampling, travel | +| `test/border_beam/render/` | the frame budget, the uniform layout, the outline mirror, emission sanity, boundaries, paint smoke, where light lands | +| `test/border_beam/widget/` | `BorderBeam` behaviour — lifecycle, theming, shorthands, speed, sync, progress, follow | +| `test/border_beam/widgets/` | the surface widgets (`BeamDecoration`, `BeamFocusRing`, `BeamHover`, `BeamPress`) | +| `test/border_beam/golden/*_golden_test.dart` | pixel scenes (macOS only, `@Tags(['golden'])`) | +| `test/distortion_wave/models/` | the wave's value objects, `WaveSpec` resolution, palettes | +| `test/distortion_wave/timeline/` | `WaveFrame` (ported from the reference's tests), particles, rim, clock, a property sweep | +| `test/distortion_wave/render/` | the wave's frame budget and snapshot counts, uniform layout, where pixels land | +| `test/distortion_wave/widget/` | `DistortionWave` and `DistortionWaveRoute` behaviour and lifecycle | +| `test/distortion_wave/golden/` | the wave's pixel scenes, held with `progress:` | +| `test/core/`, `test/support/` | code shared by both effects (`ShaderProgram`, `Oklab`); shared test helpers | Conventions worth knowing: - Anything that reads pixels needs the shader loaded: - `setUpAll(BorderBeam.precache)`. + `setUpAll(BorderBeam.precache)` or `setUpAll(DistortionWave.precache)`. +- The wave's lifecycle and route tests run with `LeakTesting.enable()` + (`leak_tracker_flutter_testing`): dispose everything you create — + controllers, images, curves. - For new rendering behaviour, prefer comparing regions of a real frame - against each other (see `test/render/paint_structure_test.dart`) over + against each other (see `test/border_beam/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. @@ -190,8 +222,9 @@ Docs and code comments **describe how the code works now**. No change-history 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. +why it is that way. Don't quote tuning values (glow reaches, layer weights, +the wave's durations) in docs — they live in `lib/src/border_beam/look/`, the +emitters, and `lib/src/distortion_wave/look/`, and they change. ## Commits and PRs @@ -217,9 +250,9 @@ 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 -- [ ] 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 +- [ ] Frame budget: still one draw (the wave: one draw plus at most one atlas), no layers, clips, or filters +- [ ] Shader uniforms changed together with `beam_frame.dart` / `wave_frame_data.dart` (if touched) +- [ ] Public API is documented, and `doc/` covers anything user-facing - [ ] `CHANGELOG.md` has an entry under the unreleased version The PR template asks for exactly this. Open the PR as a draft while it is in @@ -227,7 +260,7 @@ progress. ## Releases -Maintainers only. The recipe lives in [CLAUDE.md](CLAUDE.md) under "Cutting a +Maintainers only. The recipe lives in [AGENTS.md](AGENTS.md) under "Cutting a release": bump `version:` in `pubspec.yaml`, add a matching `## ` section to `CHANGELOG.md`, merge to `main`, then push the tag: diff --git a/LICENSE b/LICENSE index 5f29ba0..9bbf0c7 100644 --- a/LICENSE +++ b/LICENSE @@ -22,10 +22,4 @@ SOFTWARE. ------------------------------------------------------------------------------- -Third-party notice - -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. +Third-party notices: see the NOTICE file. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..64dd267 --- /dev/null +++ b/NOTICE @@ -0,0 +1,17 @@ +prismatic — third-party notices + +prismatic is released under the MIT License (see LICENSE). Its two effects +began as designs by Jakub Antalik, both released under the MIT License. + +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. + +The DistortionWave effect reimplements the look of the "Distortion waves" +library (DistortionWavesKit, packages/distortion-waves in +https://github.com/Jakubantalik/Libraries.dev): +Copyright (c) 2026 Jakub Antalik, released under the MIT License. Its +timeline, field, colour model, palettes and tuned styles are derived from +that work. diff --git a/README.md b/README.md index 68a1276..9c28058 100644 --- a/README.md +++ b/README.md @@ -1,670 +1,166 @@
-

flutter_border_beam

-

- Animated light around any widget's border — cards, buttons, inputs, search bars. -

+

prismatic

+

Light and motion for Flutter, drawn by shaders.

- pub package - pub points + pub package + pub points Flutter 3.47+ - Dart 3.9+ - CI - codecov + CI + codecov License: MIT

-
- Border beams animating in the demo reel -
- - -## Overview +prismatic gives you two effects. Each is one small shader, made for +Flutter's Impeller renderer. They run on Skia and the web too. -`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. +## BorderBeam -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. - -**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 effect on a card
- rotate — a beam laps the border -
- Pulse effect on a card
- pulse — colour breathes in from the border -
- Line effect on an input
- line — a streak rides the bottom edge -
- Superellipse corners in the ocean palette
- superellipse corners, ocean palette -
- -Around the effects: - -- **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 demo - -**** — 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 - -```console -flutter pub add flutter_border_beam -``` - -```dart -import 'package:flutter_border_beam/flutter_border_beam.dart'; -``` +A beam of light that travels around a widget's border. Put it on a card +while an agent works, on a search bar, or on anything that is thinking. -| Requirement | Version | -| --- | --- | -| 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. - -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 - -### Quick start +

+ Border beams lapping a card, riding a chat composer's edge, and breathing in from a card's border +

```dart BorderBeam( borderRadius: 16, colors: BeamColors.ocean, - child: Card( - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - child: const Padding( - padding: EdgeInsets.all(24), - child: Text('Working on it…'), - ), - ), -) -``` - -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( - 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)), - playback: const BeamPlayback(reducedMotion: BeamReducedMotion.staticFrame), child: card, ) ``` -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(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); -``` - -| 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. - -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. - -`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/effects.md) - -### Palettes - -```dart -// A preset -BorderBeam(colors: BeamColors.aurora, child: card); - -// 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 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, - ), - child: card, -); - -// The app's Material scheme -BorderBeam( - colors: BeamColors.fromScheme(Theme.of(context).colorScheme), - child: card, -); - -// Blend two palettes, and dim one -BorderBeam( - colors: const BeamColors.lerp(BeamColors.ocean, BeamColors.sunset, 0.35), - child: card, -); -BorderBeam(colors: BeamColors.ember.scaleAlpha(0.6), child: card); -``` - -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) - -### Shape - -```dart -// Uniform radius, const -BorderBeam(shape: const BeamShape.all(24, superellipse: true), child: card); - -// Per-corner, direction-aware -BorderBeam( - shape: const BeamShape( - radius: BorderRadiusDirectional.only(topStart: Radius.circular(28)), - ), - child: card, -); - -// A pill (a circle on a square box) that tracks the box as it resizes -BorderBeam(shape: const BeamShape.stadium(), child: chip); - -// The outline 8px outside the child, with a 2px stroke -BorderBeam( - shape: const BeamShape.all(24, ringOffset: 8, borderWidth: 2), - child: card, -); -``` - -`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. - -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 dashes - -`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( - shape: const BeamShape( - radius: BorderRadius.all(Radius.circular(24)), - segment: BeamSegment.bottomHalf, - ), - child: square, -); -``` - -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. +Pick the effect that fits: -| Preset | Coverage | -| --- | --- | -| `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 | +- **`rotate`** laps the border. It's the default. +- **`line`** rides one edge. Lovely on inputs. +- **`pulse`** breathes in from every side. A calm "thinking" state. -`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. +There are 19 palettes, squircle corners, a theme and a controller. Use the +same radius as your widget, and the light sits right on its edge. -`BeamShape.dashes` breaks the border into that many evenly spaced dashes (2 or more; 0 and 1 keep it solid): +## DistortionWave -```dart -BorderBeam( - shape: const BeamShape.all(16, dashes: 12), - child: badge, -); -``` +A colourful wave that bends one screen into the next. Use it when someone +pays, sends, finishes a step, or succeeds. -### Style + + + + + + +
+ A wave rising from a Send button and carrying a payment review into its receipt
+ vertical: up from a button +
+ A wave crossing from the left edge to the next sign-up step
+ horizontal: across from an edge +
+ A ring of colour spreading from an icon inside a sheet
+ center: a ring from an icon +
```dart -BorderBeam( - style: const BeamStyle( - colors: BeamColors.aurora, - theme: BeamTheme.dark, - strength: 0.8, - glow: 1.3, - hueMode: BeamHueMode.continuous, - hueBase: 40, +DistortionWave( + revealed: sent, + revealedChild: const ReceiptScreen(), + child: ReviewScreen( + send: DistortionWaveAnchor( + child: FilledButton( + onPressed: () => setState(() => sent = true), + child: const Text('Send'), + ), + ), ), - child: card, -); +) ``` -| 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. | +Flip `revealed` to send the wave out. Flip it back to bring it home. The +anchor tells the wave where to start, and it leans toward your finger. -`mono` and `gold` never drift, whatever `hueMode` says. - -### Motion +Going to a new page? Push a `DistortionWaveRoute`: ```dart -BorderBeam( - effect: const BeamEffect.rotate(count: 3), - timing: const BeamTiming( - cycle: Duration(seconds: 3), // one lap - cycleGap: Duration(seconds: 1), // rest between laps - direction: BeamDirection.bounce, // alternate each cycle - phaseOffset: 0.25, // start a quarter of the way in - speed: 1.5, // playback rate - huePeriod: Duration(seconds: 8), // colour drift period +Navigator.of(context).push( + DistortionWaveRoute( + source: WaveSource.of(context), + builder: (_) => const ReceiptScreen(), ), - child: card, ); ``` -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 +Five palettes come built in, and any `BorderBeam` palette works too +through `WavePalette.fromBeamColors(BeamColors.aurora)`. Or pass your own +colours: ```dart -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), - repeat: BeamRepeat.count(3), - reducedMotion: BeamReducedMotion.staticFrame, +DistortionWave( + palette: const WavePalette( + colors: [Color(0xFF7C5CFF), Color(0xFF39C6FF), Color(0xFF4CF2B5)], + ahead: Color(0xFFFF8FD8), + behind: Color(0xFF3D5AFE), ), - onActivate: () => debugPrint('visible'), // when the fade-in completes - onDeactivate: () => debugPrint('hidden'), - child: card, -); -``` - -| `BeamReducedMotion` | Behaviour | -| --- | --- | -| `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. | - -`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 - -### Theming - -```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)), - playback: BeamPlayback(reducedMotion: BeamReducedMotion.slow), - ), - child: MaterialApp(home: home), -); -``` - -`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 - -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(controller: controller, child: card); - -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(); // a sharper blink, hold 120ms, decay -controller.stop(); // fade out, halt -``` - -`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 - -```dart -// 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 (normalized 0–1). -BorderBeam(follow: const Offset(0.5, 0.2), child: card); - -// Live opacity and rate, without rebuilding. -BorderBeam( - strengthListenable: micLevel, // ValueListenable - speedListenable: tempo, // ValueListenable, positive - child: card, -); -``` - -| Input | Type | What it does | -| --- | --- | --- | -| `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. | - -Ambient effects ignore `progress` and `follow`. `BeamHover` wires `follow` to the mouse for you. - -### Synchronized groups - -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( - timing: BeamTiming(phaseOffset: i / cards.length), - child: card, - ), - ], - ), -); + // ... +) ``` -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. +## Get started -### Overlay and decoration - -`BorderBeam.overlay` is a beam with no child of its own, sized by its parent: - -```dart -Stack( - children: [ - content, - const Positioned.fill(child: BorderBeam.overlay(borderRadius: 16)), - ], -); +```console +flutter pub add prismatic ``` -`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( - effect: const BeamEffect.rotate(), - brightness: Theme.of(context).brightness, - theme: BorderBeamTheme.of(context), - colors: BeamColors.ocean, - borderRadius: 16, - ), - decoration: BoxDecoration( - color: surface, - borderRadius: BorderRadius.circular(16), - ), - child: content, -); +import 'package:prismatic/prismatic.dart'; ``` -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 +You need Flutter 3.47 or newer. Load the shaders before your first frame, +so the very first beam or wave is smooth: ```dart -BeamFocusRing(borderRadius: 12, child: TextField(decoration: decoration)); -BeamHover(borderRadius: 20, child: pricingCard); -BeamPress(borderRadius: 20, onTap: submit, child: card); -``` - -| Widget | Lights when | Default effect | Notable options | -| --- | --- | --- | --- | -| `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 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 null means *inherit*; the defaults below are what you get when nothing sets a field. - -### `BeamStyle` - -| 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 | -| --- | --- | --- | -| `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 | -| --- | --- | --- | -| `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.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 | 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` | 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 - -`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 -shorthand > value object on the widget > BorderBeamTheme (inner over outer) > effect default -``` - - -## Accessibility - -- **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 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: - - ```xml - CADisableMinimumFrameDurationOnPhone - - ``` - - 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. - -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) - - -## FAQ - -**The beam's corners don't match my card's.** -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.** -`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. 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). - -**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-centre. Swap the anchors for the other side of the border. - -**Does it work 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 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 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 +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await BorderBeam.precache(); + await DistortionWave.precache(); + runApp(const App()); +} ``` -Demo reels live in `example/lib/*.dart` and use the marker-based harness in `example/lib/demo_harness.dart`. Record one on a booted iOS simulator (requires `ffmpeg`): +## Good to know -```console -tool/record_demo.sh --target lib/showcase.dart --prefix SHOWCASE --contact -``` +- Give both screens of a wave an opaque background. The wave paints + pictures of them. +- The beam reads your light or dark theme from + [`material_ui`](https://pub.dev/packages/material_ui). Still on + `package:flutter/material.dart`? Set `BeamStyle(theme: BeamTheme.dark)` + yourself. +- Both effects respect the system's reduced-motion setting. -Outputs land in `.demos/` (gitignored). +## Try it +- **[Live demo](https://simplifyjobs.github.io/prismatic/)** in your browser. +- **[The example app](example)**: `cd example && flutter run`. -## Contributing - -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). +## Learn more +- **[API reference](https://pub.dev/documentation/prismatic/latest/)** on + pub.dev. +- **[Guides](doc/README.md)** for every option, written for you and your coding agent. +- **[Contributing](CONTRIBUTING.md)**: how to build, test and send a change. ## Credits -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. - -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. - +Both effects began as designs by +**[Jakub Antalik](https://x.com/jakubantalik)**: +[border-beam](https://github.com/Jakubantalik/Libraries/tree/main/packages/border-beam) +(React) and +[Distortion waves](https://github.com/Jakubantalik/Libraries.dev/tree/main/packages/distortion-waves) +(SwiftUI), both MIT. prismatic recreates their look with its own Flutter +renderer. If you like it, go star the originals. ## License -MIT. See [LICENSE](LICENSE) — it includes the original work's copyright notice. +MIT. See [LICENSE](LICENSE), and [NOTICE](NOTICE) for the original works. diff --git a/SECURITY.md b/SECURITY.md index bd95a91..79ea0d1 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,9 +2,9 @@ ## Supported versions -Fixes land on the latest published minor of `flutter_border_beam`. Older +Fixes land on the latest published minor of `prismatic`. Older minors are not patched — upgrade to the newest release on -[pub.dev](https://pub.dev/packages/flutter_border_beam) before reporting. +[pub.dev](https://pub.dev/packages/prismatic) before reporting. | Version | Supported | | --- | --- | @@ -16,7 +16,7 @@ minors are not patched — upgrade to the newest release on **Do not open a public issue for a security report.** Use GitHub's private vulnerability reporting: go to the -[Security tab](https://github.com/SimplifyJobs/flutter_border_beam/security) +[Security tab](https://github.com/SimplifyJobs/prismatic/security) of the repository and press **Report a vulnerability**. That opens a private advisory visible only to you and the maintainers. @@ -38,28 +38,35 @@ Please give us a reasonable window to ship a fix before disclosing publicly. ## Scope -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. +This is a **rendering package**. It draws two effects with fragment shaders +that ship inside the package — `BorderBeam`, animated light around a +widget's border (`shaders/beam.frag`), and `DistortionWave`, a wave that +carries one view into another (`shaders/wave.frag` and +`shaders/wave_glow.frag`). It opens no sockets, reads no files other than +its own bundled shader assets, writes nothing, stores nothing, and collects +nothing. Its only runtime dependencies are the Flutter SDK and +[`material_ui`](https://pub.dev/packages/material_ui), for the Material theme +the beam reads its surface from. 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, stops, radii, - durations, segment anchors — that causes a crash, an unbounded allocation, a - hang, or an unrecoverable render-loop failure in a host app. + durations, segment anchors, wave styles, palettes, sources and progress — + 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 - (including `shaders/beam.frag`). + (including the shaders: `shaders/*.frag` and the `shaders/common/*.glsl` + they include). - Anything in the package that reaches the network or the filesystem. There should be nothing; if you find something, that is the report. Out of scope: - Visual bugs, jank, and performance that is merely disappointing — those are - ordinary [issues](https://github.com/SimplifyJobs/flutter_border_beam/issues). + ordinary [issues](https://github.com/SimplifyJobs/prismatic/issues). - 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. diff --git a/assets/demos/wave_center.webp b/assets/demos/wave_center.webp new file mode 100644 index 0000000..854f3c2 Binary files /dev/null and b/assets/demos/wave_center.webp differ diff --git a/assets/demos/wave_horizontal.webp b/assets/demos/wave_horizontal.webp new file mode 100644 index 0000000..a1807a9 Binary files /dev/null and b/assets/demos/wave_horizontal.webp differ diff --git a/assets/demos/wave_vertical.webp b/assets/demos/wave_vertical.webp new file mode 100644 index 0000000..1a0c111 Binary files /dev/null and b/assets/demos/wave_vertical.webp differ diff --git a/doc/README.md b/doc/README.md new file mode 100644 index 0000000..de10c94 --- /dev/null +++ b/doc/README.md @@ -0,0 +1,82 @@ +# prismatic docs — index + +The reference for agents (Claude Code, Codex) and anyone who wants the +details. The root `README.md` is a short introduction for people; everything +it leaves out is here. Repo rules, commands and the full source map are in +[`AGENTS.md`](../AGENTS.md). + +## Which file answers what + +| Question | File | +| --- | --- | +| How do I use `BorderBeam`? Constructor, value objects and defaults, precedence, controller, `BeamSync`, `BeamDecoration`, wrappers, pitfalls | [border_beam_usage.md](border_beam_usage.md) | +| What do `rotate`, `line`, `pulse` do, and which inputs does each read? | [effects.md](effects.md) | +| Presets, custom stops, `fromSeed`, `fromScheme`, `lerp`, `scaleAlpha`, hue drift, palette equality | [palettes.md](palettes.md) | +| Radii, superellipse, stadium, `borderWidth`, `ringOffset`, segments and anchors, dashes | [shape.md](shape.md) | +| Clock, speed, retiming, `cycleGap`, direction, `BeamSync`, `progress`, `follow`, listenables, accents | [motion.md](motion.md) | +| `BeamTheme` (surface tuning) vs `BorderBeamTheme` (subtree defaults), merging | [theming.md](theming.md) | +| How is a beam frame rendered? Layer model, uniform layout, `BeamOutline`, invariants, tests | [architecture.md](architecture.md) | +| How do I use `DistortionWave` / `DistortionWaveRoute`? Sources and anchors, controller, theme, types, palettes, every style field, snapshots, display corners, fallbacks | [distortion_wave_usage.md](distortion_wave_usage.md) | +| How is a wave frame rendered? Timeline, phases, pictures, shader, uniform block, route, invariants, tests | [distortion_wave.md](distortion_wave.md) | +| Reduced motion, semantics, focus, touches — both effects | [accessibility.md](accessibility.md) | +| Frame cost, 120 Hz, offscreen ancestors, snapshot costs — both effects | [performance.md](performance.md) | + +## Package facts + +- **Libraries.** `package:prismatic/prismatic.dart` re-exports both + `package:prismatic/border_beam.dart` and + `package:prismatic/distortion_wave.dart`; each effect can be imported + alone. Their export lists are in the two usage files. +- **Requirements.** Read `pubspec.yaml` (`environment:`, `dependencies:`): + a Flutter floor (tested by CI's `min-sdk` job), a Dart SDK constraint, and + one dependency, `material_ui` (Material without the deprecated + `package:flutter/material.dart`). +- **Shaders.** `shaders/beam.frag`, `shaders/wave.frag` and + `shaders/wave_glow.frag` are declared under `flutter: shaders:` in the + package's pubspec, so a consuming app adds nothing; `shaders/common/*.glsl` + are includes. Each program is loaded once per process (`ShaderProgram`, + `lib/src/core/shader_program.dart`). `BorderBeam.precache()` and + `DistortionWave.precache()` load them ahead of first use. +- **Renderers.** Built for Impeller; the shaders are SkSL strict ES2, so both + effects also run on Skia and the web. +- **Example app.** `example/` — the showcase, also the live demo at + . Commands in `AGENTS.md`. + +## Conventions shared by both effects + +- **All-nullable value objects.** `BeamStyle`, `BeamShape`, `BeamTiming`, + `BeamPlayback`, `WaveStyle` and its groups: `const`, value-equal, + `copyWith` (null keeps) and `merge` (the argument's non-null fields win). + Null means *inherit*. +- **Precedence**, per field: widget shorthand > the widget's value object > + the nearest theme (`BorderBeamTheme` / `DistortionWaveTheme`; every + enclosing theme merged, inner over outer) > the effect's or wave type's + defaults. +- **Pure functions of one number.** A beam's frame is a function of elapsed + time (`BeamClock`); a wave's of progress 0–1 (`WaveFrame.at`). That is what + makes `BeamPlayback.debugFrozenAt`, `DistortionWave.progress`, scrubbing and + goldens possible. +- **A fixed draw budget.** A lit beam frame is one shader draw. A wave frame + that bends content is one shader draw plus at most one atlas draw. Tests + enforce both. +- **Validation in release.** Constructors assert ranges in debug; resolution + re-checks in release — the beam throws `ArgumentError` on invalid timing, + speed, repeat or palette (`models/model_validation.dart`), the wave settles + every value to a finite, in-range one (`WaveSpec`). +- **Reduced motion is honoured by default.** A beam shows a static frame; a + wave becomes a short crossfade. +- **No semantics of their own, never a hit target.** A beam passes hits and + semantics straight through to its child; a wave routes them to the side + that is on screen (or being headed for) — see + [accessibility.md](accessibility.md). + +## Writing these docs + +- Describe how the code works now, with real API names and file paths. +- Don't quote tuned look values — they live in `lib/src/border_beam/look/`, + the emitters, `animation/spring_curve.dart`, and + `lib/src/distortion_wave/look/wave_defaults.dart`, and they change. Name + the constant or getter instead. API defaults that are part of the contract + (a 16 px default radius, a 0.3 s reduced-motion crossfade) are fine. +- Change a usage file with the public API it describes; change an internals + file with the pipeline, uniform layout or module it describes. diff --git a/doc/accessibility.md b/doc/accessibility.md index a2f2c1a..d1d5406 100644 --- a/doc/accessibility.md +++ b/doc/accessibility.md @@ -1,5 +1,7 @@ # Accessibility +How both effects behave for assistive technology, reduced motion, focus and pointers. The sections up to [Contrast and legibility](#contrast-and-legibility) cover `BorderBeam`; [DistortionWave](#distortionwave) covers the wave. + A border beam is decoration. It should make a state easier to notice for people who can see it, and cost nothing for everyone else. Three rules follow from that, and the package enforces two of them for you. ## Reduced motion @@ -69,7 +71,7 @@ BeamFocusRing( 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 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. +Because it only flips `BorderBeam`'s `active`, focus arrives and leaves on the beam's spring fades 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 @@ -79,3 +81,38 @@ The beam mostly paints around content, but `BorderBeam` paints over its child, s - **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: 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. + +## DistortionWave + +Code: `lib/src/distortion_wave/distortion_wave.dart` (the widget's `build`), +`render/render_wave_stage.dart` (touches, semantics), `wave_source.dart` +(anchors). Tests: `test/distortion_wave/widget/distortion_wave_test.dart`. + +- **Reduced motion.** When `MediaQuery.disableAnimations` is on, the wave is a + plain crossfade — the outgoing side fading over the incoming one — and a + full run takes 0.3 s. `DistortionWaveRoute` does the same (both transition + durations become 300 ms). There is no per-wave switch to opt out. +- **Semantics.** The wave adds none of its own. The semantics tree holds only + the side at rest, or, while a wave runs, the side it is heading for — so a + screen reader moves to the new view as soon as the wave starts. +- **Focus.** The side off screen — at rest, or held at either end by + `progress` — is wrapped in `ExcludeFocus`, so Tab, autofocus and focus + traversal never land on a view that cannot be seen. While a wave runs, + focus is not excluded on either side. +- **Touches.** At rest the visible side takes touches. While a wave bends the + views, neither does. Once a reveal no longer bends the revealed side (the + front has crossed the whole view and only colour lingers on the edges), the + revealed side takes touches again, so its controls answer at once. During + a reduced-motion crossfade neither side takes touches until it ends. +- **Keyboard and screen-reader starts.** A `DistortionWaveAnchor` counts as + pressed when focus lands inside it, not only on pointer-down; reached by + keyboard, it forgets its last touch so the wave opens evenly rather than + leaning toward an old touch. When a screen reader activates a button + without touching or focusing it, the wave opens from the only anchor on the + side on screen (rules: [distortion_wave_usage.md](distortion_wave_usage.md#distortionwaveanchor)). +- **Never the only signal.** As with the beam, the wave is emphasis: the + revealed view itself must state the outcome ("Payment sent"). +- **Flashing.** One run is one front crossing once; while colour lingers on + the edges it drifts and breathes slowly (`WaveGlow.rimPulse`; 0 keeps only a + slow drift). Toggling `revealed` repeatedly in quick succession sends the + wave back and forth each time — treat that as a deliberate choice. diff --git a/doc/architecture.md b/doc/architecture.md index b440fb1..4906c36 100644 --- a/doc/architecture.md +++ b/doc/architecture.md @@ -1,6 +1,13 @@ -# Architecture +# Architecture — BorderBeam internals -Two ideas carry the whole package: +This document covers the border beam's renderer; for using it, see +[border_beam_usage.md](border_beam_usage.md). The distortion wave has its +own: **[distortion_wave.md](distortion_wave.md)**. Code both share lives in +`lib/src/core/` (`ShaderProgram`) and `shaders/common/` (`outline.glsl`, +the rounded-superellipse outline every shader includes). `lib/src/core/` +also holds `Oklab`, which only the wave uses so far. + +Two ideas carry the border beam: 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. @@ -14,15 +21,15 @@ Ticker ─► BeamClock ─► BeamPhaseResolver ─► effect emitter ─► Be pause, boost travellers, cycles filters, tables of the light shaders/beam.frag ``` -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. +1. **`BeamClock`** (`lib/src/border_beam/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, `BeamSpringCurve.fadeIn` / `fadeOut`, settling in `BeamClock.fadeInSeconds` / `fadeOutSeconds`), 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/border_beam/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/border_beam/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/border_beam/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/border_beam/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. -`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`. +`BeamPainter` (`lib/src/border_beam/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`. -`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. +`beamProgram` (`lib/src/border_beam/render/beam_program.dart`, a `ShaderProgram` from `lib/src/core/shader_program.dart`) loads `shaders/beam.frag` once per process (`FragmentProgram.fromAsset`, trying the `packages/prismatic/` 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 @@ -61,7 +68,7 @@ The renderer bounds the draw to where light can land: the box grown by the furth ## The design data -`lib/src/look/` holds the tuned values the look is built from — plain data, safe to retune (the goldens will move): +`lib/src/border_beam/look/` holds the tuned values the look is built from — plain data, safe to retune (the goldens will move): | File | Contents | | --- | --- | @@ -69,7 +76,7 @@ The renderer bounds the draw to where light can land: the box grown by the furth | `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. | +| `rotate_look.dart` | The rotate window, the compact window, the head highlight and bloom band tables; the inner blob alpha and scale; blurs; the compact threshold, `compactMaxExtent`. | | `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). | @@ -77,7 +84,7 @@ The renderer bounds the draw to where light can land: the box grown by the furth Some of the shader's maths runs on the CPU too, and the two copies must agree exactly. -**`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. +**`BeamOutline`** (`lib/src/border_beam/render/beam_outline.dart`) is the Dart mirror of the shaders' `outline()` in `shaders/common/outline.glsl`, which every shader includes. `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. **Conic tables.** `BeamFrameData.tableAt` reads a table exactly as the shader's `TABLE_LOOKUP` does; tests read windows and overlays back through it. @@ -96,7 +103,7 @@ Some of the shader's maths runs on the CPU too, and the two copies must agree ex | 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. +That is 672 floats, `beamUniformFloats` — inside the 896 (224 `vec4`s) GLES 3.0 guarantees. `test/border_beam/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 @@ -104,24 +111,24 @@ That is 672 floats, `beamUniformFloats` — inside the 896 (224 `vec4`s) GLES 3. | 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/prismatic.dart`, `lib/border_beam.dart` | `prismatic.dart` is the package barrel and re-exports `border_beam.dart` and `distortion_wave.dart`. `border_beam.dart` 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/` or `effects/effect_emitters.dart` is public. | +| `lib/src/border_beam/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/border_beam_controller.dart` | `BorderBeamController`, a `ChangeNotifier` over one clock. | +| `lib/src/border_beam/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/border_beam/beam_sync.dart` | `BeamSync` and its internal scope — one clock for a subtree. | -### `lib/src/effects/` +### `lib/src/border_beam/effects/` | File | Contents | | --- | --- | | `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/` +### `lib/src/border_beam/look/` The design data (see above). -### `lib/src/render/` +### `lib/src/border_beam/render/` | File | Contents | | --- | --- | @@ -129,14 +136,14 @@ The design data (see above). | `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`. | +| `beam_program.dart` | `beamProgram`, the beam's shared `ShaderProgram`. | | `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. | ### `shaders/beam.frag` 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/` +### `lib/src/border_beam/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`. @@ -144,7 +151,7 @@ The four public value objects (`beam_style.dart`, `beam_shape.dart`, `beam_timin `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/` +### `lib/src/border_beam/animation/` | File | Contents | | --- | --- | @@ -152,13 +159,13 @@ The four public value objects (`beam_style.dart`, `beam_shape.dart`, `beam_timin | `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/` +### `lib/src/border_beam/widgets/` `beam_decoration.dart` (the renderer as a `Decoration`), `beam_focus_ring.dart`, `beam_hover.dart`, `beam_press.dart`. ## Invariants -**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. +**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/border_beam/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. **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). @@ -176,11 +183,11 @@ The four public value objects (`beam_style.dart`, `beam_shape.dart`, `beam_timin | Directory | Covers | | --- | --- | -| `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/` | Five golden families — `beam_`, `palette_`, `motion_`, `surface_`, `widgets_`. | +| `test/border_beam/models/` | The value objects, `BeamConfig.resolve`, `BeamColors` and palettes, `BeamEffect`, segments. | +| `test/border_beam/animation/` | The clock, the spring, phase sampling, travel, and a seeded property test over `BeamPhaseResolver.sample`. | +| `test/border_beam/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/border_beam/widget/` | `BorderBeam` itself: lifecycle, updates, shorthands, theming, sync, speed, progress, follow, motion, playback, cycle gap, shape. | +| `test/border_beam/widgets/` | The four widgets in `lib/src/border_beam/widgets/`. | +| `test/border_beam/golden/` | Five golden families — `beam_`, `palette_`, `motion_`, `surface_`, `widgets_`. | 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/border_beam_usage.md b/doc/border_beam_usage.md new file mode 100644 index 0000000..b1aadbc --- /dev/null +++ b/doc/border_beam_usage.md @@ -0,0 +1,368 @@ +# BorderBeam — usage reference + +How to use `BorderBeam` and its companions: every public type, the +parameters, defaults and precedence, and the pitfalls. Topic guides go +deeper: [effects.md](effects.md), [palettes.md](palettes.md), +[shape.md](shape.md), [motion.md](motion.md), [theming.md](theming.md), +[accessibility.md](accessibility.md), [performance.md](performance.md). How a +frame is rendered: [architecture.md](architecture.md). + +Look values (glow reaches, layer strengths, fade responses) are tuned in +`lib/src/border_beam/look/`, the emitters, and +`lib/src/border_beam/animation/spring_curve.dart`. This page names fields and +describes behaviour; read the code for current numbers. + +## Entry points + +```dart +import 'package:prismatic/border_beam.dart'; // the beam alone +import 'package:prismatic/prismatic.dart'; // both effects +``` + +`lib/border_beam.dart` exports exactly: `BorderBeam`, `BorderBeamController`, +`BorderBeamTheme`, `BorderBeamThemeData`, `BeamSync`, `BeamEffect`, +`RotateEffect`, `LineEffect`, `PulseEffect`, `BeamColors`, +`BeamSeedHarmony`, `BeamDirection`, `BeamEdge`, `BeamHueMode`, +`BeamReducedMotion`, `BeamRepeat`, `BeamAnchor`, `BeamCorner`, +`BeamSegment`, `BeamTheme`, `BeamStyle`, `BeamShape`, `BeamTiming`, +`BeamPlayback`, `BeamDecoration`, `BeamFocusRing`, `BeamHover`, `BeamPress`. +Nothing under `lib/src/border_beam/render/` or `effects/effect_emitters.dart` +is public. + +| Public type | File | +| --- | --- | +| `BorderBeam` | `lib/src/border_beam/border_beam.dart` | +| `BorderBeamController` | `lib/src/border_beam/border_beam_controller.dart` | +| `BorderBeamTheme`, `BorderBeamThemeData` | `lib/src/border_beam/border_beam_theme.dart` | +| `BeamSync` | `lib/src/border_beam/beam_sync.dart` | +| `BeamEffect` and subclasses | `lib/src/border_beam/effects/beam_effect.dart` | +| Value objects, `BeamColors`, options, segments, `BeamTheme` | `lib/src/border_beam/models/` | +| `BeamDecoration`, `BeamFocusRing`, `BeamHover`, `BeamPress` | `lib/src/border_beam/widgets/` | + +## Setup facts + +- The shader (`shaders/beam.frag`) is declared in the package's own pubspec; + a consuming app adds nothing. +- Material is read through `package:material_ui`, not + `package:flutter/material.dart`. Their `Theme` and `ColorScheme` are + different types. Under an app still on `flutter/material.dart`, + `BeamTheme.auto` finds no `material_ui` theme and tunes for a light + surface, and `BeamColors.fromScheme` needs `material_ui`'s `ColorScheme`. + Fix: migrate (`dart fix --apply --code=migrate_design_widgets`) or set + `BeamStyle.theme` explicitly. +- Optional: `await BorderBeam.precache();` in `main()` (after + `WidgetsFlutterBinding.ensureInitialized()`) loads the shader before the + first beam. Without it, a beam paints nothing until the load resolves, + which its fade-in hides. + +## Minimal use + +```dart +BorderBeam( + borderRadius: 16, // match the child's own radius + colors: BeamColors.ocean, + child: Card( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + child: const Padding(padding: EdgeInsets.all(24), child: Text('Working…')), + ), +) +``` + +That is `BeamEffect.rotate()`, the default effect. Everything else lives on +four value objects: + +```dart +BorderBeam( + 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)), + playback: const BeamPlayback(reducedMotion: BeamReducedMotion.staticFrame), + child: card, +) +``` + +## `BorderBeam` + +```dart +const BorderBeam({ + Key? key, + required Widget child, + BeamEffect? effect, + BeamColors? colors, // shorthand for style.colors + bool? active, // shorthand for playback.active + double? borderRadius, // shorthand for a uniform shape.radius + BeamStyle? style, + BeamShape? shape, + BeamTiming? timing, + BeamPlayback? playback, + BorderBeamController? controller, + double? progress, + Offset? follow, + ValueListenable? strengthListenable, + ValueListenable? speedListenable, + VoidCallback? onActivate, + VoidCallback? onDeactivate, +}) +``` + +| Parameter | Behaviour | +| --- | --- | +| `child` | Laid out and hit-tested normally; sits in its own `RepaintBoundary`, so the beam animating never repaints it. | +| `effect` | `BeamEffect.rotate({length, count, comet})`, `.line({edge})`, `.pulse()`. Null → nearest theme's → `rotate()`. See [effects.md](effects.md). | +| `colors`, `active`, `borderRadius` | Shorthands; a non-null value wins over the same field on the value object. | +| `style`, `shape`, `timing`, `playback` | Value objects (tables below). Every field nullable = inherit. | +| `controller` | Attached, it owns playback (see below). Not allowed below a `BeamSync`. | +| `progress` | 0–1. Places the travel instead of the clock: `rotate` becomes a progress ring, `line` a progress bar. Ambient `pulse` ignores it. NaN = unset. | +| `follow` | Normalized point (0–1 per axis) in the box; the travel eases to the nearest border point. `progress` wins. Non-finite = unset. | +| `strengthListenable` | Scales opacity per frame without a rebuild; above 1 brightens, saturating at full opacity. | +| `speedListenable` | Playback rate per frame; wins over `timing.speed` and a controller's `speed`. Must stay positive. Ignored below a `BeamSync`. | +| `onActivate` / `onDeactivate` | Fire when the fade-in / fade-out completes. | +| `BorderBeam.precache()` | `static Future`: loads the shader. | + +`BorderBeam.overlay({...})` takes the same parameters minus `child`: the beam +paints over a `SizedBox.expand()`, so it is sized by its parent: + +```dart +Stack(children: [content, const Positioned.fill(child: BorderBeam.overlay(borderRadius: 16))]) +``` + +The beam adds no semantics and never takes part in hit-testing. + +## Value objects + +All four are `const`, all-nullable, value-equal, with `copyWith` (a null +argument keeps the value) and `merge` (the argument's non-null fields win). +The defaults below are what a field resolves to when nothing sets it +(`BeamConfig.resolve` in `lib/src/border_beam/models/beam_config.dart`). + +### `BeamStyle` + +| Field | Type | Default | Notes | +| --- | --- | --- | --- | +| `colors` | `BeamColors?` | `BeamColors.colorful` | See [palettes.md](palettes.md). | +| `theme` | `BeamTheme?` | `BeamTheme.auto` | `dark` / `light` / `auto` (follows `material_ui`'s `Theme.of(context).brightness`). Picks the dark- or light-surface tuning. | +| `strength` | `double?` | 1 | Overall opacity, clamped 0–1; NaN = 1. | +| `glow` | `double?` | 1 | Scales every glow's reach and, below 1, brightness; 0 leaves only the stroke. Not negative. | +| `hueMode` | `BeamHueMode?` | `effect.defaultHueMode` | `pingPong`, `continuous`, `none`. `mono` and `gold` force `none`. | +| `hueShift` | `double?` | 30 | Degrees either side, `pingPong` only. | +| `hueBase` | `double?` | 0 | Fixed hue rotation, degrees, on top of any drift. | + +Non-finite `glow`, `hueShift`, `hueBase` count as unset. + +### `BeamShape` + +| Field / constructor | Type | Default | Notes | +| --- | --- | --- | --- | +| `BeamShape({radius, superellipse, borderWidth, ringOffset, segment, dashes})` | | | Per-corner. | +| `BeamShape.all(double r, {...})` | | | `const` uniform radius; equal to `circular(r)`. | +| `BeamShape.circular(double r, {...})` | | | Same shape as `all`, built as a `BorderRadius` (not const). | +| `BeamShape.stadium({...})` | | | Each corner half the shortest side; tracks resizes. | +| `radius` | `BorderRadiusGeometry?` | `BeamShape.defaultRadius` (16) on every corner | Direction-aware; clamped like `RRect.scaleRadii`. Not read from the child. | +| `superellipse` | `bool?` | false | Flutter's `RSuperellipse` (matches `RoundedSuperellipseBorder`). | +| `borderWidth` | `double?` | 1 | Stroke thickness, drawn inward from the outline. | +| `ringOffset` | `double?` | 0 | Outline pushed out (+) or in (−) from the bounds; radii are not adjusted. | +| `segment` | `BeamSegment?` | whole border | Clockwise span from top-centre. See [shape.md](shape.md#segments). | +| `dashes` | `int?` | 0 | 2+ = that many dashes; 0/1 solid. Not negative. | + +### `BeamTiming` + +| Field | Type | Default | Notes | +| --- | --- | --- | --- | +| `cycle` | `Duration?` | `effect.defaultCycle` | Positive. Changing it live retimes in place. Floored at `BeamConfig.minCycleSeconds`. | +| `cycleGap` | `Duration?` | `effect.defaultCycleGap` (zero) | Rest after each sweep; travelling effects only. Not negative. | +| `speed` | `double?` | 1 | Finite, positive. Replaced by a controller's `speed`; `speedListenable` wins over both. Scales the animation, never the fades. | +| `direction` | `BeamDirection?` | `forward` | `forward`, `reverse`, `bounce`. Travelling effects only. | +| `phaseOffset` | `double?` | 0 | Fraction of a cycle, 0–1. | +| `huePeriod` | `Duration?` | `effect.defaultHuePeriod` | Positive. Changing it live re-phases the drift (one jump). | + +The effects' own defaults are getters on `BeamEffect` (`defaultCycle`, +`defaultCycleGap`, `defaultHueMode`, `defaultHuePeriod`) in +`effects/beam_effect.dart`. + +### `BeamPlayback` + +| Field | Type | Default | Notes | +| --- | --- | --- | --- | +| `active` | `bool?` | true | Toggling fades in / out on springs. | +| `autoPlay` | `bool?` | true | Starts by itself. | +| `startAfter` | `Duration?` | none | Delay before autoplay. Must be null with a controller. | +| `duration` | `Duration?` | none | Total play time, then a fade-out. Must be null with a controller. | +| `repeat` | `BeamRepeat?` | `BeamRepeat.forever()` | `forever()`, `once()`, `count(n)` (n ≥ 1) cycles, then a fade-out. | +| `reducedMotion` | `BeamReducedMotion?` | `staticFrame` | `staticFrame`, `hide`, `slow` (quarter speed), `animate`. See [accessibility.md](accessibility.md). | +| `pauseWhenOffscreen` | `bool?` | true | Stops the clock while the beam is more than 256 px outside its nearest `Scrollable`'s viewport; resumes where it left off. No `Scrollable` → no effect. | +| `fadeCurve` | `Curve?` | critically damped springs | Replaces both fades. `BeamPlayback.cssEase` is the web's `ease`. | +| `debugFrozenAt` | `Duration?` | none | Pins the beam to one instant and never starts its clock; for goldens and captures. | + +**Release-mode validation.** `BeamTiming` values, a controller's `speed`, +`BeamRepeat.count`, and palette lists are checked at resolve time in release +builds too, and throw `ArgumentError` (`models/model_validation.dart`). + +## Shorthands and precedence + +```text +shorthand (colors:, active:, borderRadius:) > value object on the widget > BorderBeamTheme (inner over outer) > effect default +``` + +The effect follows the same order: widget `effect:` → nearest theme's +`effect` → `BeamEffect.rotate()`. Effects never merge; a widget's effect +replaces the theme's whole. Details: [theming.md](theming.md). + +## `BorderBeamController` + +```dart +final controller = BorderBeamController(); +BorderBeam(controller: controller, child: card); + +controller.start(); // fade in, play; resumes a paused, showing beam +controller.pause(); // freeze the frame (no fade) +controller.resume(); +controller.speed = 2; // finite, positive (throws otherwise) +controller.seek(const Duration(seconds: 1)); // jump the timeline; fades unaffected +controller.pulse(); // one brightness bump that settles +controller.flash(); // a sharper blink: hold, then decay +controller.stop(); // fade out, halt +``` + +- **Ownership.** Attached, the controller owns playback exclusively: + `playback.startAfter` and `playback.duration` must be null (on the widget + *and* any theme — asserted), `active` and `autoPlay` are ignored, the + controller's `speed` replaces `timing.speed`, and the beam starts hidden + until `start()`. +- `speed` and `seek` move the animation only; fades and accents run on real + time. `speedListenable` still wins over the controller's rate; + `BeamReducedMotion.slow` still quarters it. +- `pulse()` / `flash()` are no-ops while the beam is hidden or frozen; + repeated calls each start a fresh accent. +- `isAttached`, `isActive` (visible, fading counts), `isRunning` (producing + frames). It notifies when one of its methods is called — not when the beam + changes state by itself; use `onActivate` / `onDeactivate` for that. +- **One controller, one beam** (asserted). Handing it to another beam in the + same frame is fine. A beam under a `BeamSync` cannot take one. + +## Driving the beam: `progress`, `follow`, listenables + +Summary; details in [motion.md](motion.md#driving-the-travel-yourself). + +| Input | Type | What it does | +| --- | --- | --- | +| `progress` | `double?` 0–1 | Places the travel; the clock keeps running underneath (fade, hue, `line`'s spikes stay alive). Linear, stays lit (no gap rest, no end fades). Repaints without re-resolving the config. | +| `follow` | `Offset?` | Eases the travel to the border point nearest the point (critically damped). Null hands it back to the clock without a snap, keeping its direction. `BeamHover` wires it to the mouse. | +| `strengthListenable` | `ValueListenable?` | Per-frame opacity scale. | +| `speedListenable` | `ValueListenable?` | Per-frame rate. | + +Ambient effects (`pulse`) ignore `progress` and `follow`. + +## `BeamSync` + +```dart +BeamSync( + child: Row(children: [ + for (final (i, card) in cards.indexed) + BorderBeam(timing: BeamTiming(phaseOffset: i / cards.length), child: card), + ]), +) +``` + +`const BeamSync({required Widget child, bool active = true, double speed = 1, +BeamReducedMotion reducedMotion = BeamReducedMotion.staticFrame})`. One +ticker and one timeline for every beam below. The group owns playback: +`active`, `autoPlay`, `startAfter`, `duration`, `repeat`, `fadeCurve`, +`pauseWhenOffscreen`, `timing.speed`, `speedListenable`, and per-beam +`reducedMotion` are ignored below it; a member's `BorderBeamController` +asserts. Effect, palette, shape, `phaseOffset` and `cycle` stay per beam (a +member changing its `cycle` retimes only itself). Details: +[motion.md](motion.md#beamsync). + +## `BeamDecoration` + +The renderer as a `Decoration`, for an existing `Container`. Put it in +`foregroundDecoration:` (paints over the child, as `BorderBeam` does): + +```dart +Container( + foregroundDecoration: BeamDecoration( + effect: const BeamEffect.rotate(), + brightness: Theme.of(context).brightness, // required + theme: BorderBeamTheme.of(context), // optional: inherit app defaults + colors: BeamColors.ocean, + borderRadius: 16, + ), + decoration: BoxDecoration(color: surface, borderRadius: BorderRadius.circular(16)), + child: content, +) +``` + +Takes `effect`, `brightness` (required), `theme`, `colors`, `active`, +`borderRadius`, `style`, `shape`, `timing`, `playback`. A `BoxPainter` has no +`BuildContext`, so compared with `BorderBeam`: + +- ambient theming is passed in, not read (`effect` falls back to + `theme.effect`, then `rotate()`); +- its ticker is not muted by `TickerMode` (keeps ticking in a scrollable's + cache extent or under an inactive route); +- `reducedMotion` and `pauseWhenOffscreen` are inert; +- `active` is a starting state: changing any field replaces the painter, so + flipping `active` cuts instead of fading; +- `lerpFrom`/`lerpTo` return null, so an `AnimatedContainer` snaps; +- `hitTest` returns false. + +Prefer `BorderBeam` when any of these matter. + +## Interaction wrappers + +```dart +BeamFocusRing(borderRadius: 12, child: TextField(decoration: decoration)); +BeamHover(borderRadius: 20, child: pricingCard); +BeamPress(borderRadius: 20, onTap: submit, child: card); +``` + +| Widget | Lights when | `effect` default | Other parameters | +| --- | --- | --- | --- | +| `BeamFocusRing` | `child`'s subtree (or `focusNode`) has focus and `FocusManager.highlightMode` is traditional (keyboard/mouse) | `rotate()` | `focusNode`, `alwaysShow` (also under touch focus). `colors` falls back to `style.colors`, the theme's colours, then `BeamColors.ocean`. | +| `BeamHover` | the cursor is over `child`; the travel follows it | `rotate()` | `followPointer` (default true), `holdAfterExit` (default 300 ms). | +| `BeamPress` | a pointer is down on `child`, held at least `minimumDuration` | `pulse()` | `minimumDuration` (default 600 ms; `Duration.zero` releases on pointer-up), `onTap` (pointer lifts inside; bypasses the gesture arena). | + +All three also take `colors`, `borderRadius`, `style`, `shape`, `timing` and +pass them to an inner `BorderBeam`; transitions use the beam's own fades. +Their `effect` is a non-nullable parameter with a default, so a +`BorderBeamTheme`'s `effect` does **not** apply to them — pass `effect:` +explicitly. `BeamPress` listens through a translucent `Listener` and never +enters the gesture arena: buttons inside keep their taps, scrollables above +keep their drags. + +## Pitfalls + +- **Corners don't match the child.** The beam never reads the child's + decoration. Pass the same radius (`borderRadius:` / `shape.radius`) and + `superellipse: true` for a `RoundedSuperellipseBorder` child. +- **Beam clipped.** `rotate(comet: true)` and a positive `ringOffset` paint + outside the child's box. Leave room (padding in the parent); remove tight + `ClipRRect`/`ClipPath` above it. +- **Nothing shows.** Reduced motion with `BeamReducedMotion.hide`; `strength: + 0`; or, in a widget test, the shader not loaded — `setUpAll(BorderBeam.precache)`. +- **Translucent child.** Fine: the beam paints in one pass over the child. +- **Segment runs the wrong way.** Segments always run clockwise from `start` + to `end`, wrapping through top-centre; swap the anchors. +- **Fading a beam with `Opacity`.** Forces an offscreen pass every frame. Use + `style.strength`, `strengthListenable`, or `active`. See + [performance.md](performance.md#impeller-keep-the-beam-off-offscreen-ancestors). +- **Palette rebuilt unequal every build** (e.g. a fresh `List` of computed + colours that differ) re-resolves the config each frame. `BeamColors` is + value-equal, so inline `const`/equal palettes are free. +- **Animating between configurations.** `BorderBeam` retimes `cycle` in place + and `BeamColors.lerp` crossfades palettes; `BeamDecoration` snaps. +- **Controller + theme scheduling.** `startAfter`/`duration` in an app-wide + `BorderBeamTheme` assert on every controller-driven beam below it. +- **Web.** Supported; the example app's web build is the live demo and CI + builds it. + +## Testing a beam + +- `setUpAll(BorderBeam.precache)` before reading pixels or counting draws. +- `playback: BeamPlayback(debugFrozenAt: …)` pins a frame; goldens freeze the + fake clock at t = 1.3 s instead (`test/border_beam/golden/golden_scene.dart`). +- The first tick after `Ticker.start()` reports elapsed 0: pump once before + pumping durations. +- No ticker may survive disposal: `tester.binding.transientCallbackCount` + returns to 0 (`test/border_beam/widget/border_beam_lifecycle_test.dart`). diff --git a/doc/distortion_wave.md b/doc/distortion_wave.md new file mode 100644 index 0000000..be2609c --- /dev/null +++ b/doc/distortion_wave.md @@ -0,0 +1,337 @@ +# DistortionWave — internals + +How a distortion wave is built, from its timeline to the draws a frame +takes. For using it, see [distortion_wave_usage.md](distortion_wave_usage.md); +for the border beam's renderer, [architecture.md](architecture.md). Code +shared with the beam: `lib/src/core/shader_program.dart` (`ShaderProgram`) +and `shaders/common/outline.glsl`, mirrored in Dart by `BeamOutline` +(`lib/src/border_beam/render/beam_outline.dart`). The wave's colours are +mixed in OKLab with `Oklab` (`lib/src/core/oklab.dart`), which lives in +`lib/src/core/` but only the wave uses. + +Three ideas carry it: + +1. **Everything is a pure function of one progress value.** `WaveFrame.at` + turns progress (0–1 over the wave's whole life), the source, the view's + size and the settled style into every number the frame needs. Nothing is + integrated frame to frame, which is what lets the wave scrub, reverse + mid-way, run off a route's animation, and freeze for a golden. +2. **The views are drawn from pictures of themselves.** While the wave bends + content, each side is rasterised to a GPU image (plus two blurred copies), + and one fragment shader draws the frame from those images. The frame's own + canvas gets no layer, clip, `BackdropFilter`, `ImageFilter` or image draw; + the pictures and their blurred copies are separate offscreen renders made + only when a side is pictured. +3. **A picture is taken only when it is needed.** Once when the wave first + needs a side, and again only when that side's content repaints (or every + frame, under `WaveSnapshots.everyFrame`); released as soon as the content + no longer bends. + +## Module map + +| Path | Contents | +| --- | --- | +| `lib/distortion_wave.dart` | The library: exports the public types only. | +| `lib/src/distortion_wave/distortion_wave.dart` | `DistortionWave` and its state (clock, controller binding, anchor registry, theme/shorthand resolution into a `WaveSpec`, `maintainState`, `TickerMode` and `ExcludeFocus` for the side off screen); `WaveStage` (a `SlottedMultiChildRenderObjectWidget` over `RenderWaveStage`); `WaveSide` / `RenderWaveSide` (reports repaints of a side to the stage). | +| `lib/src/distortion_wave/distortion_wave_route.dart` | `DistortionWaveRoute` and its transition widget. | +| `lib/src/distortion_wave/distortion_wave_controller.dart` | `DistortionWaveController`; the unexported `WaveDriver` interface (implemented by the wave's state) and `DistortionWaveControllerBinding` (`attach`/`detach`/`arrived`). | +| `lib/src/distortion_wave/distortion_wave_theme.dart` | `DistortionWaveTheme`, `DistortionWaveThemeData`. | +| `lib/src/distortion_wave/wave_source.dart` | `WaveSource` (sealed: rect / key / global / none), `defaultWaveSource`, `DistortionWaveAnchor` + state, `WaveAnchorRegistry`, `WaveAnchorScope`. | +| `lib/src/distortion_wave/models/` | Public value objects (`wave_style.dart`, `wave_timing.dart`, `wave_motion.dart`, `wave_lens.dart`, `wave_glow.dart`, `wave_dots.dart`, `wave_palette.dart`, `wave_type.dart`, `wave_snapshots.dart`) and the internal `wave_spec.dart`. | +| `lib/src/distortion_wave/look/wave_defaults.dart` | `waveDefaults(type)`: each type's fully set, tuned style; `waveTravelEasing`, `waveRimEasing`. | +| `lib/src/distortion_wave/timeline/` | `wave_frame.dart` (`WaveFrame.at`, `waveCoverZone`, `waveSmooth`), `wave_particles.dart` (`WaveParticle.all(spec)`, cached for the last few specs), `wave_rim.dart` (`WaveRim.lumps`, `WaveRim.count`, `thickness`), `wave_clock.dart` (`WaveClock`). | +| `lib/src/distortion_wave/render/` | `render_wave_stage.dart` (`RenderWaveStage`, `WaveSlot`, `WavePhase`), `wave_snapshot.dart` (`WaveSideImages`), `wave_frame_data.dart` (`WaveFrameData`, `waveUniformFloats`, `wavePaletteSlots`, `waveNearBlur`), `wave_programs.dart` (`waveProgram`, `waveGlowProgram`, `loadWavePrograms`), `dot_atlas.dart` (`DotAtlas`), `wave_warm_up.dart` (`warmUpWaveRendering`). | +| `shaders/wave.frag`, `shaders/wave_glow.frag` | The two programs, declared under `flutter: shaders:`. | +| `shaders/common/wave_uniforms.glsl`, `wave_field.glsl`, `wave_colour.glsl`, `outline.glsl` | Includes (not listed in the pubspec; impellerc gets `shaders/` as an include path). | + +## Settling the look: `WaveSpec` + +`WaveSpec.resolve(style, fallback: themeStyle)` layers the widget's style +(with the `type`/`palette` shorthands merged over it) over the merged theme +style, picks the type (else `vertical`), and merges the result over +`waveDefaults(type)`. Every field is then converted to seconds and logical +pixels and settled to a finite value: the constructors' `assert`s vanish in +release builds, so `_within` maps NaN to the field's floor and clamps to its +range, and `_finite` maps a non-finite signed length to 0. Equality is the +resolved style's, so a rebuild with an equal style changes nothing in the +render object (`RenderWaveStage.spec` returns early on `==`). + +`duration` = anticipation + the latest of (travel × 0.6, linger + rimFade, +linger + hairlineLinger + hairlineFade, dot life). `returnDuration` = +`duration / returnSpeed`. + +## The timeline + +The wave's life, in order (`lib/src/distortion_wave/timeline/wave_frame.dart`): + +1. **Anticipation.** Everything is pulled toward the source, more the nearer + it is; a ring of colour falls in onto where the front will start; dots hop + toward the source and fade before reaching it. +2. **Launch.** The front leaves the source's own outline. For the vertical + and horizontal waves the front is an offset of a pill — the source's long + side — whose straight spine shrinks to nothing while its radius grows, so + it opens into an arc; its x axis is squashed so the arc bows across a tall + screen. It leans toward the touch as it opens. The center wave is a ring + from the source's centre, and leaves the source itself alone (`hold`). +3. **Travel.** The front crosses the view on the wave's easing (fast out of + the source, settling softly). The swell, blur and colour on the front die + away over the middle part of the travel, while the front still moves. +4. **Edges.** The colour the band left on the view's edges clings there, + uneven and drifting, with a hairline on the glass; a second, later front + wipes the colour away, and a third, later still, the hairline. + +`WaveFrame` reports which sides show (`showsOutgoing` until the front has +crossed the whole view — `hasCleared` — and `showsIncoming` once it has +`launched`), whether content is bent (`bendsContent`: `energy > 0 || +gravity > 0`) and whether the content can be drawn as itself +(`contentAtRest`: cleared and not bent). `WaveParticle` and `WaveRim` are +pure in the same way. + +A reveal runs the clock linearly over `duration`; a collapse runs it back on +`spec.easing` over `returnDuration`. `WaveClock` runs from wherever progress +is, at a full run's speed (half the way takes half the time); a new `runTo` +interrupts the one in flight without a jump, and its `onDone` is dropped. A +route drives the same stage from its own animation, curved linearly forward +and on `spec.easing.flipped` in reverse. + +## The frame + +```text +WaveClock or route animation (or the held `progress`) + └─► RenderWaveStage.paint + ├─ WaveFrame.at(progress, source, size, spec, focus) + ├─ phase: rest │ distorting │ glowing │ crossfading + ├─ WaveSideImages for each side shown (taken or reused) + ├─ WaveFrameData ─► wave.frag ─► one drawRect + └─ DotAtlas ─► at most one drawRawAtlas +``` + +| Phase | When | Draws | +| --- | --- | --- | +| `rest` | progress 0 or 1 (or the shader not yet loaded) | the visible side, as itself; images released | +| `distorting` | the wave bends content, or the outgoing side still shows | both sides' images through `wave.frag` (one `drawRect`), and the dots | +| `glowing` | `contentAtRest` | the revealed side as itself, `wave_glow.frag` over it (one `drawRect`, skipped when edge colour and band are both 0), and the dots; images released | +| `crossfading` | reduced motion (`plain`), or a side that cannot be rasterised | the incoming side, and the outgoing one over it in a `pushOpacity` layer (with no outgoing side — a route over a page it could not picture — the incoming side fading in in that layer); images released | + +The stage is a repaint boundary that repaints on every change of its +progress listenable. A side that is not shown is never pictured; its sampler +slots are bound to the other side's images so every sampler is set. + +### Pictures of the sides + +`WaveSideImages.take(side, devicePixelRatio)` paints a side into a detached +`OffsetLayer` and rasterises it with `toImageSync` at the device pixel ratio +— the technique of Flutter's `SnapshotWidget`. It returns null when the +layer does not support rasterisation (a platform view); the stage then +crossfades for the rest of that run (`_unrasterizable`, reset at rest). + +`bakeBlurs(near, far)` then makes two blurred copies from the sharp image, +each one `drawImageRect` with `ImageFilter.blur` (edge-clamped tile mode) +into a `Picture` rasterised with `toImageSync`: + +- *near*: blurred by `min(waveNearBlur, spec.blur)`, at one pixel per logical + pixel; +- *far*: blurred by `spec.blur`, at half a pixel per logical pixel. + +They are baked on the first frame that has blur to show +(`frame.energy > 0 && spec.blur > 0`) and kept with that picture +(`hasBlurs`); a new picture bakes them again. With `blur: 0` they are never +baked and the shader reads the sharp image in their slots. + +Each side sits under a `RenderWaveSide`, which overrides `markNeedsPaint`: a +repaint anywhere below that is not caught by a repaint boundary passes +through it on its way up and flags the side (`RenderWaveStage.sideChanged`), +and the next frame that needs the side takes a new picture. The wave's own +animation repaints only the stage, so it never triggers one. Content inside +a nested `RepaintBoundary` repaints without passing through, which is what +`WaveSnapshots.everyFrame` is for: it re-takes (and re-bakes) every shown +side on every `distorting` frame. + +Pictures are released (`_release`) whenever a frame is not `distorting`, when +a side stops showing, when the device pixel ratio changes, and on +`detach`/`dispose`. + +### `wave.frag` + +Per pixel, in the stage's logical coordinates (see the shader's header): + +1. **The field** (`common/wave_field.glsl`): the signed distance `d` to the + front, divided by the gradient of the squashed metric so it stays a + distance, plus a slow bend along the front. Every other part reads `d`, so + the swell, the blur and the colour can never drift apart. +2. **The lens:** one rise per pixel as the swell passes (steeper ahead, long + behind), along the field's normal, plus the pull toward the source before + the launch. The held source of the center wave is left alone. +3. **The blur:** the radius this content should have — gathering ahead of + the front, peaking on it, clearing slowly behind — evaluated with the + field moved along with the content, then turned into the coverage of the + near and far copies. Sharp → near → far: the reference's stacked blurred + copies, mixed in one pass. +4. **The crossfade:** ahead of the front the outgoing side covers the + incoming one, with a zone either side of the front where they fade. +5. **Colour fringing:** the colours part along the way a pixel has moved, in + proportion to how far, over five taps across the spectrum; anything that + moved less than a quarter of a point takes one tap and stays clean. +6. **The colour** (`common/wave_colour.glsl`), over the content: the band on + the front (the palette flowing along it in OKLab, the `ahead` fringe in + front of it, the `behind` fringe after it, a near-white core) and the rim + and hairline on the view's edges, which follow the shared `outline()` — + Flutter's rounded superellipse, each corner with its own radius — and its + arc length. The rim's lumps arrive as uniforms, computed once a frame by + `WaveRim.lumps`. + +`wave_glow.frag` is step 6 alone, for the `glowing` phase. + +### The edges' corners + +`RenderWaveStage._corners`: when the widget passed the display's radii +(`MediaQuery.maybeDisplayCornerRadiiOf`, only when no style or theme sets +`WaveGlow.cornerRadius`) and the stage fills the view (global origin and +`MediaQuery.sizeOf` size, within half a pixel), each corner takes the +display's radius; otherwise all four take `spec.cornerRadius`. The stage +builds a `BeamOutline` (superellipse) from those radii, cached until the +size or corners change, and writes its radii, perimeter and quadrant starts +into the uniforms. The largest radius goes into `uBand.w`, bounding where the +edge colour can reach. + +### The uniform block + +`shaders/common/wave_uniforms.glsl` declares the float uniforms once; both +shaders include it, and `WaveFrameData` (`render/wave_frame_data.dart`) +writes them in that order, all `vec4`s: + +| Uniform | Contents | Writer | +| --- | --- | --- | +| `uRect` | the stage in the canvas: left, top, width, height | `setStage` | +| `uView` | px per device px, dither, outline perimeter | `setStage` | +| `uQuads` | arc length where each quadrant starts | `setStage` | +| `uFront0`–`uFront4` | the front, time, strengths, wipes, ring/hold, which sides show | `setFrame` | +| `uLens`, `uBlur`, `uBand`, `uRim`, `uHair` | the settled style: lens, blur levels (near, far), band (+ largest corner), rim, hairline (+ palette colour count) | `setSpec` | +| `uStops[8]` | palette colours in OKLab, cycled to fill `wavePaletteSlots` | `setSpec` | +| `uFringe[2]` | the `ahead` and `behind` fringes in OKLab | `setSpec` | +| `uLumps[7]` | the rim's lumps (`WaveRim.count`) | `setLumps` | +| `uRadii` | corner radii TL, TR, BR, BL | `setStage` | + +That is 31 `vec4`s, **124 floats** — `waveUniformFloats`. `wave.frag` then +declares its six samplers, in the order the renderer binds them: the +outgoing side's sharp, near and far images, then the incoming side's. +`setSpec` is rewritten only when the spec or the corners change; +`setStage`, `setFrame` and `setLumps` every frame. `upload` writes all 124 +floats. + +`test/distortion_wave/render/wave_uniform_layout_test.dart` (through +`test/support/shader_source.dart`, which inlines `#include`s) checks that +both shaders declare the same block, that every float uniform is a `vec4` or +`vec4` array, that the arrays hold what `WaveFrameData` packs, that the +shaders' loops visit every slot, that the total equals `waveUniformFloats` +(and fits the 224 `vec4`s GLES 3.0 guarantees), that each writer lands in the +uniform declared at its offset, and the six samplers' order. + +## The dots + +`DotAtlas` draws every visible dot in one `drawRawAtlas`: one anti-aliased +white disc sprite, scaled per dot and modulated by its opacity. The sprite is +rendered once per diameter in device pixels and kept until the diameter +changes. **Each `RenderWaveStage` owns its `DotAtlas` and disposes it in +`dispose()`**, so no image outlives its wave. Dot positions come from +`WaveParticle.all(spec)` (cached for the last few specs) evaluated on the frame. + +## Anchors and sources + +Every `DistortionWave` owns one `WaveAnchorRegistry` and wraps **each side +in its own `WaveAnchorScope`** (`onRevealedSide` true for the incoming side, +false for the outgoing). An anchor registers on `didChangeDependencies` with +its side, and reports `pressed` on pointer-down and when focus lands inside +it (keyboard focus also clears its `lastTouch`). `sourceFor(revealedOnScreen:)` +picks: last pressed if on the side on screen → the only anchor on that side +→ last pressed anywhere → none. The wave's state calls it only when a run +starts from rest (`_sourceForRun`), so the source never changes mid-wave. +`DistortionWaveRoute` wraps its stage in a registry of its own, made once +per route, so anchors in a route's page never register with an enclosing +wave. The rules as a user sees +them: [distortion_wave_usage.md](distortion_wave_usage.md#where-the-wave-opens-from). + +`RenderWaveStage` resolves its source lazily (`_origin`) and keeps the +result until the source changes (by `==`), the type changes, or — for the +default spot only — the stage is laid out again. + +## Touches, focus, semantics, warm-up + +- **Touches** (`_touchable`): the side at rest; while running, none, except + the revealed side once a reveal reaches `contentAtRest` (never while + crossfading). +- **Focus**: the widget wraps the side off screen — `child` at progress 1, + `revealedChild` at progress 0, at rest or held there — in `ExcludeFocus`. +- **Tickers**: at rest the hidden side is under `TickerMode(enabled: false)`; + with `maintainState: false` it is not built at all. +- **Semantics** (`visitChildrenForSemantics`): the side at rest, or the side + the wave is heading for (`revealing`). +- **Warm-up**: `DistortionWave.precache()` awaits `loadWavePrograms()` and + then `warmUpWaveRendering()` draws both shaders, a blurred bake and an + atlas once into a 4 × 4 image, so the GPU builds those pipelines before the + first wave rather than on its first frames. + +## The route + +`DistortionWaveRoute` drives the same `WaveStage` from its animation. The +incoming side is the new page; the outgoing side is a `RawImage` of the page +underneath, pictured from that route's own page `RepaintBoundary` +(`subtreeContext`'s render object) with `toImageSync` in a post-frame +callback after the push's first frame — until then the outgoing side is +empty, so the page underneath shows through and nothing jumps — and again +after a pop starts. The old image is disposed when replaced and in +`dispose()`. A page whose layer does not support rasterisation (a platform +view) is not pictured: the transition then gives the stage no outgoing side +and `plain: true`, so the new page fades in over the live page underneath, +and out on pop. `canTransitionFrom` is false, so the page underneath plays no +exit transition of its own behind the wave. + +The route's `CurvedAnimation` (linear forward, `spec.easing.flipped` in +reverse) is **made once** — `buildTransitions` runs every frame, and a curve +made there would add a listener to the route's animation each time — and +disposed with the route; it is remade only if the parent animation changes. +`spec` is resolved once, lazily, against `DistortionWaveTheme.of` the +navigator's context. Durations: `spec.duration` / `spec.returnDuration`, or +300 ms each under reduced motion. + +## Invariants + +- **Distortion window: one shader `drawRect` and at most one `drawRawAtlas` + per frame** on the stage's canvas, with no `saveLayer`, clip, filter or + image draw; at rest, the visible side and nothing else; glowing, the + revealed side plus one `drawRect` and at most one atlas. + `test/distortion_wave/render/wave_frame_budget_test.dart` asserts this per + phase × type. +- **A side is pictured only when its content changed** (or every frame under + `everyFrame`), and released when the phase leaves `distorting`. The + snapshot-count tests in the same file and the lifecycle test pin both. +- **The uniform block and `WaveFrameData` change together**, in one commit. +- **`WaveFrame` is pure**: a function of progress, source, size, spec and + focus. Tickers and images live in the clock and the stage. +- **The shaders are SkSL strict ES2** (constant loop bounds, arrays indexed by + constants or loop indices), so they run on Skia and the web too. +- **Never `ImageFilter.shader` or `BackdropFilter`** for the wave: they are + Impeller-only, need a new filter object every frame, and hit open engine + bugs (flutter#185175, #187820). + +## Calibration + +The look is the reference's: its timeline, field, colour model, palettes and +tuned styles. The port was checked by building the reference +(DistortionWavesKit) into a throwaway SwiftUI harness, rendering it with +`ImageRenderer` at fixed progress (`scrub:`) over mock screens, rendering the +Flutter wave at the same progress over the same screens, and comparing pixel +by pixel. The harness is built with `xcodebuild`, which needs the Metal +Toolchain. The goldens in `test/distortion_wave/golden/` pin those scenes. +When retuning `wave_defaults.dart`, repeat the comparison at the golden +scenes' progress values, then regenerate only the affected goldens. + +## Tests + +| Path | Covers | +| --- | --- | +| `test/distortion_wave/models/` | Value objects (`copyWith`, `merge`, `==`, ranges asserted), `WaveSpec.resolve` (precedence, per-type defaults, release-mode settling, durations), palettes. | +| `test/distortion_wave/timeline/` | `WaveFrame`, ported case for case from the reference's `WaveFrontTests`, plus a seeded property sweep; particles, rim, clock. | +| `test/distortion_wave/render/` | Uniform layout of both shaders, the frame budget per phase × type and the snapshot counts (`wave_frame_budget_test.dart`), where pixels land in real frames (`wave_paint_structure_test.dart`). | +| `test/distortion_wave/widget/` | Behaviour (sources, anchors, focus, touches, controller, theme, holding, display corners), lifecycle, the route. Helpers in `wave_test_utils.dart`. `distortion_wave_lifecycle_test.dart` and `distortion_wave_route_test.dart` call `LeakTesting.enable()` (`leak_tracker_flutter_testing`, a dev dependency), so an object Flutter's leak tracker instruments — an image, a `ChangeNotifier`, a `CurvedAnimation` — that is created and never disposed fails them. | +| `test/distortion_wave/golden/` | `wave_golden_test.dart`: each type at its telling moments, palettes, mixed display corners; scenes held with `progress:`. | diff --git a/doc/distortion_wave_usage.md b/doc/distortion_wave_usage.md new file mode 100644 index 0000000..537f2d1 --- /dev/null +++ b/doc/distortion_wave_usage.md @@ -0,0 +1,593 @@ +# DistortionWave — usage reference + +How to use `DistortionWave` and `DistortionWaveRoute`: every public type, +what each parameter does, the rules that decide where a wave opens from, and +the pitfalls. How the wave is rendered is in +[distortion_wave.md](distortion_wave.md); its cost in +[performance.md](performance.md#distortionwave); accessibility in +[accessibility.md](accessibility.md#distortionwave). + +Look values (durations, distances, strengths) are tuned per type in +`lib/src/distortion_wave/look/wave_defaults.dart`. This page names fields and +describes behaviour; read that file for current numbers. + +## Entry points + +```dart +import 'package:prismatic/distortion_wave.dart'; // the wave alone +import 'package:prismatic/prismatic.dart'; // both effects +``` + +`lib/distortion_wave.dart` exports exactly: `DistortionWave`, +`DistortionWaveRoute`, `DistortionWaveController`, `DistortionWaveTheme`, +`DistortionWaveThemeData`, `DistortionWaveAnchor`, +`DistortionWaveAnchorState`, `WaveSource`, `WaveType`, `WaveStyle`, +`WaveTiming`, `WaveMotion`, `WaveLens`, `WaveGlow`, `WaveDots`, +`WavePalette`, `maxWavePaletteColors`, `WaveSnapshots`. Nothing under +`lib/src/distortion_wave/render/`, `timeline/` or `look/` is public. + +| Public type | File | +| --- | --- | +| `DistortionWave` | `lib/src/distortion_wave/distortion_wave.dart` | +| `DistortionWaveRoute` | `lib/src/distortion_wave/distortion_wave_route.dart` | +| `DistortionWaveController` | `lib/src/distortion_wave/distortion_wave_controller.dart` | +| `DistortionWaveTheme`, `DistortionWaveThemeData` | `lib/src/distortion_wave/distortion_wave_theme.dart` | +| `WaveSource`, `DistortionWaveAnchor`, `DistortionWaveAnchorState` | `lib/src/distortion_wave/wave_source.dart` | +| `WaveStyle` and its groups, `WavePalette`, `WaveType`, `WaveSnapshots` | `lib/src/distortion_wave/models/` | + +## Minimal use + +```dart +DistortionWave( + revealed: sent, // flip to run the wave + revealedChild: const ReceiptScreen(), + child: ReviewScreen( + send: DistortionWaveAnchor( // the wave opens from this button + child: FilledButton( + onPressed: () => setState(() => sent = true), + child: const Text('Send'), + ), + ), + ), +) +``` + +Flip `revealed` to `true` to send the wave out to `revealedChild`; flip it +back to `false` to collapse it into its source. Flipping mid-run turns the +wave back from wherever it is. + +Optional, in `main()` after `WidgetsFlutterBinding.ensureInitialized()`: +`await DistortionWave.precache();` — loads both wave shaders and draws each +once into a 4 × 4 offscreen image so the GPU has built its pipelines before +the first wave. Without it, a wave started before the shaders load shows its +sides plainly (the side the wave is on) until they do. + +## `DistortionWave` + +```dart +const DistortionWave({ + Key? key, + bool revealed = false, + required Widget revealedChild, + required Widget child, + WaveSource? source, + WaveType? type, + WavePalette? palette, + WaveStyle? style, + DistortionWaveController? controller, + double? progress, // asserted 0–1 + WaveSnapshots? snapshots, + bool maintainState = true, + VoidCallback? onFinish, +}) +``` + +| Parameter | Behaviour | +| --- | --- | +| `revealed` | Target side. `true` runs toward `revealedChild`, `false` back to `child`. Ignored while a `controller` is attached. The initial value sets the side the wave starts resting on. | +| `child` | The side shown at progress 0 (the "outgoing" side). | +| `revealedChild` | The side shown at progress 1 (the "incoming" side). | +| `source` | Where the wave opens from. Null → the anchor rules below. Read only when a run starts from rest. | +| `type` | Shorthand for `style.type`; wins over it. | +| `palette` | Shorthand for `style.palette`; wins over it. | +| `style` | Everything else; over the nearest `DistortionWaveTheme`'s style, over the type's tuned defaults. | +| `controller` | Attached, it owns playback; `revealed` is ignored. | +| `progress` | Non-null holds the wave at that point of its life (0–1) instead of animating. Back to null plays on from the held point toward `revealed` (or the controller's `isRevealed`). | +| `snapshots` | When the sides are pictured again while bent. Null → theme's → `WaveSnapshots.onChange`. | +| `maintainState` | `true`: the hidden side stays mounted at rest, tickers muted. `false`: the hidden side is built only while a wave runs (it loses its state). | +| `onFinish` | Called when a run arrives (reveal: the edges have cleared; collapse: back at rest), the reduced-motion crossfade included. Not called for a run interrupted by another run or by `controller.seek`. | +| `DistortionWave.precache()` | `static Future`. See above. | + +### Layout, touches, focus, semantics + +- **Layout.** With bounded constraints the wave takes the biggest size; with + an unbounded axis it takes the larger of its two children. Both sides are + then laid out tight to that size — each side fills the wave. +- **Opaque sides.** Both sides are drawn from pictures of themselves while the + wave bends them; transparent pixels in a side show nothing behind the wave. + Give both sides an opaque background (a `ColoredBox`, a `Scaffold`). +- **Touches.** At rest, the visible side. While a wave runs, neither — except + that once a reveal no longer bends the revealed side (the `glowing` phase: + the front has crossed the whole view), the revealed side takes touches + while colour lingers on the edges. Under reduced motion no side takes + touches until the crossfade ends. +- **Focus.** The side off screen — at rest, or held at either end by + `progress` — is wrapped in `ExcludeFocus`: Tab and autofocus never land on + it. During a run neither side is excluded. +- **Tickers.** At rest the hidden side sits under `TickerMode(enabled: + false)`. While a wave runs, or while held by `progress`, both tick. +- **Semantics.** The semantics tree contains only the side at rest, or, while + a wave runs, the side it is heading for. + +## Where the wave opens from + +A wave opens from a **source**: a rect (the button, edge or avatar that +started it) and optionally a **focus** point (the touch), which the +`vertical` and `horizontal` waves lean toward (`WaveMotion.orientation`; the +`center` wave never leans). + +The source of a run is taken **once, when the run starts from rest** (also +when `controller.seek` or a non-null `progress` picks the wave up at rest). +Changing `source` mid-run has no effect until the next run from rest. Order: + +1. the `source:` argument of `controller.reveal` / `collapse` / `toggle` + (honoured only at rest); +2. `DistortionWave.source`; +3. a `DistortionWaveAnchor` inside the wave (rules below); +4. the type's usual spot (`defaultWaveSource` in `wave_source.dart`): a wide + button along the bottom for `vertical`, the left edge for `horizontal`, a + small square in the centre for `center`. Also used when a source cannot be + measured (its widget is gone). + +### `WaveSource` + +| Constructor | Coordinates | Measured | +| --- | --- | --- | +| `WaveSource.rect(Rect rect, {Offset? focus})` | the wave's own (local) | never — used as given | +| `WaveSource.key(GlobalKey key, {Offset? focus})` | widget measured globally; `focus` global | at the first frame of each run that needs it | +| `WaveSource.of(BuildContext context)` | global | immediately, at the call | + +`WaveSource.of(context)` measures the widget at `context`; if `context` is +inside a `DistortionWaveAnchor`, it measures the anchor instead and carries +the anchor's last touch as the focus. Call it where the wave starts (a +button's `onPressed`), not in `build`. All sources are value-equal. + +The stage (`RenderWaveStage`) measures its source on the first frame of a +run that needs it, keeps that measurement until the run ends (so nothing +jumps mid-wave), and drops it whenever it paints at rest. A +`WaveSource.key` handed in unchanged is therefore re-measured every run, +and finds a widget that moved since (a scroll, a rotation). Pinned by +`a source by key is measured afresh each run` in +`test/distortion_wave/widget/distortion_wave_test.dart`. + +### `DistortionWaveAnchor` + +```dart +DistortionWaveAnchor(child: FilledButton(onPressed: send, child: const Text('Send'))) +``` + +Marks its child as a candidate source and records where it was touched. +`DistortionWaveAnchorState.lastTouch` is the last pointer-down position +(global), or null. + +An anchor counts as **pressed** when: + +- a pointer goes down on it (a `Listener`; never enters the gesture arena); +- focus lands anywhere inside it (`Focus.onFocusChange`; the anchor's own + `Focus` is not focusable, skips traversal, adds no semantics). When the + focus arrives in keyboard highlight mode (`FocusHighlightMode.traditional`), + the anchor drops its stale `lastTouch`, so the wave opens evenly instead of + leaning toward an old touch. + +Each side of a wave has its own `WaveAnchorScope` (one shared +`WaveAnchorRegistry` per wave, which records each anchor's side). When a run +starts, the side on screen picks: + +1. the anchor pressed or focused last, if it is on the side on screen; +2. else the **only** anchor on the side on screen, if there is exactly one — + this covers a screen reader activating a button without touching or + focusing it; +3. else the anchor pressed or focused last on the other side — so a collapse + started by something other than an anchor goes back into the anchor the + wave opened from; +4. else none (→ `source:` was null too → the type's usual spot). + +With two or more anchors on the side on screen and none pressed there, rule +3 applies. Anchors inside a `DistortionWaveRoute`'s page register with the +route's own scope, not with any enclosing `DistortionWave`. + +## `DistortionWaveRoute` + +```dart +DistortionWaveAnchor( + // A context inside the anchor, so WaveSource.of measures the anchor and + // carries its touch. + child: Builder( + builder: (context) => FilledButton( + onPressed: () => Navigator.of(context).push( + DistortionWaveRoute( + source: WaveSource.of(context), + builder: (context) => const ReceiptScreen(), + ), + ), + child: const Text('Send'), + ), + ), +) +``` + +```dart +DistortionWaveRoute({ + required WidgetBuilder builder, + WaveSource? source, + WaveType? type, + WavePalette? palette, + WaveStyle? style, + WaveSnapshots? snapshots, + bool maintainState = true, // PageRoute.maintainState + RouteSettings? settings, + bool fullscreenDialog = false, +}) +``` + +- A `PageRoute`, `opaque`, no barrier. The push plays the wave from `source` + into the new page; a pop collapses it back into the same source. +- **No anchor discovery.** The route opens from `source` or, when null, the + type's usual spot. Pass `WaveSource.of(context)` from the button that + pushes. +- **The page underneath** is pictured from its route's own page + `RepaintBoundary` (`toImageSync`) after the push's first frame, and again + after a pop starts; the wave bends that picture. Until the first picture + exists the outgoing side draws nothing, so the page underneath shows + through unchanged. `canTransitionFrom` is false: the page underneath plays + no exit transition of its own. In debug builds a page that still needs + paint is skipped (`debugNeedsPaint`); in release it is pictured as last + painted. +- **Durations:** `transitionDuration` is the spec's full reveal + (`WaveSpec.duration`), `reverseTransitionDuration` the collapse + (`duration / returnSpeed`); both 300 ms under reduced motion. The route's + animation runs linearly forward and on `timing.easing.flipped` in + reverse — the same timeline as `DistortionWave`. +- **Theme:** the look (`spec`) is resolved **once**, lazily, against + `DistortionWaveTheme.of(navigator.context)`. Put the theme above the + `Navigator` (around `MaterialApp`, or in its `builder`) for routes to see + it; a theme inside another page does not reach the route. +- The new page needs an opaque background, as a `DistortionWave` side does. +- `maintainState` here is `PageRoute.maintainState` (keep the route alive + when covered), not the widget's hidden-side switch. + +## `DistortionWaveController` + +```dart +final wave = DistortionWaveController(); // or DistortionWaveController(revealed: true) + +DistortionWave(controller: wave, revealedChild: receipt, child: review); + +wave.reveal(); // send it out (from `source:` if given, at rest) +wave.collapse(); // back into the source it opened from +wave.toggle(); // reveal or collapse by isRevealed +wave.seek(0.4); // hold at 0.4; stops any run +``` + +| Member | Behaviour | +| --- | --- | +| `DistortionWaveController({bool revealed = false})` | Starts resting on the first side, or the revealed side. | +| `reveal({WaveSource? source})` | Runs toward the revealed side. | +| `collapse({WaveSource? source})` | Runs back to the first side, into `source` if given and the wave is at rest, else into the source it opened from. | +| `toggle({WaveSource? source})` | `collapse` when `isRevealed`, else `reveal`. | +| `seek(double progress)` | Holds the wave at `progress` (clamped 0–1), stopping any run; `isRevealed` becomes `progress >= 0.5`. A later `reveal`/`collapse` continues from there. | +| `isRevealed` | On, or heading for, the revealed side. | +| `progress` | 0–1; without a wave attached, 0 or 1 by `isRevealed`. | +| `isRunning` | A run is in flight. | + +- Attached, it **owns playback**: `DistortionWave.revealed` is ignored. +- **One wave at a time** (asserted). Moving it to another wave and outliving + its wave are both fine; dispose it yourself. +- A `ChangeNotifier`: notifies on every `reveal` / `collapse` / `toggle` / + `seek` call, and when a run arrives. + +## Holding and scrubbing: `progress` + +`progress` is the wave's whole life on one 0–1 axis (anticipation, launch, +travel, lingering edges). Non-null holds the frame there; `WaveFrame.at` is a +pure function of it, so a held frame is deterministic (goldens use this). +Driving it from a gesture: + +```dart +GestureDetector( + onVerticalDragUpdate: (d) => setState(() { + // dragExtent: how far a drag travels for the whole wave, in px. + _held = ((_held ?? 0) - d.primaryDelta! / dragExtent).clamp(0.0, 1.0); + }), + onVerticalDragEnd: (_) => setState(() { + _revealed = (_held ?? 0) >= 0.5; // where to play on to + _held = null; // let go: plays on from the held point + }), + child: DistortionWave( + progress: _held, + revealed: _revealed, + revealedChild: next, + child: current, + ), +) +``` + +Picking a resting wave up with `progress` takes the run's source as a run +would (anchor rules included). + +## Timeline and durations + +A reveal runs linearly over its whole duration; the curve shaping the front's +travel is `WaveTiming.easing`, applied inside the timeline. A collapse runs +back on `WaveTiming.easing`, `returnSpeed` times faster, so it answers at +once (it is quick through the end of the wave's life, where little is on +screen). A partial run (flipped mid-way) takes its share of a full run's +time. `WaveSpec.duration` is the anticipation plus whichever part ends last: +the swell, the colour on the edges, the hairline, or the last dot. Under +reduced motion a full run takes 0.3 s and is a crossfade. + +## `WaveType` + +| Value | Front | Use | +| --- | --- | --- | +| `WaveType.vertical` (default) | Leaves a wide source (a bottom button) as its own outline and opens into an arc that bows up the view; leans with the touch. | Confirming a payment, sending, submitting. | +| `WaveType.horizontal` | The vertical wave on its side, from a tall source at the left; leans with the touch. Same tuned values as `vertical`. | An edge swipe, a side tab, going on to the next step. | +| `WaveType.center` | A ring spreading from the centre of a round source. The source is left alone — no pull, swell, blur or colour on it — so it can change in plain view. Its own tuning: shorter lengths (for a sheet or card rather than a full screen), `WavePalette.green`, no colour fringing, no colour or dots gathered before launch. | A success state on an avatar or icon, inside a sheet or card. | + +`type` also selects the defaults every unset style field falls back to. + +## Palettes: `WavePalette` + +```dart +DistortionWave(palette: WavePalette.ocean, ...); +DistortionWave(palette: WavePalette.single(const Color(0xFF35BA00)), ...); +DistortionWave(palette: WavePalette.fromBeamColors(BeamColors.aurora), ...); +DistortionWave( + palette: const WavePalette( + colors: [Color(0xFF6B2BFF), Color(0xFFF02BD9), Color(0xFF33A1FF)], + ahead: Color(0xFFFFB6F0), // fringe riding just ahead of the front + behind: Color(0xFF2B3BFF), // fringe trailing behind it + ), + ... +); +``` + +| API | Behaviour | +| --- | --- | +| `const WavePalette({required List colors, required Color ahead, required Color behind})` | `colors` flow along the front and round the edges, wrapping last → first. Only the first `maxWavePaletteColors` (8) are used; fewer are cycled to fill the shader's 8 slots; an empty list uses `ahead` alone. All colours are drawn opaque (alpha ignored). | +| `WavePalette.single(Color)` | One colour, with lightened and deepened neighbours; `ahead` lighter, `behind` deeper. Opaque. | +| `WavePalette.fromBeamColors(BeamColors)` | The beam palette's resolved stops (first 8) along the front; `ahead` is a lightened first stop, `behind` a deepened middle stop. Opaque. | +| Presets | `colorful` (default for `vertical` and `horizontal`), `green` (default for `center`), `ocean`, `sunset`, `mono`. | +| `WavePalette.presets` | `Map` of the five, in that order. | + +Colours are mixed in OKLab (`lib/src/core/oklab.dart`), so neighbouring hues +never pass through grey. Palettes are value-equal; `toString` names a preset. + +## Style: `WaveStyle` and its groups + +```dart +const WaveStyle({ + WaveType? type, + WavePalette? palette, + WaveTiming? timing, + WaveMotion? motion, + WaveLens? lens, + WaveGlow? glow, + WaveDots? dots, +}) +``` + +Every field of every group is nullable and means *inherit*. All are `const`, +value-equal, with `copyWith` (null keeps) and `merge` (the argument's +non-null fields win; `WaveStyle.merge` merges the groups field by field, so +`WaveStyle(lens: WaveLens(blur: 0))` over a theme changes only the blur). + +**Precedence**, per field: + +```text +widget shorthand (type:, palette:) > widget style > DistortionWaveTheme (inner over outer) > waveDefaults(type) +``` + +The type is settled first (from the widget and theme, else `vertical`), and +that type's tuned style fills every remaining field. The settled result is +the internal `WaveSpec` (`models/wave_spec.dart`): seconds and logical +pixels, value-equal, so a rebuild with an equal style changes nothing. + +**Validation.** In debug builds the constructors assert the bounded ranges +they document: the 0–1 and 0–2 fields, `blur`, `returnSpeed` and dot +`count`. The minimums on lengths (the "At least" entries below, such as +`lead`, `tail`, `rimWidth` and `rimSoftness`) are not asserted: a smaller +value is raised to the minimum. `WaveSpec` settles every value this way in +every build mode, so release builds stay safe too: a NaN becomes the field's +floor, out-of-range values are clamped (lengths to their minimums, 0–1 +fields to 0–1, `blur` to 0–64, `returnSpeed` to 0.01–100, dot `count` to +0–256), and a non-finite `pull`, `inhale`, `amplitude` or `swell` becomes 0. + +### `WaveTiming` — the wave's life + +| Field | Type | Meaning | +| --- | --- | --- | +| `anticipation` | `Duration?` | Pull toward the source before the wave leaves it. | +| `travel` | `Duration?` | From leaving the source to the front having settled past the far side. | +| `easing` | `Curve?` | How the front covers its way over `travel` (default leaves at full speed, settles softly); also the collapse's curve. | +| `returnSpeed` | `double?` | How much faster the collapse runs than the reveal. Asserted > 0 and ≤ 100. | +| `linger` | `Duration?` | After launch, when the wipe of the edge colour starts. Negative starts it before launch, so the wipe follows close behind the front. | +| `rimFade` | `Duration?` | How long the wipe of the edge colour takes. | +| `rimEasing` | `Curve?` | The wipe's curve (default ease-in-out). | +| `hairlineLinger` | `Duration?` | How long the hairline holds on after the colour starts to go. | +| `hairlineFade` | `Duration?` | How long the hairline's wipe takes. | + +### `WaveMotion` — before the launch, and the lean + +| Field | Type | Meaning | +| --- | --- | --- | +| `pull` | `double?` pt | How far the anticipation pulls content toward the source. | +| `inhale` | `double?` pt | How far out the ring of colour that falls onto the source starts. | +| `gatherGlow` | `double?` 0–2 | Colour gathered through the anticipation: 1 = half the front's colour by launch, 2 = all, 0 = none. | +| `gatherDots` | `double?` 0–1 | Visibility of dots hopping toward the source before launch; 0 leaves only the dots that fly out with the front. | +| `launchGap` | `double?` pt | How far out from the source's outline the front starts; 0 = from the source itself. | +| `orientation` | `double?` 0–1 | Lean toward the touch: 0 opens evenly from the whole source, 1 from under the finger. `center` never leans. | + +### `WaveLens` — the bend and the blur + +| Field | Type | Meaning | +| --- | --- | --- | +| `amplitude` | `double?` pt | How far the swell lifts content as it passes. | +| `width` | `double?` pt | Width of the swell. | +| `aberration` | `double?` | Colour fringing: how far red and blue part, as a share of how far content moved. 0 turns it off. | +| `swell` | `double?` pt | How far the front bends along its length. | +| `blur` | `double?` pt, 0–64 | Blur radius on the front; 0 turns the blur off (and skips the blurred copies). | +| `blurAhead` | `double?` pt | Distance ahead of the front over which the blur gathers. | +| `blurBehind` | `double?` pt | Distance behind the front over which the blur clears. | + +### `WaveGlow` — colour on the front and the edges + +| Field | Type | Meaning | +| --- | --- | --- | +| `lead` | `double?` pt | How far the colour feathers ahead of the front. At least 1. | +| `tail` | `double?` pt | Length of the colour trailing behind the front. At least 1. | +| `strength` | `double?` 0–1 | Peak opacity of the band on the front; 0 hides it. | +| `rimWidth` | `double?` pt | How far in from the view's edges the lingering colour reaches. At least 0.5. | +| `rimUnevenness` | `double?` 0–2 | 0 = even thickness all round; 1 = drifting lumps with thin stretches; past 1 the thinnest stretches break off. | +| `rimStrength` | `double?` 0–1 | Peak opacity of the edge colour; 0 leaves none behind. | +| `rimSoftness` | `double?` pt | How softly the edge colour is wiped away. At least 1. | +| `rimPulse` | `double?` 0–1 | How alive the edge colour is (lumps drift and breathe, brightness runs round, colours flow); 0 keeps a slow drift. | +| `hairlineWidth` | `double?` pt | Width of a hairline on the view's edge, over the colour; 0 draws none. | +| `hairlineOpacity` | `double?` 0–1 | Peak opacity of the hairline. | +| `hairlineWhite` | `double?` 0–1 | How far the hairline whitens where the pulse's light runs. | +| `cornerRadius` | `double?` pt | Corner radius of the view the wave fills; the edge colour and hairline follow it (rounded superellipse corners). Setting it anywhere (widget or theme) opts out of the display's corners. | + +### `WaveDots` — the sparks + +| Field | Type | Meaning | +| --- | --- | --- | +| `count` | `int?` 0–`WaveDots.maxWaveDots` (256) | How many dots; 0 draws none. | +| `size` | `double?` pt | Diameter of the largest dot. | +| `reach` | `double?` pt | How far from the source the farthest dot is born in the anticipation. | +| `flight` | `double?` pt | How far a dot flies toward the source in one hop. | +| `gap` | `double?` pt | How close to the source a dot comes before it has faded. | +| `life` | `Duration?` | After launch, when the last dot has faded. | +| `spread` | `double?` 0–1 | How far the dots are thrown, as a share of the front's way: 1 lets the quickest ride off the view. | + +## Display corners + +A wave that **fills the view** puts its edge colour and hairline on the +display's own corners, each corner its own radius, read from +`MediaQuery.displayCornerRadii` (via `MediaQuery.maybeDisplayCornerRadiiOf`). +"Fills the view" means the wave's top-left is at the global origin and its +size equals `MediaQuery.sizeOf` (both within half a pixel). Otherwise — a +wave in a sheet or a card, or a platform that reports no radii — the edges +use `WaveGlow.cornerRadius` (the type's default when unset) on all four +corners. + +- Android reports display corners to Flutter. iOS does not: an app supplies + them with `MediaQueryData.applyDisplayCornerRadii` + (`example/lib/src/display_corners.dart` measures them through a method + channel and re-measures on rotation). +- Setting `WaveGlow.cornerRadius` on the widget's style or any + `DistortionWaveTheme` style turns display corners off for that wave. For a + route, only the route's `style` and the theme count. + +## Theme: `DistortionWaveTheme` + +```dart +DistortionWaveTheme( + data: const DistortionWaveThemeData( + style: WaveStyle(palette: WavePalette.ocean, lens: WaveLens(aberration: 0)), + snapshots: WaveSnapshots.onChange, + ), + child: MaterialApp(home: home), // above the Navigator, so routes see it too +) +``` + +- `DistortionWaveThemeData({WaveStyle? style, WaveSnapshots? snapshots})`, + value-equal, `copyWith`, `merge` (style merges field by field; snapshots: + the argument's wins when set). +- `DistortionWaveTheme.of(context)` merges **every** enclosing theme outer to + inner and depends on each (empty data when there is none); + `maybeOf(context)` returns null when there is none. +- Applies to every `DistortionWave` below it, and to `DistortionWaveRoute`s + pushed on a `Navigator` below it (resolved once per route). + +## Snapshots: `WaveSnapshots` + +While the wave bends content it draws both sides from GPU pictures of them. + +| Value | A side is pictured again… | Use when | +| --- | --- | --- | +| `WaveSnapshots.onChange` (default) | when content under it repaints — a repaint that travels up through the side to the stage. | Almost always. | +| `WaveSnapshots.everyFrame` | on every frame the wave bends it. | Content inside a nested `RepaintBoundary` (a list item, a spinner wrapped in one, a video) must keep moving through the wave: such repaints stop at their boundary, so under `onChange` that content holds still while it is bent. | + +Each new picture is one offscreen rasterisation of the side, plus two small +blurred copies baked with `ImageFilter.blur` once the frame has blur to +show. `everyFrame` pays that every frame for each side shown. Exact costs: +[performance.md](performance.md#distortionwave). + +## Fallbacks + +| Situation | What the wave does | +| --- | --- | +| Reduced motion (`MediaQuery.disableAnimations`) | A plain crossfade, the outgoing side fading over the incoming one; a full run takes 0.3 s. Routes too. | +| A side holding a platform view (map, web view) | It cannot be pictured (`OffsetLayer.supportsRasterization()` is false): that run crossfades. The next run from rest tries the wave again. | +| A `DistortionWaveRoute` over a page holding a platform view | The page underneath cannot be pictured: the new page fades in over it, and out on pop. | +| Shaders still loading | The side the wave is on is shown plainly until they load. | +| A source that cannot be measured | The type's usual spot. | + +## Recipes + +**Success ring on an avatar inside a sheet:** + +```dart +DistortionWave( + type: WaveType.center, + style: const WaveStyle(glow: WaveGlow(cornerRadius: 28)), // the sheet's corners + revealed: done, + revealedChild: const DoneSheet(), + child: PendingSheet(avatar: DistortionWaveAnchor(child: avatar)), +) +``` + +**One-shot, then back:** use `onFinish` to collapse after a reveal arrives, +or drive both from a controller: + +```dart +controller.reveal(); +// later +controller.collapse(); +``` + +**Brand palette from the beam's colours:** +`WavePalette.fromBeamColors(BeamColors.fromSeed(brand))`. + +**No fringing, no blur, no dots:** +`WaveStyle(lens: WaveLens(aberration: 0, blur: 0), dots: WaveDots(count: 0))`. + +## Pitfalls + +- **A black or empty area while the wave runs** — a side (or the route's new + page) has a transparent background. Give it an opaque one. +- **Part of the screen holds still while the wave passes** — it sits in a + nested `RepaintBoundary`. Use `snapshots: WaveSnapshots.everyFrame`. +- **The wave opens from the wrong place** — the source is read only at the + start of a run from rest; with several anchors on one side, only a pressed + or focused one is picked. Pass `source:` (or `controller.reveal(source:)`) + explicitly when in doubt. +- **A route ignores the theme** — the theme is below the `Navigator`. Move it + above. +- **The edge colour misses the screen's corners on iOS** — iOS does not + report display corners; supply them with + `MediaQueryData.applyDisplayCornerRadii`, or set `WaveGlow.cornerRadius`. +- **`revealed` does nothing** — a controller is attached; it owns playback. +- **Two waves, one controller** — asserts. One controller per wave. + +## Testing a wave + +- `setUpAll(DistortionWave.precache)` before anything that reads pixels or + counts draws; before the shaders load, a wave shows its sides plainly. +- Hold frames with `progress:` for goldens and pixel checks (see + `test/distortion_wave/golden/wave_golden_test.dart`). +- Reduced motion: wrap in `MediaQuery(data: …copyWith(disableAnimations: true))`. +- Helpers: `test/distortion_wave/widget/wave_test_utils.dart`. Lifecycle and + route tests run under `leak_tracker_flutter_testing` + (`LeakTesting.enable()`): dispose every controller a test creates + (`addTearDown(controller.dispose)`). diff --git a/doc/effects.md b/doc/effects.md index b5189c4..fb4cf9e 100644 --- a/doc/effects.md +++ b/doc/effects.md @@ -24,13 +24,13 @@ All three are drawn by the same shader in the same single draw call, so they cos ## 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 | +| Effect | Family | `cycleGap` | `hueMode` | +| --- | --- | --- | --- | +| `rotate` | travelling | zero | `pingPong` | +| `line` | travelling | zero | `pingPong` (on a shorter period than `rotate`) | +| `pulse` | ambient | — (ignored) | `continuous` | -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's default `cycle` and `huePeriod` are getters on its class in `lib/src/border_beam/effects/beam_effect.dart` — `BeamEffect.defaultCycle`, `defaultCycleGap`, `defaultHueMode`, `defaultHuePeriod` — read them there rather than hard-coding them. Every one is a fallback: `BeamTiming` and `BeamStyle` override them field by field. Each effect is also tuned twice — once for dark surfaces and once for light ones — and `BeamStyle.theme` picks which (see [theming](theming.md)). @@ -51,7 +51,7 @@ BorderBeam( | `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()`. +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 whose shortest side is at most `compactMaxExtent` (`lib/src/border_beam/look/rotate_look.dart`; chip and pill-button sized) 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. @@ -83,7 +83,7 @@ Patches of colour on the hairline and washing inward from the edges, each swelli 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. +Its colours rotate continuously by default (a full turn per `huePeriod`). With a segment, only the patches inside it breathe. ## Choosing at runtime diff --git a/doc/motion.md b/doc/motion.md index c14bbcb..0be8ec8 100644 --- a/doc/motion.md +++ b/doc/motion.md @@ -1,6 +1,6 @@ # Motion -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. +Timing, direction, rest, synchronization, and taking the travel off the clock. The [`BeamTiming` table](border_beam_usage.md#beamtiming) lists the fields and defaults; this guide is about how they interact. Code: `lib/src/border_beam/animation/` (`beam_clock.dart`, `beam_phases.dart`, `spring_curve.dart`). ## The clock @@ -10,7 +10,7 @@ The clock ticks on every frame the engine produces. Nothing is capped, so a beam `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. +`speed` moves the animation only. The fades and the controller's `pulse()` / `flash()` accents run on real time, so a beam at half speed fades in exactly as fast as one at full speed, and seeking or retiming never stretches, skips, or replays a fade. Pausing — the controller's `pause()`, an offscreen pause — freezes both. ## Cycle and retiming @@ -31,7 +31,7 @@ BorderBeam( 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`). +The fades run on critically damped springs — Apple's `.smooth` — so the light eases in from rest and settles without overshoot, with a slightly longer, gentler response on the way out so it leaves softly rather than cutting off (`BeamSpringCurve.fadeIn` / `fadeOut` in `spring_curve.dart`; `BeamClock.fadeInSeconds` / `fadeOutSeconds` are their settling times). 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 @@ -44,7 +44,7 @@ BorderBeam( ); ``` -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. +The sweep still takes `cycle`; the gap is added after it. The beam fades out and back in over a short envelope at each end of the rest — never more than half the gap (`BeamPhaseResolver` in `beam_phases.dart`) — so it reads as breathing rather than blinking off. The hue drift keeps running through the gap. 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. @@ -92,8 +92,8 @@ The hue is a separate track from the travel, on its own period (`huePeriod`): | `hueMode` | What it does | Default for | | --- | --- | --- | -| `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) | +| `pingPong` | Swings ±`hueShift` degrees (30 by default) and back, eased at each end. | `rotate`, `line` | +| `continuous` | Turns a full 360° per period, never reversing. | `pulse` | | `none` | No drift. | — (`mono` and `gold` force it) | `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)). @@ -167,7 +167,7 @@ Widget build(BuildContext context) { } ``` -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`. +The travel leaves its schedule and eases toward the given normalized point — critically damped and quick, 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 ambient effects ignore both. A NaN `progress` or a non-finite `follow` counts as unset. `BeamHover` is this wired up for you. @@ -186,4 +186,4 @@ Values of `strengthListenable` above 1 brighten the beam, saturating at full opa ### 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. +A `BorderBeamController` adds two one-shot accents on a running beam: `pulse()` lifts its brightness and lets it settle, and `flash()` blinks it brighter, holds briefly, and decays. `pulse()` rises on `BeamSpringCurve.pop`; `flash()` has no rise and starts at its peak. Neither touches the timeline, both run on real time, and both are no-ops while the beam is hidden or frozen. diff --git a/doc/palettes.md b/doc/palettes.md index 4266c80..e312aa8 100644 --- a/doc/palettes.md +++ b/doc/palettes.md @@ -1,5 +1,7 @@ # Palettes +`BeamColors` (`lib/src/border_beam/models/beam_colors.dart`) for `BorderBeam`. The wave's palettes are `WavePalette` — see [distortion_wave_usage.md](distortion_wave_usage.md#palettes-wavepalette); `WavePalette.fromBeamColors` converts one into the other. + 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. Effects draw a palette as soft blobs of colour placed around the border — the same blob tables the original design was tuned with: @@ -36,7 +38,7 @@ How the colours are shown depends on the effect: | `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. +`BeamColors.presets` is a `Map` of all 19, in this order — handy for a picker. The presets' stops live in `lib/src/border_beam/models/beam_presets.dart` and their blob tables in `lib/src/border_beam/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. @@ -82,7 +84,7 @@ Colours blend **gamma-aware**: squared channels (close to linear light) are inte | `triadic` | 0°, +120°, +240° | three-way, evenly spaced | | `monochrome` | one hue, four lightness steps | a single-hue brand look | -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. +The derived colours are lifted into a lightness band a glow reads well in, with a saturation floor (`_seedMinLightness`, `_seedMaxLightness`, `_seedMinSaturation` in `models/beam_colors.dart`), 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 const BeamColors.fromSeed(Color(0xFF18A8F0), harmony: BeamSeedHarmony.complementary); diff --git a/doc/performance.md b/doc/performance.md index ac60926..e36f372 100644 --- a/doc/performance.md +++ b/doc/performance.md @@ -1,12 +1,14 @@ # Performance +What a frame of each effect costs, what the widgets do to keep it cheap, and what an app can do wrong. The sections up to [Getting a scene cheaper](#getting-a-scene-cheaper) cover `BorderBeam`; [DistortionWave](#distortionwave) covers the wave. + 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 a frame costs **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. -`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. +`test/border_beam/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. **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. @@ -83,6 +85,73 @@ To fade a beam, use `style.strength` (static), `strengthListenable` (per frame, 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). +## DistortionWave + +Code: `lib/src/distortion_wave/render/render_wave_stage.dart`, +`render/wave_snapshot.dart`, `render/dot_atlas.dart`. Internals: +[distortion_wave.md](distortion_wave.md). + +### What a frame costs, by phase + +| Phase | On the stage's canvas | Offscreen work | +| --- | --- | --- | +| `rest` (progress 0 or 1) | the visible side, painted as itself | none; no ticker runs; pictures released | +| `distorting` (the wave bends content) | one `drawRect` with `wave.frag`, plus at most one `drawRawAtlas` for the dots | a side's pictures, only when (re)taken — below | +| `glowing` (front crossed, only colour on the edges) | the revealed side as itself, one `drawRect` with `wave_glow.frag` (none once the colour is gone), at most one `drawRawAtlas` | none; pictures released | +| `crossfading` (reduced motion, or a side holding a platform view) | both sides, the outgoing one in a `pushOpacity` layer | the opacity layer's offscreen pass | + +The stage's own drawing never adds a `saveLayer`, clip, `ImageFilter`, +`BackdropFilter`, `MaskFilter`, `drawImage` or `drawImageRect` in the first +three phases. The one image the stage does draw is the dots' sprite, in +the at most one `drawRawAtlas` above. +`test/distortion_wave/render/wave_frame_budget_test.dart` asserts this per +phase × type, and pins how many pictures each side gets. + +Per frame on the CPU: `WaveFrame.at` (pure arithmetic), the rim's lumps, +the visible dots' positions, and an upload of `waveUniformFloats` (124) +floats into a `FragmentShader` the stage keeps. The spec's uniforms are +written only when the spec or the corners change; the stage's — its rect, +pixel size and outline — are written every frame, with the frame's own. + +### What a picture costs + +Taking a picture of a side (`WaveSideImages.take`) is one offscreen render +of the side's layer tree at the device pixel ratio (`OffsetLayer.toImageSync`). +The first frame of a picture that has blur to show (blur energy above 0 and +`WaveLens.blur` above 0) also bakes two blurred copies, each a +`drawImageRect` through `ImageFilter.blur` into a `Picture` rasterised with +`toImageSync`: a near copy at one pixel per logical pixel and a far copy at +half that. With `WaveLens.blur: 0` no copies are baked. + +| `WaveSnapshots` | Pictures per run | +| --- | --- | +| `onChange` (default) | The outgoing side once, on the first `distorting` frame; the incoming side once, when the front launches. Again only when content repaints through the side (an animation inside it that is not behind its own `RepaintBoundary`). Each picture: 1 render + up to 2 blur bakes. | +| `everyFrame` | Every `distorting` frame, for each side shown: 1 render + up to 2 blur bakes each — up to 6 offscreen renders a frame while both sides show. Use it only when content behind a nested `RepaintBoundary` must keep moving through the wave. | + +Pictures are GPU images the size of the stage (the blurred copies smaller), +held only while the phase is `distorting`: released at rest, in the glowing +and crossfading phases, when a side stops showing, when the device pixel +ratio changes, and when the stage is detached or disposed. + +`DistortionWaveRoute` adds one more picture: the page underneath, rasterised +from its route's `RepaintBoundary` once after the push's first frame and +once as a pop starts, held by the route until it is replaced or the route is +disposed. + +### Keeping it cheap + +- `await DistortionWave.precache()` at startup: it loads both programs and + draws both shaders, a blur bake and an atlas into a 4 × 4 image, so the + pipelines exist before the first wave's first frame. +- Keep `snapshots: WaveSnapshots.onChange` unless something visibly freezes. +- An animation inside a side that repaints through it re-pictures that side + on each of its frames while the wave bends it; pause decorative animations + in a side for the second or so the wave runs, or put them behind a + `RepaintBoundary` (they then hold still while bent). +- A platform view in a side cannot be pictured; that run is a crossfade. A + `DistortionWaveRoute` over a page showing one fades the new page in and + out instead of bending the page underneath. + ## Web -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. +The package compiles and runs on web — the [live demo](https://simplifyjobs.github.io/prismatic/) is a web build of the example app, and CI builds it on every commit. The beam is the same single shader draw there; the wave's shaders are SkSL strict ES2 so they run on Skia and the web as well as Impeller. diff --git a/example/README.md b/example/README.md index 73474cc..409596f 100644 --- a/example/README.md +++ b/example/README.md @@ -1,70 +1,115 @@ -# flutter_border_beam example +# prismatic examples + +## A beam around a card + +```dart +BorderBeam( + borderRadius: 16, + colors: BeamColors.ocean, + child: const Card(child: Padding( + padding: EdgeInsets.all(24), + child: Text('Working on it…'), + )), +) +``` -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. +Pick another effect with `effect: const BeamEffect.line()` or +`const BeamEffect.pulse()`. + +## A wave from a button + +Flip `revealed` to send the wave out. Flip it back to bring it home. + +```dart +DistortionWave( + revealed: sent, + revealedChild: const ReceiptScreen(), + child: ReviewScreen( + send: DistortionWaveAnchor( + child: FilledButton( + onPressed: () => setState(() => sent = true), + child: const Text('Send'), + ), + ), + ), +) +``` -```bash -flutter run # phone / desktop -flutter run -d chrome +Give both screens an opaque background. + +## A wave between pages + +```dart +Navigator.of(context).push( + DistortionWaveRoute( + source: WaveSource.of(context), + builder: (_) => const ReceiptScreen(), + ), +); ``` -`main()` awaits `BorderBeam.precache()` after -`WidgetsFlutterBinding.ensureInitialized()`, so the shader is loaded before the -first frame. +## Load the shaders early -## What it shows +```dart +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await BorderBeam.precache(); + await DistortionWave.precache(); + runApp(const App()); +} +``` -Swipe the stage, or tap the selector under it, to move between the effects: +## The showcase app -| Effect | Surface | -| --- | --- | -| `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: +This folder is a full app that shows both effects. + +```bash +flutter run # a phone or desktop +flutter run -d chrome # the web +``` + +- **Home** shows each beam effect on the widget it suits: `rotate` on a task + card, `line` on a chat composer, and `pulse` on a "thinking" card. Swipe + between them, pick a palette, pause the beam, or flip the theme. +- **The wave button** in the header opens the wave page, on a + `DistortionWaveRoute`. Each wave type has its own demo screen: + - **Send money** (`vertical`): Send reveals the receipt. + - **Next step** (`horizontal`): the tab on the left edge goes on. + - **Success sheet** (`center`): the icon turns the sheet into its paid + state. +- On a phone the send and step demos fill the screen, so the wave follows + your display's corners; the success sheet sits at the bottom. The tab on the right edge slides in the options: the demo, its + palette, a bar that holds the wave at any moment, and a page pushed on a + route. On a wide screen the options sit in a side bar. + +Three `--dart-define`s set the opening state, which helps with screenshots: ```bash flutter run --dart-define=START=pulse --dart-define=PALETTE=ocean --dart-define=THEME=light ``` -## Layout +### Where things are | 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` | +| `lib/main.dart` | `main()` and the app | +| `lib/src/home.dart` | the beam screen | +| `lib/src/surfaces.dart` | the mock widgets the beams wrap | +| `lib/src/wave_page.dart` | the wave screen, and the page its route pushes | +| `lib/src/wave_scenes.dart` | the wave demos, shared with the reel | +| `lib/src/display_corners.dart` | the display's corner radii on iOS | +| `lib/src/controls.dart` | selectors, swatches, toggles and the scrub bar | +| `lib/src/tokens.dart` | dark and light colour tokens | -## Demo reels +### Demo reels -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`: +`lib/showcase.dart` (the beams) and `lib/wave_reel.dart` (the waves) play +themselves for recording. From the package root, with a booted iOS simulator +and ffmpeg: ```bash -# from the package root, with a booted iOS simulator and ffmpeg installed tool/record_demo.sh --target lib/showcase.dart --prefix SHOWCASE --contact +tool/record_demo.sh --target lib/wave_reel.dart --prefix WAVE --no-crop --contact ``` -Output mp4s land in `.demos/` (gitignored), centre-cropped at 60fps, with an -optional contact-sheet PNG for review. +Videos land in `.demos/`. diff --git a/example/android/app/build.gradle.kts b/example/android/app/build.gradle.kts index 08743e3..ddb3da5 100644 --- a/example/android/app/build.gradle.kts +++ b/example/android/app/build.gradle.kts @@ -5,7 +5,7 @@ plugins { } android { - namespace = "com.example.border_beam_example" + namespace = "com.example.prismatic_example" compileSdk = flutter.compileSdkVersion ndkVersion = flutter.ndkVersion @@ -16,7 +16,7 @@ android { defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId = "com.example.border_beam_example" + applicationId = "com.example.prismatic_example" // You can update the following values to match your application needs. // For more information, see: https://flutter.dev/to/review-gradle-config. minSdk = flutter.minSdkVersion diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml index 917db86..3e27ecd 100644 --- a/example/android/app/src/main/AndroidManifest.xml +++ b/example/android/app/src/main/AndroidManifest.xml @@ -1,6 +1,6 @@