mirror of
https://github.com/kuhyx/todo-app.git
synced 2026-11-24 15:26:28 +01:00
Compare commits
11 Commits
2c97a9c19c
...
4e66de5467
| Author | SHA1 | Date | |
|---|---|---|---|
| 4e66de5467 | |||
| 34b2c1c87c | |||
| 5856617cbf | |||
| 25e2c9bb20 | |||
| 95c358cb5c | |||
| 10a546f6d6 | |||
| d145f92a07 | |||
| 381afd1d77 | |||
| d4c8162e0e | |||
| 63725e726f | |||
| 9d2aa1c178 |
33
.github/workflows/file-length.yml
vendored
Normal file
33
.github/workflows/file-length.yml
vendored
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
name: file-length
|
||||||
|
|
||||||
|
# The 250-line cap, enforced on push as well as at commit time. The local
|
||||||
|
# pre-commit hook can be skipped (a fresh clone that never ran
|
||||||
|
# scripts/install_hooks.sh has no hooks at all), so the cap needs a second
|
||||||
|
# gate that no one can forget to install.
|
||||||
|
#
|
||||||
|
# Deliberately a SEPARATE workflow from release-apk.yml: a file that grew too
|
||||||
|
# long should fail lint, not block publishing an APK.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
file-length:
|
||||||
|
name: file length <= 250 lines
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# The gate and its exemption list live in the shared utils repo so every
|
||||||
|
# repo enforces the same cap. Checking it out beats vendoring a copy
|
||||||
|
# here, which is exactly how a gate and a survey start disagreeing.
|
||||||
|
- name: Check out the shared gate
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
repository: kuhyx/utils
|
||||||
|
path: .utils
|
||||||
|
|
||||||
|
- name: Enforce the cap
|
||||||
|
run: bash .utils/scripts/check_file_length.sh --all
|
||||||
52
.pre-commit-config.yaml
Normal file
52
.pre-commit-config.yaml
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
# Pre-commit hooks for todo.
|
||||||
|
#
|
||||||
|
# This repo previously used a hand-written .git/hooks/pre-commit installed by
|
||||||
|
# scripts/install_hooks.sh. It moved to the pre-commit framework when the
|
||||||
|
# 250-line file-length gate was added, so the *checks* live in one place with
|
||||||
|
# one install path.
|
||||||
|
#
|
||||||
|
# Only non-mutating checks belong here. pre-commit stashes unstaged changes
|
||||||
|
# for the duration of the run and restores them with `git apply` afterwards;
|
||||||
|
# a hook that rewrites a tracked file inside that window makes the restore
|
||||||
|
# conflict, which aborts the commit AND drops the developer's uncommitted
|
||||||
|
# edit. scripts/bump_patch_version.sh rewrites pubspec.yaml, so it stays out
|
||||||
|
# of this file and runs from the wrapper hook instead -- see
|
||||||
|
# scripts/install_hooks.sh.
|
||||||
|
#
|
||||||
|
# fail_fast so a later check cannot run after an earlier one has already
|
||||||
|
# rejected the commit.
|
||||||
|
#
|
||||||
|
# Install with: scripts/install_hooks.sh
|
||||||
|
# The hooks are `language: system` because they are plain bash/python already
|
||||||
|
# on this machine; pre-commit must not build an isolated env for them.
|
||||||
|
fail_fast: true
|
||||||
|
repos:
|
||||||
|
- repo: local
|
||||||
|
hooks:
|
||||||
|
# Gate first: a local crdt_sync override left in place makes CI build a
|
||||||
|
# library this checkout has never tested against, silently and in both
|
||||||
|
# directions. Blocking the commit is the only thing that prevents it.
|
||||||
|
#
|
||||||
|
# always_run/pass_filenames rather than `files:`: a poisoned pubspec can
|
||||||
|
# arrive by pull, merge or --no-verify, and a staged-only trigger would
|
||||||
|
# then never look at it again for any commit that does not happen to
|
||||||
|
# touch pubspec.yaml. The old hand-written hook checked it every time;
|
||||||
|
# narrowing that to staged-only silently widened the hole this gate
|
||||||
|
# exists to close.
|
||||||
|
- id: no-crdt-sync-override
|
||||||
|
name: no local crdt_sync dependency_override
|
||||||
|
entry: scripts/check_no_crdt_sync_override.sh
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
always_run: true
|
||||||
|
|
||||||
|
# The shared 250-line cap. Checks only the files in the commit, so an
|
||||||
|
# unrelated commit never breaks; exits 1 rather than warning. No
|
||||||
|
# baseline and no allowlist -- those are suppressions. The exemption
|
||||||
|
# list (generated/vendored/data files) lives with the checker in
|
||||||
|
# ~/utils/file_length/config.py so the gate and the survey cannot
|
||||||
|
# disagree.
|
||||||
|
- id: file-length
|
||||||
|
name: file length <= 250 lines
|
||||||
|
entry: scripts/check_file_length.sh
|
||||||
|
language: system
|
||||||
827
CLAUDE.md
827
CLAUDE.md
@ -26,7 +26,7 @@ and sync peer-to-peer through a GitHub repo used as dumb storage.
|
|||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
- Run tests + coverage: `flutter test --coverage` (suite runs in 1–2min; keep it
|
- Run tests + coverage: `flutter test --coverage` (suite runs in under a minute; keep it
|
||||||
quick — see Testing below).
|
quick — see Testing below).
|
||||||
- Coverage summary: `lcov --list coverage/lcov.info`.
|
- Coverage summary: `lcov --list coverage/lcov.info`.
|
||||||
- Static analysis: `flutter analyze` (must be clean before committing).
|
- Static analysis: `flutter analyze` (must be clean before committing).
|
||||||
@ -100,8 +100,9 @@ migrate → Settings → Import).
|
|||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
- **The suite must stay quick and fully green.** It is currently **238 tests at
|
- **The suite must stay quick and fully green.** It is currently **313 tests at
|
||||||
100% line coverage**, running in 1–2min on this machine. Don't regress either.
|
100% line coverage** (2005 lines), running well under a minute on this
|
||||||
|
machine. Don't regress either.
|
||||||
(The "~5s" figure this file used to quote had drifted well before the port
|
(The "~5s" figure this file used to quote had drifted well before the port
|
||||||
guard was added; measure before quoting a new one.)
|
guard was added; measure before quoting a new one.)
|
||||||
- Widget tests use `test/fake_note_repository.dart` — a `FakeNoteRepository`
|
- Widget tests use `test/fake_note_repository.dart` — a `FakeNoteRepository`
|
||||||
@ -133,793 +134,39 @@ migrate → Settings → Import).
|
|||||||
- Run `dart format` + `flutter analyze` (clean) before every commit.
|
- Run `dart format` + `flutter analyze` (clean) before every commit.
|
||||||
- Comments explain intent/trade-offs, not syntax.
|
- Comments explain intent/trade-offs, not syntax.
|
||||||
- Keep the app buttery-smooth and low on CPU/RAM — it's a quick-capture tool.
|
- Keep the app buttery-smooth and low on CPU/RAM — it's a quick-capture tool.
|
||||||
|
- **Every file is at most 250 lines**, source and prose alike. Enforced by a
|
||||||
|
pre-commit hook (`scripts/check_file_length.sh`, delegating to the shared
|
||||||
|
gate in `~/utils`) and by `.github/workflows/file-length.yml`, so it fails
|
||||||
|
the commit rather than being a note anyone can ignore. Install the hook on
|
||||||
|
a fresh clone with `scripts/install_hooks.sh`.
|
||||||
|
- **Only non-mutating checks go in `.pre-commit-config.yaml`.** pre-commit
|
||||||
|
stashes unstaged changes and restores them with `git apply`; a hook that
|
||||||
|
rewrites a tracked file inside that window makes the restore conflict,
|
||||||
|
which aborts the commit *and drops the developer's uncommitted edit*. That
|
||||||
|
is why `bump_patch_version.sh` runs from the wrapper hook that
|
||||||
|
`install_hooks.sh` writes, after pre-commit has exited and only when it
|
||||||
|
passed — see the comments in both files. There is deliberately no
|
||||||
|
baseline and no allowlist — split the file instead. Exemptions (generated,
|
||||||
|
vendored, data files) live with the checker so the gate and the survey
|
||||||
|
cannot disagree.
|
||||||
|
- Where a split would otherwise break callers, keep the original path as a
|
||||||
|
barrel that re-exports the parts (`note_template.dart`,
|
||||||
|
`firebase_backend.dart`, `note_repository.dart` all do this). Where a
|
||||||
|
widget and its private `State` must stay one library, use `part` files
|
||||||
|
(`note_editor_*.dart`, `capture_screen_*.dart`).
|
||||||
|
|
||||||
## Flutter/Dart AI rules
|
## Flutter/Dart AI rules
|
||||||
|
|
||||||
_Appended from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md) via `/home/kuhy/.claude/CLAUDE.md` Flutter AI tooling setup. Re-fetch periodically to stay current._
|
Upstream's Flutter/Dart guidance used to be pasted in below this line, which
|
||||||
|
made 85% of this always-loaded file a document nobody edits. It now lives in
|
||||||
## AI rules for Flutter
|
`docs/`, linked rather than inlined so the part loaded on every turn stays
|
||||||
|
about *this repo*:
|
||||||
You are an expert in Flutter and Dart development. Your goal is to build
|
|
||||||
beautiful, performant, and maintainable applications following modern best
|
- [Language, style and architecture](docs/flutter-rules-language.md)
|
||||||
practices. You have expert experience with application writing, testing, and
|
- [State, routing and data](docs/flutter-rules-state-and-data.md)
|
||||||
running Flutter applications for various platforms, including desktop, web, and
|
- [Code generation, testing, theming and assets](docs/flutter-rules-testing-and-assets.md)
|
||||||
mobile platforms.
|
- [UI: theming, layout and overlays](docs/flutter-rules-ui.md)
|
||||||
|
- [Colour, type, documentation and accessibility](docs/flutter-rules-design.md)
|
||||||
### Interaction Guidelines
|
|
||||||
* **User Persona:** Assume the user is familiar with programming concepts but
|
Sourced from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
||||||
may be new to Dart.
|
via `~/.claude/CLAUDE.md`'s Flutter AI tooling setup. Re-fetch periodically.
|
||||||
* **Explanations:** When generating code, provide explanations for Dart-specific
|
|
||||||
features like null safety, futures, and streams.
|
|
||||||
* **Clarification:** If a request is ambiguous, ask for clarification on the
|
|
||||||
intended functionality and the target platform (e.g., command-line, web,
|
|
||||||
server).
|
|
||||||
* **Dependencies:** When suggesting new dependencies from `pub.dev`, explain
|
|
||||||
their benefits.
|
|
||||||
* **Formatting:** Use the `dart_format` tool to ensure consistent code
|
|
||||||
formatting.
|
|
||||||
* **Fixes:** Use the `dart_fix` tool to automatically fix many common errors,
|
|
||||||
and to help code conform to configured analysis options.
|
|
||||||
* **Linting:** Use the Dart linter with a recommended set of rules to catch
|
|
||||||
common issues. Use the `analyze_files` tool to run the linter.
|
|
||||||
|
|
||||||
### Project Structure
|
|
||||||
* **Standard Structure:** Assumes a standard Flutter project structure with
|
|
||||||
`lib/main.dart` as the primary application entry point.
|
|
||||||
|
|
||||||
### Flutter style guide
|
|
||||||
* **SOLID Principles:** Apply SOLID principles throughout the codebase.
|
|
||||||
* **Concise and Declarative:** Write concise, modern, technical Dart code.
|
|
||||||
Prefer functional and declarative patterns.
|
|
||||||
* **Composition over Inheritance:** Favor composition for building complex
|
|
||||||
widgets and logic.
|
|
||||||
* **Immutability:** Prefer immutable data structures. Widgets (especially
|
|
||||||
`StatelessWidget`) should be immutable.
|
|
||||||
* **State Management:** Separate ephemeral state and app state. Use a state
|
|
||||||
management solution for app state to handle the separation of concerns.
|
|
||||||
* **Widgets are for UI:** Everything in Flutter's UI is a widget. Compose
|
|
||||||
complex UIs from smaller, reusable widgets.
|
|
||||||
* **Navigation:** Use a modern routing package like `auto_route` or `go_router`.
|
|
||||||
For more guidelines around navigation, see the section on [routing](#routing).
|
|
||||||
|
|
||||||
### Package Management
|
|
||||||
* **Pub Tool:** To manage packages, use the `pub` tool, if available.
|
|
||||||
* **External Packages:** If a new feature requires an external package, use the
|
|
||||||
`pub_dev_search` tool, if it is available. Otherwise, identify the most
|
|
||||||
suitable and stable package from pub.dev.
|
|
||||||
* **Adding Dependencies:** To add a regular dependency, use the `pub` tool, if
|
|
||||||
it is available. Otherwise, run `flutter pub add <package_name>`.
|
|
||||||
* **Adding Dev Dependencies:** To add a development dependency, use the `pub`
|
|
||||||
tool, if it is available, with `dev:<package name>`. Otherwise, run `flutter
|
|
||||||
pub add dev:<package_name>`.
|
|
||||||
* **Dependency Overrides:** To add a dependency override, use the `pub` tool, if
|
|
||||||
it is available, with `override:<package name>:1.0.0`. Otherwise, run `flutter
|
|
||||||
pub add override:<package_name>:1.0.0`.
|
|
||||||
* **Removing Dependencies:** To remove a dependency, use the `pub` tool, if it
|
|
||||||
is available. Otherwise, run `dart pub remove <package_name>`.
|
|
||||||
|
|
||||||
### Code Quality
|
|
||||||
* **Code structure:** Adhere to maintainable code structure and separation of
|
|
||||||
concerns (e.g., UI logic separate from business logic).
|
|
||||||
* **Naming conventions:** Avoid abbreviations and use meaningful, consistent,
|
|
||||||
descriptive names for variables, functions, and classes.
|
|
||||||
* **Conciseness:** Write code that is as short as it can be while remaining
|
|
||||||
clear.
|
|
||||||
* **Simplicity:** Write straightforward code. Code that is clever or
|
|
||||||
obscure is difficult to maintain.
|
|
||||||
* **Error Handling:** Anticipate and handle potential errors. Don't let your
|
|
||||||
code fail silently.
|
|
||||||
* **Styling:**
|
|
||||||
* Line length: Lines should be 80 characters or fewer.
|
|
||||||
* Use `PascalCase` for classes, `camelCase` for
|
|
||||||
members/variables/functions/enums, and `snake_case` for files.
|
|
||||||
* **Functions:**
|
|
||||||
* Keep functions short and with a single purpose.
|
|
||||||
Strive for less than 20 lines.
|
|
||||||
* **Testing:** Write code with testing in mind. Use the `file`, `process`, and
|
|
||||||
`platform` packages, if appropriate, so you can inject in-memory and fake
|
|
||||||
versions of the objects.
|
|
||||||
* **Logging:** Use the `logging` package instead of `print`.
|
|
||||||
|
|
||||||
### Dart Best Practices
|
|
||||||
* **Effective Dart:** Follow the official Effective Dart guidelines
|
|
||||||
(https://dart.dev/effective-dart)
|
|
||||||
* **Class Organization:** Define related classes within the same library file.
|
|
||||||
For large libraries, export smaller, private libraries from a single top-level
|
|
||||||
library.
|
|
||||||
* **Library Organization:** Group related libraries in the same folder.
|
|
||||||
* **API Documentation:** Add documentation comments to all public APIs,
|
|
||||||
including classes, constructors, methods, and top-level functions.
|
|
||||||
* **Comments:** Write clear comments for complex or non-obvious code. Avoid
|
|
||||||
over-commenting.
|
|
||||||
* **Trailing Comments:** Don't add trailing comments.
|
|
||||||
* **Async/Await:** Ensure proper use of `async`/`await` for asynchronous
|
|
||||||
operations with robust error handling.
|
|
||||||
* Use `Future`s, `async`, and `await` for asynchronous operations.
|
|
||||||
* Use `Stream`s for sequences of asynchronous events.
|
|
||||||
* **Null Safety:** Write code that is soundly null-safe. Leverage Dart's null
|
|
||||||
safety features. Avoid `!` unless the value is guaranteed to be non-null.
|
|
||||||
* **Pattern Matching:** Use pattern matching features where they simplify the
|
|
||||||
code.
|
|
||||||
* **Records:** Use records to return multiple types in situations where defining
|
|
||||||
an entire class is cumbersome.
|
|
||||||
* **Switch Statements:** Prefer using exhaustive `switch` statements or
|
|
||||||
expressions, which don't require `break` statements.
|
|
||||||
* **Exception Handling:** Use `try-catch` blocks for handling exceptions, and
|
|
||||||
use exceptions appropriate for the type of exception. Use custom exceptions
|
|
||||||
for situations specific to your code.
|
|
||||||
* **Arrow Functions:** Use arrow syntax for simple one-line functions.
|
|
||||||
|
|
||||||
### Flutter Best Practices
|
|
||||||
* **Immutability:** Widgets (especially `StatelessWidget`) are immutable; when
|
|
||||||
the UI needs to change, Flutter rebuilds the widget tree.
|
|
||||||
* **Composition:** Prefer composing smaller widgets over extending existing
|
|
||||||
ones. Use this to avoid deep widget nesting.
|
|
||||||
* **Private Widgets:** Use small, private `Widget` classes instead of private
|
|
||||||
helper methods that return a `Widget`.
|
|
||||||
* **Build Methods:** Break down large `build()` methods into smaller, reusable
|
|
||||||
private Widget classes.
|
|
||||||
* **List Performance:** Use `ListView.builder` or `SliverList` for long lists to
|
|
||||||
create lazy-loaded lists for performance.
|
|
||||||
* **Isolates:** Use `compute()` to run expensive calculations in a separate
|
|
||||||
isolate to avoid blocking the UI thread, such as JSON parsing.
|
|
||||||
* **Const Constructors:** Use `const` constructors for widgets and in `build()`
|
|
||||||
methods whenever possible to reduce rebuilds.
|
|
||||||
* **Build Method Performance:** Avoid performing expensive operations, like
|
|
||||||
network calls or complex computations, directly within `build()` methods.
|
|
||||||
|
|
||||||
### API Design Principles
|
|
||||||
When building reusable APIs, such as a library, follow these principles.
|
|
||||||
|
|
||||||
* **Consider the User:** Design APIs from the perspective of the person who will
|
|
||||||
be using them. The API should be intuitive and easy to use correctly.
|
|
||||||
* **Documentation is Essential:** Good documentation is a part of good API
|
|
||||||
design. It should be clear, concise, and provide examples.
|
|
||||||
|
|
||||||
### Application Architecture
|
|
||||||
* **Separation of Concerns:** Aim for separation of concerns similar to MVC/MVVM, with defined Model,
|
|
||||||
View, and ViewModel/Controller roles.
|
|
||||||
* **Logical Layers:** Organize the project into logical layers:
|
|
||||||
* Presentation (widgets, screens)
|
|
||||||
* Domain (business logic classes)
|
|
||||||
* Data (model classes, API clients)
|
|
||||||
* Core (shared classes, utilities, and extension types)
|
|
||||||
* **Feature-based Organization:** For larger projects, organize code by feature,
|
|
||||||
where each feature has its own presentation, domain, and data subfolders. This
|
|
||||||
improves navigability and scalability.
|
|
||||||
|
|
||||||
### Lint Rules
|
|
||||||
|
|
||||||
Include the package in the `analysis_options.yaml` file. Use the following
|
|
||||||
`analysis_options.yaml` file as a starting point:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
include: package:flutter_lints/flutter.yaml
|
|
||||||
|
|
||||||
linter:
|
|
||||||
rules:
|
|
||||||
# Add additional lint rules here:
|
|
||||||
# avoid_print: false
|
|
||||||
# prefer_single_quotes: true
|
|
||||||
```
|
|
||||||
|
|
||||||
#### State Management
|
|
||||||
* **Built-in Solutions:** Prefer Flutter's built-in state management solutions.
|
|
||||||
Do not use a third-party package unless explicitly requested.
|
|
||||||
* **Streams:** Use `Streams` and `StreamBuilder` for handling a sequence of
|
|
||||||
asynchronous events.
|
|
||||||
* **Futures:** Use `Futures` and `FutureBuilder` for handling a single
|
|
||||||
asynchronous operation that will complete in the future.
|
|
||||||
* **ValueNotifier:** Use `ValueNotifier` with `ValueListenableBuilder` for
|
|
||||||
simple, local state that involves a single value.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// Define a ValueNotifier to hold the state.
|
|
||||||
final ValueNotifier<int> _counter = ValueNotifier<int>(0);
|
|
||||||
|
|
||||||
// Use ValueListenableBuilder to listen and rebuild.
|
|
||||||
ValueListenableBuilder<int>(
|
|
||||||
valueListenable: _counter,
|
|
||||||
builder: (context, value, child) {
|
|
||||||
return Text('Count: $value');
|
|
||||||
},
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
* **ChangeNotifier:** For state that is more complex or shared across multiple
|
|
||||||
widgets, use `ChangeNotifier`.
|
|
||||||
* **ListenableBuilder:** Use `ListenableBuilder` to listen to changes from a
|
|
||||||
`ChangeNotifier` or other `Listenable`.
|
|
||||||
* **MVVM:** When a more robust solution is needed, structure the app using the
|
|
||||||
Model-View-ViewModel (MVVM) pattern.
|
|
||||||
* **Dependency Injection:** Use simple manual constructor dependency injection
|
|
||||||
to make a class's dependencies explicit in its API, and to manage dependencies
|
|
||||||
between different layers of the application.
|
|
||||||
* **Provider:** If a dependency injection solution beyond manual constructor
|
|
||||||
injection is explicitly requested, `provider` can be used to make services,
|
|
||||||
repositories, or complex state objects available to the UI layer without tight
|
|
||||||
coupling (note: this document generally defaults against third-party packages
|
|
||||||
for state management unless explicitly requested).
|
|
||||||
|
|
||||||
#### Data Flow
|
|
||||||
* **Data Structures:** Define data structures (classes) to represent the data
|
|
||||||
used in the application.
|
|
||||||
* **Data Abstraction:** Abstract data sources (e.g., API calls, database
|
|
||||||
operations) using Repositories/Services to promote testability.
|
|
||||||
|
|
||||||
#### Routing
|
|
||||||
* **GoRouter:** Use the `go_router` package for declarative navigation, deep
|
|
||||||
linking, and web support.
|
|
||||||
* **GoRouter Setup:** To use `go_router`, first add it to your `pubspec.yaml`
|
|
||||||
using the `pub` tool's `add` command.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// 1. Add the dependency
|
|
||||||
// flutter pub add go_router
|
|
||||||
|
|
||||||
// 2. Configure the router
|
|
||||||
final GoRouter _router = GoRouter(
|
|
||||||
routes: <RouteBase>[
|
|
||||||
GoRoute(
|
|
||||||
path: '/',
|
|
||||||
builder: (context, state) => const HomeScreen(),
|
|
||||||
routes: <RouteBase>[
|
|
||||||
GoRoute(
|
|
||||||
path: 'details/:id', // Route with a path parameter
|
|
||||||
builder: (context, state) {
|
|
||||||
final String id = state.pathParameters['id']!;
|
|
||||||
return DetailScreen(id: id);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
// 3. Use it in your MaterialApp
|
|
||||||
MaterialApp.router(
|
|
||||||
routerConfig: _router,
|
|
||||||
);
|
|
||||||
```
|
|
||||||
* **Authentication Redirects:** Configure `go_router`'s `redirect` property to
|
|
||||||
handle authentication flows, ensuring users are redirected to the login screen
|
|
||||||
when unauthorized, and back to their intended destination after successful
|
|
||||||
login.
|
|
||||||
|
|
||||||
* **Navigator:** Use the built-in `Navigator` for short-lived screens that do
|
|
||||||
not need to be deep-linkable, such as dialogs or temporary views.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// Push a new screen onto the stack
|
|
||||||
Navigator.push(
|
|
||||||
context,
|
|
||||||
MaterialPageRoute(builder: (context) => const DetailsScreen()),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Pop the current screen to go back
|
|
||||||
Navigator.pop(context);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Data Handling & Serialization
|
|
||||||
* **JSON Serialization:** Use `json_serializable` and `json_annotation` for
|
|
||||||
parsing and encoding JSON data.
|
|
||||||
* **Field Renaming:** When encoding data, use `fieldRename: FieldRename.snake`
|
|
||||||
to convert Dart's camelCase fields to snake_case JSON keys.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// In your model file
|
|
||||||
import 'package:json_annotation/json_annotation.dart';
|
|
||||||
|
|
||||||
part 'user.g.dart';
|
|
||||||
|
|
||||||
@JsonSerializable(fieldRename: FieldRename.snake)
|
|
||||||
class User {
|
|
||||||
final String firstName;
|
|
||||||
final String lastName;
|
|
||||||
|
|
||||||
User({required this.firstName, required this.lastName});
|
|
||||||
|
|
||||||
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
|
|
||||||
Map<String, dynamic> toJson() => _$UserToJson(this);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
#### Logging
|
|
||||||
* **Structured Logging:** Use the `log` function from `dart:developer` for
|
|
||||||
structured logging that integrates with Dart DevTools.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
import 'dart:developer' as developer;
|
|
||||||
|
|
||||||
// For simple messages
|
|
||||||
developer.log('User logged in successfully.');
|
|
||||||
|
|
||||||
// For structured error logging
|
|
||||||
try {
|
|
||||||
// ... code that might fail
|
|
||||||
} catch (e, s) {
|
|
||||||
developer.log(
|
|
||||||
'Failed to fetch data',
|
|
||||||
name: 'myapp.network',
|
|
||||||
level: 1000, // SEVERE
|
|
||||||
error: e,
|
|
||||||
stackTrace: s,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Code Generation
|
|
||||||
* **Build Runner:** If the project uses code generation, ensure that
|
|
||||||
`build_runner` is listed as a dev dependency in `pubspec.yaml`.
|
|
||||||
* **Code Generation Tasks:** Use `build_runner` for all code generation tasks,
|
|
||||||
such as for `json_serializable`.
|
|
||||||
* **Running Build Runner:** After modifying files that require code generation,
|
|
||||||
run the build command:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
dart run build_runner build --delete-conflicting-outputs
|
|
||||||
```
|
|
||||||
|
|
||||||
### Testing
|
|
||||||
* **Running Tests:** To run tests, use the `run_tests` tool if it is available,
|
|
||||||
otherwise use `flutter test`.
|
|
||||||
* **Unit Tests:** Use `package:test` for unit tests.
|
|
||||||
* **Widget Tests:** Use `package:flutter_test` for widget tests.
|
|
||||||
* **Integration Tests:** Use `package:integration_test` for integration tests.
|
|
||||||
* **Assertions:** Prefer using `package:checks` for more expressive and readable
|
|
||||||
assertions over the default `matchers`.
|
|
||||||
|
|
||||||
#### Testing Best practices
|
|
||||||
* **Convention:** Follow the Arrange-Act-Assert (or Given-When-Then) pattern.
|
|
||||||
* **Unit Tests:** Write unit tests for domain logic, data layer, and state
|
|
||||||
management.
|
|
||||||
* **Widget Tests:** Write widget tests for UI components.
|
|
||||||
* **Integration Tests:** For broader application validation, use integration
|
|
||||||
tests to verify end-to-end user flows.
|
|
||||||
* **integration_test package:** Use the `integration_test` package from the
|
|
||||||
Flutter SDK for integration tests. Add it as a `dev_dependency` in
|
|
||||||
`pubspec.yaml` by specifying `sdk: flutter`.
|
|
||||||
* **Mocks:** Prefer fakes or stubs over mocks. If mocks are absolutely
|
|
||||||
necessary, use `mockito` or `mocktail` to create mocks for dependencies. While
|
|
||||||
code generation is common for state management (e.g., with `freezed`), try to
|
|
||||||
avoid it for mocks.
|
|
||||||
* **Coverage:** Aim for high test coverage.
|
|
||||||
|
|
||||||
### Visual Design & Theming
|
|
||||||
* **UI Design:** Build beautiful and intuitive user interfaces that follow
|
|
||||||
modern design guidelines.
|
|
||||||
* **Responsiveness:** Ensure the app is mobile responsive and adapts to
|
|
||||||
different screen sizes, working perfectly on mobile and web.
|
|
||||||
* **Navigation:** If there are multiple pages for the user to interact with,
|
|
||||||
provide an intuitive and easy navigation bar or controls.
|
|
||||||
* **Typography:** Stress and emphasize font sizes to ease understanding, e.g.,
|
|
||||||
hero text, section headlines, list headlines, keywords in paragraphs.
|
|
||||||
* **Background:** Keep backgrounds flat and simple — no noise texture or
|
|
||||||
gradients. Follow the `unified-design-system` skill (safe-design-rules
|
|
||||||
rule 17: simple-on-complex); let content and typography carry visual
|
|
||||||
interest instead of background texture.
|
|
||||||
* **Shadows:** Follow the `unified-design-system` skill's shadow policy: no
|
|
||||||
shadows at all in dark UI (differentiate elevation with lighter surface
|
|
||||||
fills, not shadows); in light UI, shadows are for floating/overlay
|
|
||||||
elements only (menus, dialogs), never for inline cards, and never mixed
|
|
||||||
with a border on the same surface.
|
|
||||||
* **Icons:** Incorporate icons to enhance the user’s understanding and the
|
|
||||||
logical navigation of the app.
|
|
||||||
* **Interactive Elements:** Buttons/controls signal state via color and fill
|
|
||||||
changes, not a "glow" shadow — one depth technique per surface, per
|
|
||||||
`unified-design-system`.
|
|
||||||
|
|
||||||
#### Theming
|
|
||||||
* **Centralized Theme:** Define a centralized `ThemeData` object to ensure a
|
|
||||||
consistent application-wide style.
|
|
||||||
* **Light and Dark Themes:** Implement support for both light and dark themes,
|
|
||||||
ideal for a user-facing theme toggle (`ThemeMode.light`, `ThemeMode.dark`,
|
|
||||||
`ThemeMode.system`).
|
|
||||||
* **Color Scheme Generation:** Do NOT use `ColorScheme.fromSeed` for this
|
|
||||||
app's palette — it can't reproduce hand-picked values exactly. Build
|
|
||||||
`ThemeData` from explicit `ColorScheme.dark(...)`/`.light(...)` using the
|
|
||||||
frozen, identical-everywhere tokens in the `unified-design-system` skill
|
|
||||||
(`~/.claude/skills/unified-design-system/references/tokens.md`).
|
|
||||||
|
|
||||||
```dart
|
|
||||||
final ThemeData lightTheme = ThemeData(
|
|
||||||
colorScheme: ColorScheme.fromSeed(
|
|
||||||
seedColor: Colors.deepPurple,
|
|
||||||
brightness: Brightness.light,
|
|
||||||
),
|
|
||||||
// ... other theme properties
|
|
||||||
);
|
|
||||||
```
|
|
||||||
* **Color Palette:** Include a wide range of color concentrations and hues in
|
|
||||||
the palette to create a vibrant and energetic look and feel.
|
|
||||||
* **Component Themes:** Use specific theme properties (e.g., `appBarTheme`,
|
|
||||||
`elevatedButtonTheme`) to customize the appearance of individual Material
|
|
||||||
components.
|
|
||||||
* **Custom Fonts:** For custom fonts, use the `google_fonts` package. Define a
|
|
||||||
`TextTheme` to apply fonts consistently.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// 1. Add the dependency
|
|
||||||
// flutter pub add google_fonts
|
|
||||||
|
|
||||||
// 2. Define a TextTheme with a custom font
|
|
||||||
final TextTheme appTextTheme = TextTheme(
|
|
||||||
displayLarge: GoogleFonts.oswald(fontSize: 57, fontWeight: FontWeight.bold),
|
|
||||||
titleLarge: GoogleFonts.roboto(fontSize: 22, fontWeight: FontWeight.w500),
|
|
||||||
bodyMedium: GoogleFonts.openSans(fontSize: 14),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Assets and Images
|
|
||||||
* **Image Guidelines:** If images are needed, make them relevant and meaningful,
|
|
||||||
with appropriate size, layout, and licensing (e.g., freely available). Provide
|
|
||||||
placeholder images if real ones are not available.
|
|
||||||
* **Asset Declaration:** Declare all asset paths in your `pubspec.yaml` file.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
flutter:
|
|
||||||
uses-material-design: true
|
|
||||||
assets:
|
|
||||||
- assets/images/
|
|
||||||
```
|
|
||||||
|
|
||||||
* **Local Images:** Use `Image.asset` for local images from your asset
|
|
||||||
bundle.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
Image.asset('assets/images/placeholder.png')
|
|
||||||
```
|
|
||||||
* **Network images:** Use NetworkImage for images loaded from the network.
|
|
||||||
* **Cached images:** For cached images, use NetworkImage a package like
|
|
||||||
`cached_network_image`.
|
|
||||||
* **Custom Icons:** Use `ImageIcon` to display an icon from an `ImageProvider`,
|
|
||||||
useful for custom icons not in the `Icons` class.
|
|
||||||
* **Network Images:** Use `Image.network` to display images from a URL, and
|
|
||||||
always include `loadingBuilder` and `errorBuilder` for a better user
|
|
||||||
experience.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// When using network images, always provide an errorBuilder.
|
|
||||||
Image.network(
|
|
||||||
'https://picsum.photos/200/300',
|
|
||||||
loadingBuilder: (context, child, progress) {
|
|
||||||
if (progress == null) return child;
|
|
||||||
return const Center(child: CircularProgressIndicator());
|
|
||||||
},
|
|
||||||
errorBuilder: (context, error, stackTrace) {
|
|
||||||
return const Icon(Icons.error);
|
|
||||||
},
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### UI Theming and Styling Code
|
|
||||||
|
|
||||||
* **Responsiveness:** Use `LayoutBuilder` or `MediaQuery` to create responsive
|
|
||||||
UIs.
|
|
||||||
* **Text:** Use `Theme.of(context).textTheme` for text styles.
|
|
||||||
* **Text Fields:** Configure `textCapitalization`, `keyboardType`, and
|
|
||||||
`placeholder`.
|
|
||||||
|
|
||||||
### Material Theming Best Practices
|
|
||||||
|
|
||||||
#### Embrace `ThemeData` and Material 3
|
|
||||||
|
|
||||||
* **Use `ColorScheme.fromSeed()`:** Use this to generate a complete, harmonious
|
|
||||||
color palette for both light and dark modes from a single seed color.
|
|
||||||
* **Define Light and Dark Themes:** Provide both `theme` and `darkTheme` to your
|
|
||||||
`MaterialApp` to support system brightness settings seamlessly.
|
|
||||||
* **Centralize Component Styles:** Customize specific component themes (e.g.,
|
|
||||||
`elevatedButtonTheme`, `cardTheme`, `appBarTheme`) within `ThemeData` to
|
|
||||||
ensure consistency.
|
|
||||||
* **Dark/Light Mode and Theme Toggle:** Implement support for both light and
|
|
||||||
dark themes using `theme` and `darkTheme` properties of `MaterialApp`. The
|
|
||||||
`themeMode` property can be dynamically controlled (e.g., via a
|
|
||||||
`ChangeNotifierProvider`) to allow for toggling between `ThemeMode.light`,
|
|
||||||
`ThemeMode.dark`, or `ThemeMode.system`.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// main.dart
|
|
||||||
MaterialApp(
|
|
||||||
theme: ThemeData(
|
|
||||||
colorScheme: ColorScheme.fromSeed(
|
|
||||||
seedColor: Colors.deepPurple,
|
|
||||||
brightness: Brightness.light,
|
|
||||||
),
|
|
||||||
textTheme: const TextTheme(
|
|
||||||
displayLarge: TextStyle(fontSize: 57.0, fontWeight: FontWeight.bold),
|
|
||||||
bodyMedium: TextStyle(fontSize: 14.0, height: 1.4),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
darkTheme: ThemeData(
|
|
||||||
colorScheme: ColorScheme.fromSeed(
|
|
||||||
seedColor: Colors.deepPurple,
|
|
||||||
brightness: Brightness.dark,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
home: const MyHomePage(),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Implement Design Tokens with `ThemeExtension`
|
|
||||||
|
|
||||||
For custom styles that aren't part of the standard `ThemeData`, use
|
|
||||||
`ThemeExtension` to define reusable design tokens.
|
|
||||||
|
|
||||||
* **Create a Custom Theme Extension:** Define a class that extends
|
|
||||||
`ThemeExtension<T>` and include your custom properties.
|
|
||||||
* **Implement `copyWith` and `lerp`:** These methods are required for the
|
|
||||||
extension to work correctly with theme transitions.
|
|
||||||
* **Register in `ThemeData`:** Add your custom extension to the `extensions`
|
|
||||||
list in your `ThemeData`.
|
|
||||||
* **Access Tokens in Widgets:** Use `Theme.of(context).extension<MyColors>()!`
|
|
||||||
to access your custom tokens.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// 1. Define the extension
|
|
||||||
@immutable
|
|
||||||
class MyColors extends ThemeExtension<MyColors> {
|
|
||||||
const MyColors({required this.success, required this.danger});
|
|
||||||
|
|
||||||
final Color? success;
|
|
||||||
final Color? danger;
|
|
||||||
|
|
||||||
@override
|
|
||||||
ThemeExtension<MyColors> copyWith({Color? success, Color? danger}) {
|
|
||||||
return MyColors(success: success ?? this.success, danger: danger ?? this.danger);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
ThemeExtension<MyColors> lerp(ThemeExtension<MyColors>? other, double t) {
|
|
||||||
if (other is! MyColors) return this;
|
|
||||||
return MyColors(
|
|
||||||
success: Color.lerp(success, other.success, t),
|
|
||||||
danger: Color.lerp(danger, other.danger, t),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Register it in ThemeData
|
|
||||||
theme: ThemeData(
|
|
||||||
extensions: const <ThemeExtension<dynamic>>[
|
|
||||||
MyColors(success: Colors.green, danger: Colors.red),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
|
|
||||||
// 3. Use it in a widget
|
|
||||||
Container(
|
|
||||||
color: Theme.of(context).extension<MyColors>()!.success,
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Styling with `WidgetStateProperty`
|
|
||||||
|
|
||||||
* **`WidgetStateProperty.resolveWith`:** Provide a function that receives a
|
|
||||||
`Set<WidgetState>` and returns the appropriate value for the current state.
|
|
||||||
* **`WidgetStateProperty.all`:** A shorthand for when the value is the same for
|
|
||||||
all states.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// Example: Creating a button style that changes color when pressed.
|
|
||||||
final ButtonStyle myButtonStyle = ButtonStyle(
|
|
||||||
backgroundColor: WidgetStateProperty.resolveWith<Color>(
|
|
||||||
(Set<WidgetState> states) {
|
|
||||||
if (states.contains(WidgetState.pressed)) {
|
|
||||||
return Colors.green; // Color when pressed
|
|
||||||
}
|
|
||||||
return Colors.red; // Default color
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
### Layout Best Practices
|
|
||||||
|
|
||||||
#### Building Flexible and Overflow-Safe Layouts
|
|
||||||
|
|
||||||
##### For Rows and Columns
|
|
||||||
|
|
||||||
* **`Expanded`:** Use to make a child widget fill the remaining available space
|
|
||||||
along the main axis.
|
|
||||||
* **`Flexible`:** Use when you want a widget to shrink to fit, but not
|
|
||||||
necessarily grow. Don't combine `Flexible` and `Expanded` in the same `Row` or
|
|
||||||
`Column`.
|
|
||||||
* **`Wrap`:** Use when you have a series of widgets that would overflow a `Row`
|
|
||||||
or `Column`, and you want them to move to the next line.
|
|
||||||
|
|
||||||
##### For General Content
|
|
||||||
|
|
||||||
* **`SingleChildScrollView`:** Use when your content is intrinsically larger
|
|
||||||
than the viewport, but is a fixed size.
|
|
||||||
* **`ListView` / `GridView`:** For long lists or grids of content, always use a
|
|
||||||
builder constructor (`.builder`).
|
|
||||||
* **`FittedBox`:** Use to scale or fit a single child widget within its parent.
|
|
||||||
* **`LayoutBuilder`:** Use for complex, responsive layouts to make decisions
|
|
||||||
based on the available space.
|
|
||||||
|
|
||||||
#### Layering Widgets with Stack
|
|
||||||
|
|
||||||
* **`Positioned`:** Use to precisely place a child within a `Stack` by anchoring it to the edges.
|
|
||||||
* **`Align`:** Use to position a child within a `Stack` using alignments like `Alignment.center`.
|
|
||||||
|
|
||||||
#### Advanced Layout with Overlays
|
|
||||||
|
|
||||||
* **`OverlayPortal`:** Use this widget to show UI elements (like custom
|
|
||||||
dropdowns or tooltips) "on top" of everything else. It manages the
|
|
||||||
`OverlayEntry` for you.
|
|
||||||
|
|
||||||
```dart
|
|
||||||
class MyDropdown extends StatefulWidget {
|
|
||||||
const MyDropdown({super.key});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<MyDropdown> createState() => _MyDropdownState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _MyDropdownState extends State<MyDropdown> {
|
|
||||||
final _controller = OverlayPortalController();
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return OverlayPortal(
|
|
||||||
controller: _controller,
|
|
||||||
overlayChildBuilder: (BuildContext context) {
|
|
||||||
return const Positioned(
|
|
||||||
top: 50,
|
|
||||||
left: 10,
|
|
||||||
child: Card(
|
|
||||||
child: Padding(
|
|
||||||
padding: EdgeInsets.all(8.0),
|
|
||||||
child: Text('I am an overlay!'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
child: ElevatedButton(
|
|
||||||
onPressed: _controller.toggle,
|
|
||||||
child: const Text('Toggle Overlay'),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Color Scheme Best Practices
|
|
||||||
|
|
||||||
#### Contrast Ratios
|
|
||||||
|
|
||||||
* **WCAG Guidelines:** Aim to meet the Web Content Accessibility Guidelines
|
|
||||||
(WCAG) 2.1 standards.
|
|
||||||
* **Minimum Contrast:**
|
|
||||||
* **Normal Text:** A contrast ratio of at least **4.5:1**.
|
|
||||||
* **Large Text:** (18pt or 14pt bold) A contrast ratio of at least **3:1**.
|
|
||||||
|
|
||||||
#### Palette Selection
|
|
||||||
|
|
||||||
* **Primary, Secondary, and Accent:** Define a clear color hierarchy.
|
|
||||||
* **The 60-30-10 Rule:** A classic design rule for creating a balanced color scheme.
|
|
||||||
* **60%** Primary/Neutral Color (Dominant)
|
|
||||||
* **30%** Secondary Color
|
|
||||||
* **10%** Accent Color
|
|
||||||
|
|
||||||
#### Complementary Colors
|
|
||||||
|
|
||||||
* **Use with Caution:** They can be visually jarring if overused.
|
|
||||||
* **Best Use Cases:** They are excellent for accent colors to make specific
|
|
||||||
elements pop, but generally poor for text and background pairings as they can
|
|
||||||
cause eye strain.
|
|
||||||
|
|
||||||
#### Example Palette
|
|
||||||
|
|
||||||
* **Primary:** #0D47A1 (Dark Blue)
|
|
||||||
* **Secondary:** #1976D2 (Medium Blue)
|
|
||||||
* **Accent:** #FFC107 (Amber)
|
|
||||||
* **Neutral/Text:** #212121 (Almost Black)
|
|
||||||
* **Background:** #FEFEFE (Almost White)
|
|
||||||
|
|
||||||
### Font Best Practices
|
|
||||||
|
|
||||||
#### Font Selection
|
|
||||||
|
|
||||||
* **Limit Font Families:** Stick to one or two font families for the entire
|
|
||||||
application.
|
|
||||||
* **Prioritize Legibility:** Choose fonts that are easy to read on screens of
|
|
||||||
all sizes. Sans-serif fonts are generally preferred for UI body text.
|
|
||||||
* **System Fonts:** Consider using platform-native system fonts.
|
|
||||||
* **Google Fonts:** For a wide selection of open-source fonts, use the
|
|
||||||
`google_fonts` package.
|
|
||||||
|
|
||||||
#### Hierarchy and Scale
|
|
||||||
|
|
||||||
* **Establish a Scale:** Define a set of font sizes for different text elements
|
|
||||||
(e.g., headlines, titles, body text, captions).
|
|
||||||
* **Use Font Weight:** Differentiate text effectively using font weights.
|
|
||||||
* **Color and Opacity:** Use color and opacity to de-emphasize less important
|
|
||||||
text.
|
|
||||||
|
|
||||||
#### Readability
|
|
||||||
|
|
||||||
* **Line Height (Leading):** Set an appropriate line height, typically **1.4x to
|
|
||||||
1.6x** the font size.
|
|
||||||
* **Line Length:** For body text, aim for a line length of **45-75 characters**.
|
|
||||||
* **Avoid All Caps:** Do not use all caps for long-form text.
|
|
||||||
|
|
||||||
#### Example Typographic Scale
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// In your ThemeData
|
|
||||||
textTheme: const TextTheme(
|
|
||||||
displayLarge: TextStyle(fontSize: 57.0, fontWeight: FontWeight.bold),
|
|
||||||
titleLarge: TextStyle(fontSize: 22.0, fontWeight: FontWeight.bold),
|
|
||||||
bodyLarge: TextStyle(fontSize: 16.0, height: 1.5),
|
|
||||||
bodyMedium: TextStyle(fontSize: 14.0, height: 1.4),
|
|
||||||
labelSmall: TextStyle(fontSize: 11.0, color: Colors.grey),
|
|
||||||
),
|
|
||||||
```
|
|
||||||
|
|
||||||
### Documentation
|
|
||||||
|
|
||||||
* **`dartdoc`:** Write `dartdoc`-style comments for all public APIs.
|
|
||||||
|
|
||||||
|
|
||||||
#### Documentation Philosophy
|
|
||||||
|
|
||||||
* **Comment wisely:** Use comments to explain why the code is written a certain
|
|
||||||
way, not what the code does. The code itself should be self-explanatory.
|
|
||||||
* **Document for the user:** Write documentation with the reader in mind. If you
|
|
||||||
had a question and found the answer, add it to the documentation where you
|
|
||||||
first looked. This ensures the documentation answers real-world questions.
|
|
||||||
* **No useless documentation:** If the documentation only restates the obvious
|
|
||||||
from the code's name, it's not helpful. Good documentation provides context
|
|
||||||
and explains what isn't immediately apparent.
|
|
||||||
* **Consistency is key:** Use consistent terminology throughout your
|
|
||||||
documentation.
|
|
||||||
|
|
||||||
#### Commenting Style
|
|
||||||
|
|
||||||
* **Use `///` for doc comments:** This allows documentation generation tools to
|
|
||||||
pick them up.
|
|
||||||
* **Start with a single-sentence summary:** The first sentence should be a
|
|
||||||
concise, user-centric summary ending with a period.
|
|
||||||
* **Separate the summary:** Add a blank line after the first sentence to create
|
|
||||||
a separate paragraph. This helps tools create better summaries.
|
|
||||||
* **Avoid redundancy:** Don't repeat information that's obvious from the code's
|
|
||||||
context, like the class name or signature.
|
|
||||||
* **Don't document both getter and setter:** For properties with both, only
|
|
||||||
document one. The documentation tool will treat them as a single field.
|
|
||||||
|
|
||||||
#### Writing Style
|
|
||||||
|
|
||||||
* **Be brief:** Write concisely.
|
|
||||||
* **Avoid jargon and acronyms:** Don't use abbreviations unless they are widely
|
|
||||||
understood.
|
|
||||||
* **Use Markdown sparingly:** Avoid excessive markdown and never use HTML for
|
|
||||||
formatting.
|
|
||||||
* **Use backticks for code:** Enclose code blocks in backtick fences, and
|
|
||||||
specify the language.
|
|
||||||
|
|
||||||
#### What to Document
|
|
||||||
|
|
||||||
* **Public APIs are a priority:** Always document public APIs.
|
|
||||||
* **Consider private APIs:** It's a good idea to document private APIs as well.
|
|
||||||
* **Library-level comments are helpful:** Consider adding a doc comment at the
|
|
||||||
library level to provide a general overview.
|
|
||||||
* **Include code samples:** Where appropriate, add code samples to illustrate usage.
|
|
||||||
* **Explain parameters, return values, and exceptions:** Use prose to describe
|
|
||||||
what a function expects, what it returns, and what errors it might throw.
|
|
||||||
* **Place doc comments before annotations:** Documentation should come before
|
|
||||||
any metadata annotations.
|
|
||||||
|
|
||||||
### Accessibility (A11Y)
|
|
||||||
Implement accessibility features to empower all users, assuming a wide variety
|
|
||||||
of users with different physical abilities, mental abilities, age groups,
|
|
||||||
education levels, and learning styles.
|
|
||||||
|
|
||||||
* **Color Contrast:** Ensure text has a contrast ratio of at least **4.5:1**
|
|
||||||
against its background.
|
|
||||||
* **Dynamic Text Scaling:** Test your UI to ensure it remains usable when users
|
|
||||||
increase the system font size.
|
|
||||||
* **Semantic Labels:** Use the `Semantics` widget to provide clear, descriptive
|
|
||||||
labels for UI elements.
|
|
||||||
* **Screen Reader Testing:** Regularly test your app with TalkBack (Android) and
|
|
||||||
VoiceOver (iOS).
|
|
||||||
|
|||||||
@ -16,6 +16,12 @@ analyzer:
|
|||||||
- "**/*.g.dart"
|
- "**/*.g.dart"
|
||||||
- "**/*.freezed.dart"
|
- "**/*.freezed.dart"
|
||||||
- "test/**"
|
- "test/**"
|
||||||
|
- android/**
|
||||||
|
- ios/**
|
||||||
|
- web/**
|
||||||
|
- windows/**
|
||||||
|
- macos/**
|
||||||
|
- linux/**
|
||||||
|
|
||||||
linter:
|
linter:
|
||||||
rules:
|
rules:
|
||||||
|
|||||||
@ -1,18 +1,18 @@
|
|||||||
// coverage:ignore-file
|
// coverage:ignore-file
|
||||||
// Entry point for the desktop wrapper: resolves real paths, starts the server,
|
// Entry point for the desktop wrapper: resolves real paths, starts the server,
|
||||||
// and launches the browser. The serving logic it delegates to is covered by
|
// and launches the browser. The serving logic it delegates to is covered by
|
||||||
// test/wrapper_server_test.dart, and the busy-port recovery it delegates to by
|
// test/wrapper_server_*_test.dart, and the busy-port recovery it delegates to
|
||||||
// test/port_guard_test.dart. Keep this file thin wiring for that reason.
|
// by test/port_guard_*_test.dart. Keep this file thin wiring for that reason.
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
import 'package:path/path.dart' as p;
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:todo/desktop/browser_launcher.dart';
|
||||||
import 'package:todo/desktop/port_guard.dart';
|
import 'package:todo/desktop/port_guard.dart';
|
||||||
import 'package:todo/desktop/wrapper_server.dart';
|
import 'package:todo/desktop/wrapper_server.dart';
|
||||||
|
|
||||||
/// Port must stay fixed: the browser keys `localStorage` (the GitHub token) and
|
/// The fixed wrapper port; see [kWrapperPort] for why it cannot move.
|
||||||
/// IndexedDB (the notes) by origin, so a different port looks like a different
|
/// Kept in step with lib/sync/desktop_wrapper.
|
||||||
/// app with no token and no notes. Kept in step with lib/sync/desktop_wrapper.
|
const int _port = kWrapperPort;
|
||||||
const _port = 8730;
|
|
||||||
|
|
||||||
/// `errno` for EADDRINUSE. The wrapper is Linux-only (the desktop app is the
|
/// `errno` for EADDRINUSE. The wrapper is Linux-only (the desktop app is the
|
||||||
/// web build served locally), so the numeric value is stable here.
|
/// web build served locally), so the numeric value is stable here.
|
||||||
@ -69,7 +69,7 @@ Future<void> main(List<String> args) async {
|
|||||||
// A bare flag, not a valued option: requiring a dummy value meant passing a
|
// A bare flag, not a valued option: requiring a dummy value meant passing a
|
||||||
// stray positional, which the AOT runtime tries to interpret as a snapshot.
|
// stray positional, which the AOT runtime tries to interpret as a snapshot.
|
||||||
if (!args.contains('--no-browser')) {
|
if (!args.contains('--no-browser')) {
|
||||||
final ranLongEnough = await _launchBrowser(home);
|
final ranLongEnough = await launchBrowser(home);
|
||||||
if (!ranLongEnough) {
|
if (!ranLongEnough) {
|
||||||
// Chrome exits immediately when it hands the URL to an instance that
|
// Chrome exits immediately when it hands the URL to an instance that
|
||||||
// already owns the profile directory (or when a stale SingletonLock is
|
// already owns the profile directory (or when a stale SingletonLock is
|
||||||
@ -113,7 +113,7 @@ Future<bool> _recoverPort(
|
|||||||
String home,
|
String home,
|
||||||
List<String> args,
|
List<String> args,
|
||||||
) async {
|
) async {
|
||||||
final guard = PortGuard(profileDir: _profileDir(home));
|
final guard = PortGuard(profileDir: profileDir(home));
|
||||||
switch (await guard.resolve(_port)) {
|
switch (await guard.resolve(_port)) {
|
||||||
case AbortWithOwner(:final description):
|
case AbortWithOwner(:final description):
|
||||||
stderr.writeln('port $_port is already in use by $description.');
|
stderr.writeln('port $_port is already in use by $description.');
|
||||||
@ -138,7 +138,7 @@ Future<bool> _recoverPort(
|
|||||||
'todo is already running (pid $pid)'
|
'todo is already running (pid $pid)'
|
||||||
'${opening ? '; opening a window.' : '.'}',
|
'${opening ? '; opening a window.' : '.'}',
|
||||||
);
|
);
|
||||||
if (opening) await _launchBrowser(home);
|
if (opening) await launchBrowser(home);
|
||||||
return false;
|
return false;
|
||||||
case ReapThenBind(:final pid):
|
case ReapThenBind(:final pid):
|
||||||
stdout.writeln('clearing a stale todo wrapper (pid $pid) on port $_port');
|
stdout.writeln('clearing a stale todo wrapper (pid $pid) on port $_port');
|
||||||
@ -154,17 +154,6 @@ Future<bool> _recoverPort(
|
|||||||
exit(1);
|
exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Browser profile directory for the desktop app.
|
|
||||||
///
|
|
||||||
/// Must stay stable: the GitHub token (localStorage) and the notes (IndexedDB)
|
|
||||||
/// live inside it, so a changing path silently logs the user out and hides
|
|
||||||
/// their notes. It doubles as the marker for "a window is still attached".
|
|
||||||
String _profileDir(String home) =>
|
|
||||||
p.join(home, '.local', 'share', 'todo-desktop', 'profile');
|
|
||||||
|
|
||||||
/// Launches the app in a Chrome-family browser with a **stable** profile
|
|
||||||
/// directory, since the token and notes live in that profile.
|
|
||||||
/// Returns true when the browser ran long enough to have owned the session.
|
|
||||||
/// Loads the app once headlessly so it provisions its own sync account.
|
/// Loads the app once headlessly so it provisions its own sync account.
|
||||||
///
|
///
|
||||||
/// The account lives in origin-keyed localStorage, which only code running in
|
/// The account lives in origin-keyed localStorage, which only code running in
|
||||||
@ -173,7 +162,7 @@ String _profileDir(String home) =>
|
|||||||
///
|
///
|
||||||
/// Returns whether the account is present afterwards.
|
/// Returns whether the account is present afterwards.
|
||||||
Future<bool> _provisionSyncAccount(String home) async {
|
Future<bool> _provisionSyncAccount(String home) async {
|
||||||
final browser = _findBrowser();
|
final browser = findBrowser();
|
||||||
if (browser.isEmpty) {
|
if (browser.isEmpty) {
|
||||||
stderr.writeln('No Chrome-family browser found; cannot provision.');
|
stderr.writeln('No Chrome-family browser found; cannot provision.');
|
||||||
return false;
|
return false;
|
||||||
@ -185,7 +174,7 @@ Future<bool> _provisionSyncAccount(String home) async {
|
|||||||
final process = await Process.start(browser, [
|
final process = await Process.start(browser, [
|
||||||
'--headless=new',
|
'--headless=new',
|
||||||
'--disable-gpu',
|
'--disable-gpu',
|
||||||
'--user-data-dir=${_profileDir(home)}',
|
'--user-data-dir=${profileDir(home)}',
|
||||||
// Surface the page's own log() output, so a failure inside the app is
|
// Surface the page's own log() output, so a failure inside the app is
|
||||||
// visible in the terminal that started the provisioning run.
|
// visible in the terminal that started the provisioning run.
|
||||||
'--enable-logging=stderr',
|
'--enable-logging=stderr',
|
||||||
@ -203,49 +192,6 @@ Future<bool> _provisionSyncAccount(String home) async {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the first Chrome-family browser on this machine, or ''.
|
|
||||||
String _findBrowser() {
|
|
||||||
// Ordered by preference, and deliberately broad: this machine runs Thorium
|
|
||||||
// behind /opt/google/chrome, and has a policy that uninstalls the `chromium`
|
|
||||||
// package, so assuming any single browser is wrong. TODO_BROWSER overrides.
|
|
||||||
final candidates = [
|
|
||||||
Platform.environment['TODO_BROWSER'] ?? '',
|
|
||||||
'/opt/google/chrome/chrome',
|
|
||||||
'/opt/thorium-browser/thorium-browser',
|
|
||||||
'/usr/bin/google-chrome-stable',
|
|
||||||
'/usr/bin/chromium',
|
|
||||||
'/usr/bin/brave',
|
|
||||||
];
|
|
||||||
return candidates.firstWhere(
|
|
||||||
(path) => path.isNotEmpty && File(path).existsSync(),
|
|
||||||
orElse: () => '',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<bool> _launchBrowser(String home) async {
|
|
||||||
final browser = _findBrowser();
|
|
||||||
if (browser.isEmpty) {
|
|
||||||
stderr.writeln(
|
|
||||||
'No Chrome-family browser found; open '
|
|
||||||
'http://localhost:$_port manually.',
|
|
||||||
);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
final process = await Process.start(browser, [
|
|
||||||
'--app=http://localhost:$_port',
|
|
||||||
'--user-data-dir=${_profileDir(home)}',
|
|
||||||
// Sets WM_CLASS, which the .desktop entry matches on via StartupWMClass.
|
|
||||||
// Without it the window inherits the browser's class and the taskbar shows
|
|
||||||
// a browser icon instead of todo's.
|
|
||||||
'--class=todo',
|
|
||||||
'--no-first-run',
|
|
||||||
]);
|
|
||||||
|
|
||||||
final started = DateTime.now();
|
|
||||||
await process.exitCode;
|
|
||||||
return DateTime.now().difference(started) > const Duration(seconds: 5);
|
|
||||||
}
|
|
||||||
|
|
||||||
String? _argValue(List<String> args, String name) {
|
String? _argValue(List<String> args, String name) {
|
||||||
final index = args.indexOf(name);
|
final index = args.indexOf(name);
|
||||||
if (index == -1 || index + 1 >= args.length) return null;
|
if (index == -1 || index + 1 >= args.length) return null;
|
||||||
|
|||||||
@ -67,212 +67,7 @@ Key readings:
|
|||||||
- The stock counter app behaves identically, so this is not `todo`'s code.
|
- The stock counter app behaves identically, so this is not `todo`'s code.
|
||||||
- Neither renderer choice, nor driver vsync, nor a compositor moves the number.
|
- Neither renderer choice, nor driver vsync, nor a compositor moves the number.
|
||||||
|
|
||||||
## Part 2: the interaction lag is a separate, larger problem
|
---
|
||||||
|
|
||||||
The 60 Hz cap above is real but is **not** what the user is complaining about.
|
Part 2 — the interaction-lag half of this investigation, and the decision that came out of it — is in
|
||||||
Driven by the user directly (synthetic input having proved unreliable), with an
|
[desktop-performance-interaction-lag.md](desktop-performance-interaction-lag.md).
|
||||||
instrument that logs individual outliers plus event-loop blocking rather than
|
|
||||||
per-second percentiles:
|
|
||||||
|
|
||||||
- Stalls are **raster-dominated**. Build (Dart) stays at 0.1-0.9 ms throughout;
|
|
||||||
single frames reach 76 ms of raster at a 1280x1417 window.
|
|
||||||
- The UI isolate does block occasionally (65-101 ms at startup and on some
|
|
||||||
interactions), but this is the minority of the problem.
|
|
||||||
- The user reports the lag is **constant, on every interaction** — which rules
|
|
||||||
out both GitHub sync (periodic) and shader compilation (one-off, warms up).
|
|
||||||
- Impeller/Vulkan halved slow frames (18 → 7) and removed the worst 76 ms
|
|
||||||
spike, but the user perceived **no difference**.
|
|
||||||
|
|
||||||
**Raster cost scales hard with window pixel count**, and the user runs the app
|
|
||||||
fullscreen on the 4K monitor. Measured under a nested X server:
|
|
||||||
|
|
||||||
| Window | Achieved | build p50/p90 | raster p50/p90 |
|
|
||||||
|---|---|---|---|
|
|
||||||
| 1280x720 | 68.5 fps | 0.30 / 0.40 ms | 1.50 / 2.00 ms |
|
|
||||||
| 3840x2160 | 19.9 fps | 0.40 / 0.50 ms | 8.40 / 44.60 ms |
|
|
||||||
|
|
||||||
Those first 4K figures came from plain (software) Xephyr and overstated raster.
|
|
||||||
Repeated **fullscreen on the real 3840x2160 monitor**:
|
|
||||||
|
|
||||||
| Window (real display) | Achieved | build p50 | raster p50 |
|
|
||||||
|---|---|---|---|
|
|
||||||
| 1280x720 | 68.6 fps | 0.30 ms | 1.50 ms |
|
|
||||||
| 3840x2160 | **18.6 fps** | 0.30 ms | **2.70 ms** |
|
|
||||||
|
|
||||||
This is the key result, and it is *not* a rasterisation wall. At 4K each frame
|
|
||||||
costs ~3 ms of a 16.7 ms budget, yet the app achieves 18.6 fps (~54 ms per
|
|
||||||
frame). Roughly **50 ms per frame is dead time** — neither build nor raster.
|
|
||||||
The bottleneck is the presentation/swap path, which is also why Impeller never
|
|
||||||
helped: Impeller changes rasterisation, not presentation.
|
|
||||||
|
|
||||||
### It is Flutter, not todo
|
|
||||||
|
|
||||||
Run through an identical harness, the **stock `flutter create` counter app** —
|
|
||||||
one spinner on a blank Scaffold, zero todo code — collapses the same way:
|
|
||||||
|
|
||||||
| App | 1280x720 | 3840x2160 |
|
|
||||||
|---|---|---|
|
|
||||||
| stock Flutter counter | 68.5 fps | **20.5 fps** |
|
|
||||||
| todo | 68.5 fps | **20.6 fps** |
|
|
||||||
|
|
||||||
Flutter's Linux embedder manages ~20 fps rendering a **blank screen** at 4K.
|
|
||||||
Build time is 0.1-0.4 ms throughout. No application-level change can fix this.
|
|
||||||
|
|
||||||
Size curve (harness), showing the cliff begins at 1440p:
|
|
||||||
|
|
||||||
| size | Mpx | fps | frame cost | dead time |
|
|
||||||
|---|---|---|---|---|
|
|
||||||
| 1280x720 | 0.92 | 68.5 | 1.70 ms | 12.9 ms |
|
|
||||||
| 1920x1080 | 2.07 | 60.5 | 2.40 ms | 14.1 ms |
|
|
||||||
| 2560x1440 | 3.69 | 40.3 | 3.70 ms | 21.1 ms |
|
|
||||||
| 3840x2160 | 8.29 | 20.6 | 8.80 ms | 39.8 ms |
|
|
||||||
|
|
||||||
Related upstream reports:
|
|
||||||
[#66463](https://github.com/flutter/flutter/issues/66463) (Linux desktop failure
|
|
||||||
based on window size on 4K monitors),
|
|
||||||
[#88996](https://github.com/flutter/flutter/issues/88996) (high frame latency on
|
|
||||||
Linux desktop).
|
|
||||||
|
|
||||||
## Test harness (for iterating without taking over the user's screens)
|
|
||||||
|
|
||||||
`Xephyr -glamor` runs a nested X server that renders through OpenGL on the real
|
|
||||||
GPU. Validated against ground truth: it reproduced the 4K symptom at 19.8 fps
|
|
||||||
versus the real display's 18.6 fps. It inflates raster attribution (7.2 ms vs
|
|
||||||
2.7 ms real), so use it for pass/fail, **not** for attributing where time goes.
|
|
||||||
|
|
||||||
Plain `Xephyr` without `-glamor` is a software X server and is useless here: it
|
|
||||||
copies a ~33 MB framebuffer per frame at 4K and dominates the measurement.
|
|
||||||
|
|
||||||
**The harness is validated for the Flutter desktop embedder only.** A Chrome
|
|
||||||
run inside it reported 10 fps at 4K; measuring the same page on the real display
|
|
||||||
gave 142.9 fps, confirming that number was a harness artifact (Chrome disables
|
|
||||||
GPU acceleration on an unrecognised nested display). Never benchmark a browser
|
|
||||||
inside it.
|
|
||||||
|
|
||||||
## The decisive comparison: same content, same machine, real 4K display
|
|
||||||
|
|
||||||
The identical spinner probe, rendered at 3840x2160 on the real monitor:
|
|
||||||
|
|
||||||
| Renderer | Achieved at 4K |
|
|
||||||
|---|---|
|
|
||||||
| Flutter **Linux desktop embedder** | **20.5 fps** |
|
|
||||||
| Flutter **Web (CanvasKit) in Chrome** | **142.9 fps** (cadence p50 7.00 ms) |
|
|
||||||
|
|
||||||
A **7x difference**, with the same framework and the same Dart code. This is not
|
|
||||||
a hardware limit, a driver limit, or an application limit — it is specific to
|
|
||||||
Flutter's Linux desktop embedder. It validates the web route at the size that
|
|
||||||
actually matters.
|
|
||||||
|
|
||||||
## Why the 60 Hz cap exists
|
|
||||||
|
|
||||||
`libflutter_linux_gtk.so` imports `gdk_monitor_get_refresh_rate` (and GTK
|
|
||||||
correctly reports 144.00 Hz here — verified independently), but imports **no**
|
|
||||||
`gdk_frame_clock_*` symbols; the engine falls back to a fixed 60 FPS vsync
|
|
||||||
waiter.
|
|
||||||
|
|
||||||
This is a known, open upstream limitation:
|
|
||||||
[flutter/flutter#183703 — "[Proposal] Support high refresh rate (>60) on
|
|
||||||
Linux"](https://github.com/flutter/flutter/issues/183703). Opened 2026-03-14,
|
|
||||||
labelled **P2**, **no assignee, no linked PR, no milestone**. Linux is the last
|
|
||||||
Flutter platform without >60 Hz support. Related:
|
|
||||||
[#93058](https://github.com/flutter/flutter/issues/93058) (Windows, since
|
|
||||||
fixed), [#49757](https://github.com/flutter/flutter/issues/49757).
|
|
||||||
|
|
||||||
## Implication for the "switch technology" question
|
|
||||||
|
|
||||||
A rewrite in another language is **not** warranted by the evidence. The same
|
|
||||||
Flutter framework and the same Dart code reach ~143 fps on this exact machine
|
|
||||||
when built for web and run in Chrome. Only the Linux *desktop embedder* is
|
|
||||||
capped.
|
|
||||||
|
|
||||||
The leading candidate is therefore **shipping the desktop app as a Flutter web
|
|
||||||
build in a Chrome `--app` window**, reusing the UI and domain code.
|
|
||||||
|
|
||||||
**Validated at 4K on the real display: 142.9 fps vs the desktop embedder's
|
|
||||||
20.5 fps on identical content.** That settles the renderer question.
|
|
||||||
|
|
||||||
What remains unproven is todo's *own* widget tree on web: the probe is a
|
|
||||||
spinner, and web CanvasKit raster plus WASM/JS build costs differ from the
|
|
||||||
desktop's 0.30/1.50 ms. Given desktop build time is only 0.3 ms and the web
|
|
||||||
renderer has 7x the headroom, this is very likely fine — but the proof-of-
|
|
||||||
concept should build the actual app and re-measure before the port is finished.
|
|
||||||
|
|
||||||
What is reused is the UI and domain logic. The platform-adapter layer needs web
|
|
||||||
variants throughout: persistence durability under a browser profile, token
|
|
||||||
storage, device auth, sync-on-background (Page Visibility API), and the
|
|
||||||
launch mechanism (local server vs `file://`).
|
|
||||||
|
|
||||||
Port surface (the storage seam is small, because `crdt_sync_dart` was designed
|
|
||||||
for it):
|
|
||||||
|
|
||||||
- `LogStore` is deliberately `dart:io`-free and documented as web-usable;
|
|
||||||
`FileLogPersistence` is already isolated behind the `crdt_sync_io.dart`
|
|
||||||
entrypoint. `LogPersistence` is a two-method interface (`read()` /
|
|
||||||
`write(String)`), so a web implementation over IndexedDB/localStorage is
|
|
||||||
roughly 15 lines.
|
|
||||||
- `github_client.dart` has **no** `dart:io` and uses `package:http`; the GitHub
|
|
||||||
REST API sends permissive CORS headers, so sync works from a browser origin.
|
|
||||||
- `sqlite_crdt`/`sqflite_common_ffi` remain only for the one-time legacy DB
|
|
||||||
migration (`note_repository.dart:350`), which does not apply on web and can be
|
|
||||||
skipped behind `kIsWeb`.
|
|
||||||
- `path_provider` is only used to choose the file path for `FileLogPersistence`;
|
|
||||||
unnecessary on web.
|
|
||||||
- `shared_preferences`, `url_launcher`, `share_plus`, `file_selector`,
|
|
||||||
`flutter_secure_storage` all have web implementations.
|
|
||||||
|
|
||||||
### Known costs of the web route (both are security regressions)
|
|
||||||
|
|
||||||
1. **The token loses the OS keystore.** Commit `9841aec` deliberately moved the
|
|
||||||
GitHub token off plaintext and into the OS keyring via
|
|
||||||
`flutter_secure_storage`. A Chrome `--app` build cannot reach the keyring;
|
|
||||||
`flutter_secure_storage` on web falls back to WebCrypto-wrapped
|
|
||||||
`localStorage`. That is materially weaker than what is shipping today and
|
|
||||||
partially undoes that commit.
|
|
||||||
2. **Device-flow auth breaks.** GitHub's OAuth device-flow endpoints
|
|
||||||
(`github.com/login/device/code`) do not send CORS headers, so one-tap device
|
|
||||||
auth will not work from a browser origin. The settings screen's
|
|
||||||
paste-a-personal-access-token path would have to become the desktop auth
|
|
||||||
route — which also means a long-lived PAT living in the weaker storage above.
|
|
||||||
|
|
||||||
These two stack, and they are the strongest argument against the web route.
|
|
||||||
|
|
||||||
## Agreed plan (decided 2026-07-20)
|
|
||||||
|
|
||||||
The desktop app moves to a Flutter **web** build launched in Chrome. Decisions
|
|
||||||
taken, so the next session can start from here:
|
|
||||||
|
|
||||||
- **Auth:** simple PAT pasted into `localStorage` (via
|
|
||||||
`flutter_secure_storage_web`). The local-helper design that would have kept
|
|
||||||
the OS keyring and device-flow auth was considered and **rejected** for
|
|
||||||
simplicity. Consequences accepted: the token is no longer in the keyring, and
|
|
||||||
the AES-GCM wrapping is obfuscation only (the wrap key sits in the same
|
|
||||||
`localStorage`).
|
|
||||||
- Requires a **classic PAT with "No expiration"** to be a one-time paste.
|
|
||||||
- The launcher must pin a **fixed port** and a **fixed `--user-data-dir`**,
|
|
||||||
and call `navigator.storage.persist()`. Any of those changing loses the
|
|
||||||
token: `localStorage` is keyed by origin and lives in the Chrome profile.
|
|
||||||
- **The Linux desktop build is deleted**, not kept as a fallback. (Android is
|
|
||||||
unaffected and remains a normal Flutter mobile build.)
|
|
||||||
- **Launch:** a wrapper script serves the web build on a fixed port and opens
|
|
||||||
Chrome with `--app=http://localhost:<port>`.
|
|
||||||
- **Done-condition:** the real todo app, fullscreen at 4K, sustains **>=100 fps**
|
|
||||||
while scrolling the notes list, and sync works against `kuhyx/syncs`.
|
|
||||||
|
|
||||||
Still to be specified before coding: the `WebLogPersistence` implementation,
|
|
||||||
what replaces `path_provider`/`sqflite` on web (the legacy sqlite migration path
|
|
||||||
at `note_repository.dart:350` does not apply), packaging/`install_arch.sh`
|
|
||||||
changes, and how the desktop entry launches the wrapper.
|
|
||||||
|
|
||||||
## Alternatives, if the web route is rejected
|
|
||||||
|
|
||||||
Ranked by cost. All require re-implementing the UI, and the two non-Dart options
|
|
||||||
also require a third `crdt_sync` implementation (it exists today only in Python
|
|
||||||
and Dart).
|
|
||||||
|
|
||||||
1. **Accept 60 fps.** Zero cost. The app is genuinely smooth *at* 60.
|
|
||||||
2. **Qt 6 / QML (C++).** Vulkan RHI, real 144 Hz, best NVIDIA/X11 record. Weeks.
|
|
||||||
3. **Rust + Slint.** Lightweight, but the highest total cost.
|
|
||||||
|
|
||||||
Not recommended: **Tauri** — on Linux it renders via WebKitGTK, which has its
|
|
||||||
own NVIDIA/X11 DMABUF rendering bugs; it trades one renderer problem for
|
|
||||||
another.
|
|
||||||
|
|||||||
216
docs/desktop-performance-interaction-lag.md
Normal file
216
docs/desktop-performance-interaction-lag.md
Normal file
@ -0,0 +1,216 @@
|
|||||||
|
# Linux desktop performance, part 2: interaction lag
|
||||||
|
|
||||||
|
The second half of the investigation started in
|
||||||
|
[desktop-performance-findings.md](desktop-performance-findings.md), which
|
||||||
|
covers frame rate. Split only to keep each file under the 250-line cap;
|
||||||
|
the author signposted the two parts explicitly.
|
||||||
|
|
||||||
|
## Part 2: the interaction lag is a separate, larger problem
|
||||||
|
|
||||||
|
The 60 Hz cap above is real but is **not** what the user is complaining about.
|
||||||
|
Driven by the user directly (synthetic input having proved unreliable), with an
|
||||||
|
instrument that logs individual outliers plus event-loop blocking rather than
|
||||||
|
per-second percentiles:
|
||||||
|
|
||||||
|
- Stalls are **raster-dominated**. Build (Dart) stays at 0.1-0.9 ms throughout;
|
||||||
|
single frames reach 76 ms of raster at a 1280x1417 window.
|
||||||
|
- The UI isolate does block occasionally (65-101 ms at startup and on some
|
||||||
|
interactions), but this is the minority of the problem.
|
||||||
|
- The user reports the lag is **constant, on every interaction** — which rules
|
||||||
|
out both GitHub sync (periodic) and shader compilation (one-off, warms up).
|
||||||
|
- Impeller/Vulkan halved slow frames (18 → 7) and removed the worst 76 ms
|
||||||
|
spike, but the user perceived **no difference**.
|
||||||
|
|
||||||
|
**Raster cost scales hard with window pixel count**, and the user runs the app
|
||||||
|
fullscreen on the 4K monitor. Measured under a nested X server:
|
||||||
|
|
||||||
|
| Window | Achieved | build p50/p90 | raster p50/p90 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1280x720 | 68.5 fps | 0.30 / 0.40 ms | 1.50 / 2.00 ms |
|
||||||
|
| 3840x2160 | 19.9 fps | 0.40 / 0.50 ms | 8.40 / 44.60 ms |
|
||||||
|
|
||||||
|
Those first 4K figures came from plain (software) Xephyr and overstated raster.
|
||||||
|
Repeated **fullscreen on the real 3840x2160 monitor**:
|
||||||
|
|
||||||
|
| Window (real display) | Achieved | build p50 | raster p50 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1280x720 | 68.6 fps | 0.30 ms | 1.50 ms |
|
||||||
|
| 3840x2160 | **18.6 fps** | 0.30 ms | **2.70 ms** |
|
||||||
|
|
||||||
|
This is the key result, and it is *not* a rasterisation wall. At 4K each frame
|
||||||
|
costs ~3 ms of a 16.7 ms budget, yet the app achieves 18.6 fps (~54 ms per
|
||||||
|
frame). Roughly **50 ms per frame is dead time** — neither build nor raster.
|
||||||
|
The bottleneck is the presentation/swap path, which is also why Impeller never
|
||||||
|
helped: Impeller changes rasterisation, not presentation.
|
||||||
|
|
||||||
|
### It is Flutter, not todo
|
||||||
|
|
||||||
|
Run through an identical harness, the **stock `flutter create` counter app** —
|
||||||
|
one spinner on a blank Scaffold, zero todo code — collapses the same way:
|
||||||
|
|
||||||
|
| App | 1280x720 | 3840x2160 |
|
||||||
|
|---|---|---|
|
||||||
|
| stock Flutter counter | 68.5 fps | **20.5 fps** |
|
||||||
|
| todo | 68.5 fps | **20.6 fps** |
|
||||||
|
|
||||||
|
Flutter's Linux embedder manages ~20 fps rendering a **blank screen** at 4K.
|
||||||
|
Build time is 0.1-0.4 ms throughout. No application-level change can fix this.
|
||||||
|
|
||||||
|
Size curve (harness), showing the cliff begins at 1440p:
|
||||||
|
|
||||||
|
| size | Mpx | fps | frame cost | dead time |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1280x720 | 0.92 | 68.5 | 1.70 ms | 12.9 ms |
|
||||||
|
| 1920x1080 | 2.07 | 60.5 | 2.40 ms | 14.1 ms |
|
||||||
|
| 2560x1440 | 3.69 | 40.3 | 3.70 ms | 21.1 ms |
|
||||||
|
| 3840x2160 | 8.29 | 20.6 | 8.80 ms | 39.8 ms |
|
||||||
|
|
||||||
|
Related upstream reports:
|
||||||
|
[#66463](https://github.com/flutter/flutter/issues/66463) (Linux desktop failure
|
||||||
|
based on window size on 4K monitors),
|
||||||
|
[#88996](https://github.com/flutter/flutter/issues/88996) (high frame latency on
|
||||||
|
Linux desktop).
|
||||||
|
|
||||||
|
## Test harness (for iterating without taking over the user's screens)
|
||||||
|
|
||||||
|
`Xephyr -glamor` runs a nested X server that renders through OpenGL on the real
|
||||||
|
GPU. Validated against ground truth: it reproduced the 4K symptom at 19.8 fps
|
||||||
|
versus the real display's 18.6 fps. It inflates raster attribution (7.2 ms vs
|
||||||
|
2.7 ms real), so use it for pass/fail, **not** for attributing where time goes.
|
||||||
|
|
||||||
|
Plain `Xephyr` without `-glamor` is a software X server and is useless here: it
|
||||||
|
copies a ~33 MB framebuffer per frame at 4K and dominates the measurement.
|
||||||
|
|
||||||
|
**The harness is validated for the Flutter desktop embedder only.** A Chrome
|
||||||
|
run inside it reported 10 fps at 4K; measuring the same page on the real display
|
||||||
|
gave 142.9 fps, confirming that number was a harness artifact (Chrome disables
|
||||||
|
GPU acceleration on an unrecognised nested display). Never benchmark a browser
|
||||||
|
inside it.
|
||||||
|
|
||||||
|
## The decisive comparison: same content, same machine, real 4K display
|
||||||
|
|
||||||
|
The identical spinner probe, rendered at 3840x2160 on the real monitor:
|
||||||
|
|
||||||
|
| Renderer | Achieved at 4K |
|
||||||
|
|---|---|
|
||||||
|
| Flutter **Linux desktop embedder** | **20.5 fps** |
|
||||||
|
| Flutter **Web (CanvasKit) in Chrome** | **142.9 fps** (cadence p50 7.00 ms) |
|
||||||
|
|
||||||
|
A **7x difference**, with the same framework and the same Dart code. This is not
|
||||||
|
a hardware limit, a driver limit, or an application limit — it is specific to
|
||||||
|
Flutter's Linux desktop embedder. It validates the web route at the size that
|
||||||
|
actually matters.
|
||||||
|
|
||||||
|
## Why the 60 Hz cap exists
|
||||||
|
|
||||||
|
`libflutter_linux_gtk.so` imports `gdk_monitor_get_refresh_rate` (and GTK
|
||||||
|
correctly reports 144.00 Hz here — verified independently), but imports **no**
|
||||||
|
`gdk_frame_clock_*` symbols; the engine falls back to a fixed 60 FPS vsync
|
||||||
|
waiter.
|
||||||
|
|
||||||
|
This is a known, open upstream limitation:
|
||||||
|
[flutter/flutter#183703 — "[Proposal] Support high refresh rate (>60) on
|
||||||
|
Linux"](https://github.com/flutter/flutter/issues/183703). Opened 2026-03-14,
|
||||||
|
labelled **P2**, **no assignee, no linked PR, no milestone**. Linux is the last
|
||||||
|
Flutter platform without >60 Hz support. Related:
|
||||||
|
[#93058](https://github.com/flutter/flutter/issues/93058) (Windows, since
|
||||||
|
fixed), [#49757](https://github.com/flutter/flutter/issues/49757).
|
||||||
|
|
||||||
|
## Implication for the "switch technology" question
|
||||||
|
|
||||||
|
A rewrite in another language is **not** warranted by the evidence. The same
|
||||||
|
Flutter framework and the same Dart code reach ~143 fps on this exact machine
|
||||||
|
when built for web and run in Chrome. Only the Linux *desktop embedder* is
|
||||||
|
capped.
|
||||||
|
|
||||||
|
The leading candidate is therefore **shipping the desktop app as a Flutter web
|
||||||
|
build in a Chrome `--app` window**, reusing the UI and domain code.
|
||||||
|
|
||||||
|
**Validated at 4K on the real display: 142.9 fps vs the desktop embedder's
|
||||||
|
20.5 fps on identical content.** That settles the renderer question.
|
||||||
|
|
||||||
|
What remains unproven is todo's *own* widget tree on web: the probe is a
|
||||||
|
spinner, and web CanvasKit raster plus WASM/JS build costs differ from the
|
||||||
|
desktop's 0.30/1.50 ms. Given desktop build time is only 0.3 ms and the web
|
||||||
|
renderer has 7x the headroom, this is very likely fine — but the proof-of-
|
||||||
|
concept should build the actual app and re-measure before the port is finished.
|
||||||
|
|
||||||
|
What is reused is the UI and domain logic. The platform-adapter layer needs web
|
||||||
|
variants throughout: persistence durability under a browser profile, token
|
||||||
|
storage, device auth, sync-on-background (Page Visibility API), and the
|
||||||
|
launch mechanism (local server vs `file://`).
|
||||||
|
|
||||||
|
Port surface (the storage seam is small, because `crdt_sync_dart` was designed
|
||||||
|
for it):
|
||||||
|
|
||||||
|
- `LogStore` is deliberately `dart:io`-free and documented as web-usable;
|
||||||
|
`FileLogPersistence` is already isolated behind the `crdt_sync_io.dart`
|
||||||
|
entrypoint. `LogPersistence` is a two-method interface (`read()` /
|
||||||
|
`write(String)`), so a web implementation over IndexedDB/localStorage is
|
||||||
|
roughly 15 lines.
|
||||||
|
- `github_client.dart` has **no** `dart:io` and uses `package:http`; the GitHub
|
||||||
|
REST API sends permissive CORS headers, so sync works from a browser origin.
|
||||||
|
- `sqlite_crdt`/`sqflite_common_ffi` remain only for the one-time legacy DB
|
||||||
|
migration (`note_repository.dart:350`), which does not apply on web and can be
|
||||||
|
skipped behind `kIsWeb`.
|
||||||
|
- `path_provider` is only used to choose the file path for `FileLogPersistence`;
|
||||||
|
unnecessary on web.
|
||||||
|
- `shared_preferences`, `url_launcher`, `share_plus`, `file_selector`,
|
||||||
|
`flutter_secure_storage` all have web implementations.
|
||||||
|
|
||||||
|
### Known costs of the web route (both are security regressions)
|
||||||
|
|
||||||
|
1. **The token loses the OS keystore.** Commit `9841aec` deliberately moved the
|
||||||
|
GitHub token off plaintext and into the OS keyring via
|
||||||
|
`flutter_secure_storage`. A Chrome `--app` build cannot reach the keyring;
|
||||||
|
`flutter_secure_storage` on web falls back to WebCrypto-wrapped
|
||||||
|
`localStorage`. That is materially weaker than what is shipping today and
|
||||||
|
partially undoes that commit.
|
||||||
|
2. **Device-flow auth breaks.** GitHub's OAuth device-flow endpoints
|
||||||
|
(`github.com/login/device/code`) do not send CORS headers, so one-tap device
|
||||||
|
auth will not work from a browser origin. The settings screen's
|
||||||
|
paste-a-personal-access-token path would have to become the desktop auth
|
||||||
|
route — which also means a long-lived PAT living in the weaker storage above.
|
||||||
|
|
||||||
|
These two stack, and they are the strongest argument against the web route.
|
||||||
|
|
||||||
|
## Agreed plan (decided 2026-07-20)
|
||||||
|
|
||||||
|
The desktop app moves to a Flutter **web** build launched in Chrome. Decisions
|
||||||
|
taken, so the next session can start from here:
|
||||||
|
|
||||||
|
- **Auth:** simple PAT pasted into `localStorage` (via
|
||||||
|
`flutter_secure_storage_web`). The local-helper design that would have kept
|
||||||
|
the OS keyring and device-flow auth was considered and **rejected** for
|
||||||
|
simplicity. Consequences accepted: the token is no longer in the keyring, and
|
||||||
|
the AES-GCM wrapping is obfuscation only (the wrap key sits in the same
|
||||||
|
`localStorage`).
|
||||||
|
- Requires a **classic PAT with "No expiration"** to be a one-time paste.
|
||||||
|
- The launcher must pin a **fixed port** and a **fixed `--user-data-dir`**,
|
||||||
|
and call `navigator.storage.persist()`. Any of those changing loses the
|
||||||
|
token: `localStorage` is keyed by origin and lives in the Chrome profile.
|
||||||
|
- **The Linux desktop build is deleted**, not kept as a fallback. (Android is
|
||||||
|
unaffected and remains a normal Flutter mobile build.)
|
||||||
|
- **Launch:** a wrapper script serves the web build on a fixed port and opens
|
||||||
|
Chrome with `--app=http://localhost:<port>`.
|
||||||
|
- **Done-condition:** the real todo app, fullscreen at 4K, sustains **>=100 fps**
|
||||||
|
while scrolling the notes list, and sync works against `kuhyx/syncs`.
|
||||||
|
|
||||||
|
Still to be specified before coding: the `WebLogPersistence` implementation,
|
||||||
|
what replaces `path_provider`/`sqflite` on web (the legacy sqlite migration path
|
||||||
|
at `note_repository.dart:350` does not apply), packaging/`install_arch.sh`
|
||||||
|
changes, and how the desktop entry launches the wrapper.
|
||||||
|
|
||||||
|
## Alternatives, if the web route is rejected
|
||||||
|
|
||||||
|
Ranked by cost. All require re-implementing the UI, and the two non-Dart options
|
||||||
|
also require a third `crdt_sync` implementation (it exists today only in Python
|
||||||
|
and Dart).
|
||||||
|
|
||||||
|
1. **Accept 60 fps.** Zero cost. The app is genuinely smooth *at* 60.
|
||||||
|
2. **Qt 6 / QML (C++).** Vulkan RHI, real 144 Hz, best NVIDIA/X11 record. Weeks.
|
||||||
|
3. **Rust + Slint.** Lightweight, but the highest total cost.
|
||||||
|
|
||||||
|
Not recommended: **Tauri** — on Linux it renders via WebKitGTK, which has its
|
||||||
|
own NVIDIA/X11 DMABUF rendering bugs; it trades one renderer problem for
|
||||||
|
another.
|
||||||
144
docs/flutter-rules-design.md
Normal file
144
docs/flutter-rules-design.md
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
# Flutter AI rules — Colour, type, documentation and accessibility
|
||||||
|
|
||||||
|
Colour schemes, fonts, dartdoc conventions and accessibility.
|
||||||
|
|
||||||
|
_Verbatim from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md), split across four files only to keep each under the repo's 250-line
|
||||||
|
cap. Re-fetch periodically to stay current; do not hand-edit._
|
||||||
|
|
||||||
|
#### Contrast Ratios
|
||||||
|
|
||||||
|
* **WCAG Guidelines:** Aim to meet the Web Content Accessibility Guidelines
|
||||||
|
(WCAG) 2.1 standards.
|
||||||
|
* **Minimum Contrast:**
|
||||||
|
* **Normal Text:** A contrast ratio of at least **4.5:1**.
|
||||||
|
* **Large Text:** (18pt or 14pt bold) A contrast ratio of at least **3:1**.
|
||||||
|
|
||||||
|
#### Palette Selection
|
||||||
|
|
||||||
|
* **Primary, Secondary, and Accent:** Define a clear color hierarchy.
|
||||||
|
* **The 60-30-10 Rule:** A classic design rule for creating a balanced color scheme.
|
||||||
|
* **60%** Primary/Neutral Color (Dominant)
|
||||||
|
* **30%** Secondary Color
|
||||||
|
* **10%** Accent Color
|
||||||
|
|
||||||
|
#### Complementary Colors
|
||||||
|
|
||||||
|
* **Use with Caution:** They can be visually jarring if overused.
|
||||||
|
* **Best Use Cases:** They are excellent for accent colors to make specific
|
||||||
|
elements pop, but generally poor for text and background pairings as they can
|
||||||
|
cause eye strain.
|
||||||
|
|
||||||
|
#### Example Palette
|
||||||
|
|
||||||
|
* **Primary:** #0D47A1 (Dark Blue)
|
||||||
|
* **Secondary:** #1976D2 (Medium Blue)
|
||||||
|
* **Accent:** #FFC107 (Amber)
|
||||||
|
* **Neutral/Text:** #212121 (Almost Black)
|
||||||
|
* **Background:** #FEFEFE (Almost White)
|
||||||
|
|
||||||
|
### Font Best Practices
|
||||||
|
|
||||||
|
#### Font Selection
|
||||||
|
|
||||||
|
* **Limit Font Families:** Stick to one or two font families for the entire
|
||||||
|
application.
|
||||||
|
* **Prioritize Legibility:** Choose fonts that are easy to read on screens of
|
||||||
|
all sizes. Sans-serif fonts are generally preferred for UI body text.
|
||||||
|
* **System Fonts:** Consider using platform-native system fonts.
|
||||||
|
* **Google Fonts:** For a wide selection of open-source fonts, use the
|
||||||
|
`google_fonts` package.
|
||||||
|
|
||||||
|
#### Hierarchy and Scale
|
||||||
|
|
||||||
|
* **Establish a Scale:** Define a set of font sizes for different text elements
|
||||||
|
(e.g., headlines, titles, body text, captions).
|
||||||
|
* **Use Font Weight:** Differentiate text effectively using font weights.
|
||||||
|
* **Color and Opacity:** Use color and opacity to de-emphasize less important
|
||||||
|
text.
|
||||||
|
|
||||||
|
#### Readability
|
||||||
|
|
||||||
|
* **Line Height (Leading):** Set an appropriate line height, typically **1.4x to
|
||||||
|
1.6x** the font size.
|
||||||
|
* **Line Length:** For body text, aim for a line length of **45-75 characters**.
|
||||||
|
* **Avoid All Caps:** Do not use all caps for long-form text.
|
||||||
|
|
||||||
|
#### Example Typographic Scale
|
||||||
|
|
||||||
|
```dart
|
||||||
|
// In your ThemeData
|
||||||
|
textTheme: const TextTheme(
|
||||||
|
displayLarge: TextStyle(fontSize: 57.0, fontWeight: FontWeight.bold),
|
||||||
|
titleLarge: TextStyle(fontSize: 22.0, fontWeight: FontWeight.bold),
|
||||||
|
bodyLarge: TextStyle(fontSize: 16.0, height: 1.5),
|
||||||
|
bodyMedium: TextStyle(fontSize: 14.0, height: 1.4),
|
||||||
|
labelSmall: TextStyle(fontSize: 11.0, color: Colors.grey),
|
||||||
|
),
|
||||||
|
```
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
* **`dartdoc`:** Write `dartdoc`-style comments for all public APIs.
|
||||||
|
|
||||||
|
|
||||||
|
#### Documentation Philosophy
|
||||||
|
|
||||||
|
* **Comment wisely:** Use comments to explain why the code is written a certain
|
||||||
|
way, not what the code does. The code itself should be self-explanatory.
|
||||||
|
* **Document for the user:** Write documentation with the reader in mind. If you
|
||||||
|
had a question and found the answer, add it to the documentation where you
|
||||||
|
first looked. This ensures the documentation answers real-world questions.
|
||||||
|
* **No useless documentation:** If the documentation only restates the obvious
|
||||||
|
from the code's name, it's not helpful. Good documentation provides context
|
||||||
|
and explains what isn't immediately apparent.
|
||||||
|
* **Consistency is key:** Use consistent terminology throughout your
|
||||||
|
documentation.
|
||||||
|
|
||||||
|
#### Commenting Style
|
||||||
|
|
||||||
|
* **Use `///` for doc comments:** This allows documentation generation tools to
|
||||||
|
pick them up.
|
||||||
|
* **Start with a single-sentence summary:** The first sentence should be a
|
||||||
|
concise, user-centric summary ending with a period.
|
||||||
|
* **Separate the summary:** Add a blank line after the first sentence to create
|
||||||
|
a separate paragraph. This helps tools create better summaries.
|
||||||
|
* **Avoid redundancy:** Don't repeat information that's obvious from the code's
|
||||||
|
context, like the class name or signature.
|
||||||
|
* **Don't document both getter and setter:** For properties with both, only
|
||||||
|
document one. The documentation tool will treat them as a single field.
|
||||||
|
|
||||||
|
#### Writing Style
|
||||||
|
|
||||||
|
* **Be brief:** Write concisely.
|
||||||
|
* **Avoid jargon and acronyms:** Don't use abbreviations unless they are widely
|
||||||
|
understood.
|
||||||
|
* **Use Markdown sparingly:** Avoid excessive markdown and never use HTML for
|
||||||
|
formatting.
|
||||||
|
* **Use backticks for code:** Enclose code blocks in backtick fences, and
|
||||||
|
specify the language.
|
||||||
|
|
||||||
|
#### What to Document
|
||||||
|
|
||||||
|
* **Public APIs are a priority:** Always document public APIs.
|
||||||
|
* **Consider private APIs:** It's a good idea to document private APIs as well.
|
||||||
|
* **Library-level comments are helpful:** Consider adding a doc comment at the
|
||||||
|
library level to provide a general overview.
|
||||||
|
* **Include code samples:** Where appropriate, add code samples to illustrate usage.
|
||||||
|
* **Explain parameters, return values, and exceptions:** Use prose to describe
|
||||||
|
what a function expects, what it returns, and what errors it might throw.
|
||||||
|
* **Place doc comments before annotations:** Documentation should come before
|
||||||
|
any metadata annotations.
|
||||||
|
|
||||||
|
### Accessibility (A11Y)
|
||||||
|
Implement accessibility features to empower all users, assuming a wide variety
|
||||||
|
of users with different physical abilities, mental abilities, age groups,
|
||||||
|
education levels, and learning styles.
|
||||||
|
|
||||||
|
* **Color Contrast:** Ensure text has a contrast ratio of at least **4.5:1**
|
||||||
|
against its background.
|
||||||
|
* **Dynamic Text Scaling:** Test your UI to ensure it remains usable when users
|
||||||
|
increase the system font size.
|
||||||
|
* **Semantic Labels:** Use the `Semantics` widget to provide clear, descriptive
|
||||||
|
labels for UI elements.
|
||||||
|
* **Screen Reader Testing:** Regularly test your app with TalkBack (Android) and
|
||||||
|
VoiceOver (iOS).
|
||||||
163
docs/flutter-rules-language.md
Normal file
163
docs/flutter-rules-language.md
Normal file
@ -0,0 +1,163 @@
|
|||||||
|
# Flutter AI rules — language, style and architecture
|
||||||
|
|
||||||
|
Dart/Flutter style, package management, code quality, and how a project is laid out.
|
||||||
|
|
||||||
|
_Verbatim from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md), split across four files only to keep each under the repo's 250-line
|
||||||
|
cap. Re-fetch periodically to stay current; do not hand-edit._
|
||||||
|
|
||||||
|
### Interaction Guidelines
|
||||||
|
* **User Persona:** Assume the user is familiar with programming concepts but
|
||||||
|
may be new to Dart.
|
||||||
|
* **Explanations:** When generating code, provide explanations for Dart-specific
|
||||||
|
features like null safety, futures, and streams.
|
||||||
|
* **Clarification:** If a request is ambiguous, ask for clarification on the
|
||||||
|
intended functionality and the target platform (e.g., command-line, web,
|
||||||
|
server).
|
||||||
|
* **Dependencies:** When suggesting new dependencies from `pub.dev`, explain
|
||||||
|
their benefits.
|
||||||
|
* **Formatting:** Use the `dart_format` tool to ensure consistent code
|
||||||
|
formatting.
|
||||||
|
* **Fixes:** Use the `dart_fix` tool to automatically fix many common errors,
|
||||||
|
and to help code conform to configured analysis options.
|
||||||
|
* **Linting:** Use the Dart linter with a recommended set of rules to catch
|
||||||
|
common issues. Use the `analyze_files` tool to run the linter.
|
||||||
|
|
||||||
|
### Project Structure
|
||||||
|
* **Standard Structure:** Assumes a standard Flutter project structure with
|
||||||
|
`lib/main.dart` as the primary application entry point.
|
||||||
|
|
||||||
|
### Flutter style guide
|
||||||
|
* **SOLID Principles:** Apply SOLID principles throughout the codebase.
|
||||||
|
* **Concise and Declarative:** Write concise, modern, technical Dart code.
|
||||||
|
Prefer functional and declarative patterns.
|
||||||
|
* **Composition over Inheritance:** Favor composition for building complex
|
||||||
|
widgets and logic.
|
||||||
|
* **Immutability:** Prefer immutable data structures. Widgets (especially
|
||||||
|
`StatelessWidget`) should be immutable.
|
||||||
|
* **State Management:** Separate ephemeral state and app state. Use a state
|
||||||
|
management solution for app state to handle the separation of concerns.
|
||||||
|
* **Widgets are for UI:** Everything in Flutter's UI is a widget. Compose
|
||||||
|
complex UIs from smaller, reusable widgets.
|
||||||
|
* **Navigation:** Use a modern routing package like `auto_route` or `go_router`.
|
||||||
|
For more guidelines around navigation, see the section on [routing](#routing).
|
||||||
|
|
||||||
|
### Package Management
|
||||||
|
* **Pub Tool:** To manage packages, use the `pub` tool, if available.
|
||||||
|
* **External Packages:** If a new feature requires an external package, use the
|
||||||
|
`pub_dev_search` tool, if it is available. Otherwise, identify the most
|
||||||
|
suitable and stable package from pub.dev.
|
||||||
|
* **Adding Dependencies:** To add a regular dependency, use the `pub` tool, if
|
||||||
|
it is available. Otherwise, run `flutter pub add <package_name>`.
|
||||||
|
* **Adding Dev Dependencies:** To add a development dependency, use the `pub`
|
||||||
|
tool, if it is available, with `dev:<package name>`. Otherwise, run `flutter
|
||||||
|
pub add dev:<package_name>`.
|
||||||
|
* **Dependency Overrides:** To add a dependency override, use the `pub` tool, if
|
||||||
|
it is available, with `override:<package name>:1.0.0`. Otherwise, run `flutter
|
||||||
|
pub add override:<package_name>:1.0.0`.
|
||||||
|
* **Removing Dependencies:** To remove a dependency, use the `pub` tool, if it
|
||||||
|
is available. Otherwise, run `dart pub remove <package_name>`.
|
||||||
|
|
||||||
|
### Code Quality
|
||||||
|
* **Code structure:** Adhere to maintainable code structure and separation of
|
||||||
|
concerns (e.g., UI logic separate from business logic).
|
||||||
|
* **Naming conventions:** Avoid abbreviations and use meaningful, consistent,
|
||||||
|
descriptive names for variables, functions, and classes.
|
||||||
|
* **Conciseness:** Write code that is as short as it can be while remaining
|
||||||
|
clear.
|
||||||
|
* **Simplicity:** Write straightforward code. Code that is clever or
|
||||||
|
obscure is difficult to maintain.
|
||||||
|
* **Error Handling:** Anticipate and handle potential errors. Don't let your
|
||||||
|
code fail silently.
|
||||||
|
* **Styling:**
|
||||||
|
* Line length: Lines should be 80 characters or fewer.
|
||||||
|
* Use `PascalCase` for classes, `camelCase` for
|
||||||
|
members/variables/functions/enums, and `snake_case` for files.
|
||||||
|
* **Functions:**
|
||||||
|
* Keep functions short and with a single purpose.
|
||||||
|
Strive for less than 20 lines.
|
||||||
|
* **Testing:** Write code with testing in mind. Use the `file`, `process`, and
|
||||||
|
`platform` packages, if appropriate, so you can inject in-memory and fake
|
||||||
|
versions of the objects.
|
||||||
|
* **Logging:** Use the `logging` package instead of `print`.
|
||||||
|
|
||||||
|
### Dart Best Practices
|
||||||
|
* **Effective Dart:** Follow the official Effective Dart guidelines
|
||||||
|
(https://dart.dev/effective-dart)
|
||||||
|
* **Class Organization:** Define related classes within the same library file.
|
||||||
|
For large libraries, export smaller, private libraries from a single top-level
|
||||||
|
library.
|
||||||
|
* **Library Organization:** Group related libraries in the same folder.
|
||||||
|
* **API Documentation:** Add documentation comments to all public APIs,
|
||||||
|
including classes, constructors, methods, and top-level functions.
|
||||||
|
* **Comments:** Write clear comments for complex or non-obvious code. Avoid
|
||||||
|
over-commenting.
|
||||||
|
* **Trailing Comments:** Don't add trailing comments.
|
||||||
|
* **Async/Await:** Ensure proper use of `async`/`await` for asynchronous
|
||||||
|
operations with robust error handling.
|
||||||
|
* Use `Future`s, `async`, and `await` for asynchronous operations.
|
||||||
|
* Use `Stream`s for sequences of asynchronous events.
|
||||||
|
* **Null Safety:** Write code that is soundly null-safe. Leverage Dart's null
|
||||||
|
safety features. Avoid `!` unless the value is guaranteed to be non-null.
|
||||||
|
* **Pattern Matching:** Use pattern matching features where they simplify the
|
||||||
|
code.
|
||||||
|
* **Records:** Use records to return multiple types in situations where defining
|
||||||
|
an entire class is cumbersome.
|
||||||
|
* **Switch Statements:** Prefer using exhaustive `switch` statements or
|
||||||
|
expressions, which don't require `break` statements.
|
||||||
|
* **Exception Handling:** Use `try-catch` blocks for handling exceptions, and
|
||||||
|
use exceptions appropriate for the type of exception. Use custom exceptions
|
||||||
|
for situations specific to your code.
|
||||||
|
* **Arrow Functions:** Use arrow syntax for simple one-line functions.
|
||||||
|
|
||||||
|
### Flutter Best Practices
|
||||||
|
* **Immutability:** Widgets (especially `StatelessWidget`) are immutable; when
|
||||||
|
the UI needs to change, Flutter rebuilds the widget tree.
|
||||||
|
* **Composition:** Prefer composing smaller widgets over extending existing
|
||||||
|
ones. Use this to avoid deep widget nesting.
|
||||||
|
* **Private Widgets:** Use small, private `Widget` classes instead of private
|
||||||
|
helper methods that return a `Widget`.
|
||||||
|
* **Build Methods:** Break down large `build()` methods into smaller, reusable
|
||||||
|
private Widget classes.
|
||||||
|
* **List Performance:** Use `ListView.builder` or `SliverList` for long lists to
|
||||||
|
create lazy-loaded lists for performance.
|
||||||
|
* **Isolates:** Use `compute()` to run expensive calculations in a separate
|
||||||
|
isolate to avoid blocking the UI thread, such as JSON parsing.
|
||||||
|
* **Const Constructors:** Use `const` constructors for widgets and in `build()`
|
||||||
|
methods whenever possible to reduce rebuilds.
|
||||||
|
* **Build Method Performance:** Avoid performing expensive operations, like
|
||||||
|
network calls or complex computations, directly within `build()` methods.
|
||||||
|
|
||||||
|
### API Design Principles
|
||||||
|
When building reusable APIs, such as a library, follow these principles.
|
||||||
|
|
||||||
|
* **Consider the User:** Design APIs from the perspective of the person who will
|
||||||
|
be using them. The API should be intuitive and easy to use correctly.
|
||||||
|
* **Documentation is Essential:** Good documentation is a part of good API
|
||||||
|
design. It should be clear, concise, and provide examples.
|
||||||
|
|
||||||
|
### Application Architecture
|
||||||
|
* **Separation of Concerns:** Aim for separation of concerns similar to MVC/MVVM, with defined Model,
|
||||||
|
View, and ViewModel/Controller roles.
|
||||||
|
* **Logical Layers:** Organize the project into logical layers:
|
||||||
|
* Presentation (widgets, screens)
|
||||||
|
* Domain (business logic classes)
|
||||||
|
* Data (model classes, API clients)
|
||||||
|
* Core (shared classes, utilities, and extension types)
|
||||||
|
* **Feature-based Organization:** For larger projects, organize code by feature,
|
||||||
|
where each feature has its own presentation, domain, and data subfolders. This
|
||||||
|
improves navigability and scalability.
|
||||||
|
|
||||||
|
### Lint Rules
|
||||||
|
|
||||||
|
Include the package in the `analysis_options.yaml` file. Use the following
|
||||||
|
`analysis_options.yaml` file as a starting point:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
include: package:flutter_lints/flutter.yaml
|
||||||
|
|
||||||
|
linter:
|
||||||
|
rules:
|
||||||
|
# Add additional lint rules here:
|
||||||
|
# avoid_print: false
|
||||||
|
# prefer_single_quotes: true
|
||||||
|
```
|
||||||
154
docs/flutter-rules-state-and-data.md
Normal file
154
docs/flutter-rules-state-and-data.md
Normal file
@ -0,0 +1,154 @@
|
|||||||
|
# Flutter AI rules — state, routing and data
|
||||||
|
|
||||||
|
State management, data flow, routing, JSON serialization and logging.
|
||||||
|
|
||||||
|
_Verbatim from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md), split across four files only to keep each under the repo's 250-line
|
||||||
|
cap. Re-fetch periodically to stay current; do not hand-edit._
|
||||||
|
|
||||||
|
#### State Management
|
||||||
|
* **Built-in Solutions:** Prefer Flutter's built-in state management solutions.
|
||||||
|
Do not use a third-party package unless explicitly requested.
|
||||||
|
* **Streams:** Use `Streams` and `StreamBuilder` for handling a sequence of
|
||||||
|
asynchronous events.
|
||||||
|
* **Futures:** Use `Futures` and `FutureBuilder` for handling a single
|
||||||
|
asynchronous operation that will complete in the future.
|
||||||
|
* **ValueNotifier:** Use `ValueNotifier` with `ValueListenableBuilder` for
|
||||||
|
simple, local state that involves a single value.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
// Define a ValueNotifier to hold the state.
|
||||||
|
final ValueNotifier<int> _counter = ValueNotifier<int>(0);
|
||||||
|
|
||||||
|
// Use ValueListenableBuilder to listen and rebuild.
|
||||||
|
ValueListenableBuilder<int>(
|
||||||
|
valueListenable: _counter,
|
||||||
|
builder: (context, value, child) {
|
||||||
|
return Text('Count: $value');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
* **ChangeNotifier:** For state that is more complex or shared across multiple
|
||||||
|
widgets, use `ChangeNotifier`.
|
||||||
|
* **ListenableBuilder:** Use `ListenableBuilder` to listen to changes from a
|
||||||
|
`ChangeNotifier` or other `Listenable`.
|
||||||
|
* **MVVM:** When a more robust solution is needed, structure the app using the
|
||||||
|
Model-View-ViewModel (MVVM) pattern.
|
||||||
|
* **Dependency Injection:** Use simple manual constructor dependency injection
|
||||||
|
to make a class's dependencies explicit in its API, and to manage dependencies
|
||||||
|
between different layers of the application.
|
||||||
|
* **Provider:** If a dependency injection solution beyond manual constructor
|
||||||
|
injection is explicitly requested, `provider` can be used to make services,
|
||||||
|
repositories, or complex state objects available to the UI layer without tight
|
||||||
|
coupling (note: this document generally defaults against third-party packages
|
||||||
|
for state management unless explicitly requested).
|
||||||
|
|
||||||
|
#### Data Flow
|
||||||
|
* **Data Structures:** Define data structures (classes) to represent the data
|
||||||
|
used in the application.
|
||||||
|
* **Data Abstraction:** Abstract data sources (e.g., API calls, database
|
||||||
|
operations) using Repositories/Services to promote testability.
|
||||||
|
|
||||||
|
#### Routing
|
||||||
|
* **GoRouter:** Use the `go_router` package for declarative navigation, deep
|
||||||
|
linking, and web support.
|
||||||
|
* **GoRouter Setup:** To use `go_router`, first add it to your `pubspec.yaml`
|
||||||
|
using the `pub` tool's `add` command.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
// 1. Add the dependency
|
||||||
|
// flutter pub add go_router
|
||||||
|
|
||||||
|
// 2. Configure the router
|
||||||
|
final GoRouter _router = GoRouter(
|
||||||
|
routes: <RouteBase>[
|
||||||
|
GoRoute(
|
||||||
|
path: '/',
|
||||||
|
builder: (context, state) => const HomeScreen(),
|
||||||
|
routes: <RouteBase>[
|
||||||
|
GoRoute(
|
||||||
|
path: 'details/:id', // Route with a path parameter
|
||||||
|
builder: (context, state) {
|
||||||
|
final String id = state.pathParameters['id']!;
|
||||||
|
return DetailScreen(id: id);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
// 3. Use it in your MaterialApp
|
||||||
|
MaterialApp.router(
|
||||||
|
routerConfig: _router,
|
||||||
|
);
|
||||||
|
```
|
||||||
|
* **Authentication Redirects:** Configure `go_router`'s `redirect` property to
|
||||||
|
handle authentication flows, ensuring users are redirected to the login screen
|
||||||
|
when unauthorized, and back to their intended destination after successful
|
||||||
|
login.
|
||||||
|
|
||||||
|
* **Navigator:** Use the built-in `Navigator` for short-lived screens that do
|
||||||
|
not need to be deep-linkable, such as dialogs or temporary views.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
// Push a new screen onto the stack
|
||||||
|
Navigator.push(
|
||||||
|
context,
|
||||||
|
MaterialPageRoute(builder: (context) => const DetailsScreen()),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Pop the current screen to go back
|
||||||
|
Navigator.pop(context);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Data Handling & Serialization
|
||||||
|
* **JSON Serialization:** Use `json_serializable` and `json_annotation` for
|
||||||
|
parsing and encoding JSON data.
|
||||||
|
* **Field Renaming:** When encoding data, use `fieldRename: FieldRename.snake`
|
||||||
|
to convert Dart's camelCase fields to snake_case JSON keys.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
// In your model file
|
||||||
|
import 'package:json_annotation/json_annotation.dart';
|
||||||
|
|
||||||
|
part 'user.g.dart';
|
||||||
|
|
||||||
|
@JsonSerializable(fieldRename: FieldRename.snake)
|
||||||
|
class User {
|
||||||
|
final String firstName;
|
||||||
|
final String lastName;
|
||||||
|
|
||||||
|
User({required this.firstName, required this.lastName});
|
||||||
|
|
||||||
|
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
|
||||||
|
Map<String, dynamic> toJson() => _$UserToJson(this);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
#### Logging
|
||||||
|
* **Structured Logging:** Use the `log` function from `dart:developer` for
|
||||||
|
structured logging that integrates with Dart DevTools.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
import 'dart:developer' as developer;
|
||||||
|
|
||||||
|
// For simple messages
|
||||||
|
developer.log('User logged in successfully.');
|
||||||
|
|
||||||
|
// For structured error logging
|
||||||
|
try {
|
||||||
|
// ... code that might fail
|
||||||
|
} catch (e, s) {
|
||||||
|
developer.log(
|
||||||
|
'Failed to fetch data',
|
||||||
|
name: 'myapp.network',
|
||||||
|
level: 1000, // SEVERE
|
||||||
|
error: e,
|
||||||
|
stackTrace: s,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Code Generation
|
||||||
151
docs/flutter-rules-testing-and-assets.md
Normal file
151
docs/flutter-rules-testing-and-assets.md
Normal file
@ -0,0 +1,151 @@
|
|||||||
|
# Flutter AI rules — Code generation, testing, theming and assets
|
||||||
|
|
||||||
|
Code generation, the testing guidance, and the visual-design, theming and asset rules.
|
||||||
|
|
||||||
|
_Verbatim from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md), split across four files only to keep each under the repo's 250-line
|
||||||
|
cap. Re-fetch periodically to stay current; do not hand-edit._
|
||||||
|
|
||||||
|
* **Build Runner:** If the project uses code generation, ensure that
|
||||||
|
`build_runner` is listed as a dev dependency in `pubspec.yaml`.
|
||||||
|
* **Code Generation Tasks:** Use `build_runner` for all code generation tasks,
|
||||||
|
such as for `json_serializable`.
|
||||||
|
* **Running Build Runner:** After modifying files that require code generation,
|
||||||
|
run the build command:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
dart run build_runner build --delete-conflicting-outputs
|
||||||
|
```
|
||||||
|
|
||||||
|
### Testing
|
||||||
|
* **Running Tests:** To run tests, use the `run_tests` tool if it is available,
|
||||||
|
otherwise use `flutter test`.
|
||||||
|
* **Unit Tests:** Use `package:test` for unit tests.
|
||||||
|
* **Widget Tests:** Use `package:flutter_test` for widget tests.
|
||||||
|
* **Integration Tests:** Use `package:integration_test` for integration tests.
|
||||||
|
* **Assertions:** Prefer using `package:checks` for more expressive and readable
|
||||||
|
assertions over the default `matchers`.
|
||||||
|
|
||||||
|
#### Testing Best practices
|
||||||
|
* **Convention:** Follow the Arrange-Act-Assert (or Given-When-Then) pattern.
|
||||||
|
* **Unit Tests:** Write unit tests for domain logic, data layer, and state
|
||||||
|
management.
|
||||||
|
* **Widget Tests:** Write widget tests for UI components.
|
||||||
|
* **Integration Tests:** For broader application validation, use integration
|
||||||
|
tests to verify end-to-end user flows.
|
||||||
|
* **integration_test package:** Use the `integration_test` package from the
|
||||||
|
Flutter SDK for integration tests. Add it as a `dev_dependency` in
|
||||||
|
`pubspec.yaml` by specifying `sdk: flutter`.
|
||||||
|
* **Mocks:** Prefer fakes or stubs over mocks. If mocks are absolutely
|
||||||
|
necessary, use `mockito` or `mocktail` to create mocks for dependencies. While
|
||||||
|
code generation is common for state management (e.g., with `freezed`), try to
|
||||||
|
avoid it for mocks.
|
||||||
|
* **Coverage:** Aim for high test coverage.
|
||||||
|
|
||||||
|
### Visual Design & Theming
|
||||||
|
* **UI Design:** Build beautiful and intuitive user interfaces that follow
|
||||||
|
modern design guidelines.
|
||||||
|
* **Responsiveness:** Ensure the app is mobile responsive and adapts to
|
||||||
|
different screen sizes, working perfectly on mobile and web.
|
||||||
|
* **Navigation:** If there are multiple pages for the user to interact with,
|
||||||
|
provide an intuitive and easy navigation bar or controls.
|
||||||
|
* **Typography:** Stress and emphasize font sizes to ease understanding, e.g.,
|
||||||
|
hero text, section headlines, list headlines, keywords in paragraphs.
|
||||||
|
* **Background:** Keep backgrounds flat and simple — no noise texture or
|
||||||
|
gradients. Follow the `unified-design-system` skill (safe-design-rules
|
||||||
|
rule 17: simple-on-complex); let content and typography carry visual
|
||||||
|
interest instead of background texture.
|
||||||
|
* **Shadows:** Follow the `unified-design-system` skill's shadow policy: no
|
||||||
|
shadows at all in dark UI (differentiate elevation with lighter surface
|
||||||
|
fills, not shadows); in light UI, shadows are for floating/overlay
|
||||||
|
elements only (menus, dialogs), never for inline cards, and never mixed
|
||||||
|
with a border on the same surface.
|
||||||
|
* **Icons:** Incorporate icons to enhance the user’s understanding and the
|
||||||
|
logical navigation of the app.
|
||||||
|
* **Interactive Elements:** Buttons/controls signal state via color and fill
|
||||||
|
changes, not a "glow" shadow — one depth technique per surface, per
|
||||||
|
`unified-design-system`.
|
||||||
|
|
||||||
|
#### Theming
|
||||||
|
* **Centralized Theme:** Define a centralized `ThemeData` object to ensure a
|
||||||
|
consistent application-wide style.
|
||||||
|
* **Light and Dark Themes:** Implement support for both light and dark themes,
|
||||||
|
ideal for a user-facing theme toggle (`ThemeMode.light`, `ThemeMode.dark`,
|
||||||
|
`ThemeMode.system`).
|
||||||
|
* **Color Scheme Generation:** Do NOT use `ColorScheme.fromSeed` for this
|
||||||
|
app's palette — it can't reproduce hand-picked values exactly. Build
|
||||||
|
`ThemeData` from explicit `ColorScheme.dark(...)`/`.light(...)` using the
|
||||||
|
frozen, identical-everywhere tokens in the `unified-design-system` skill
|
||||||
|
(`~/.claude/skills/unified-design-system/references/tokens.md`).
|
||||||
|
|
||||||
|
```dart
|
||||||
|
final ThemeData lightTheme = ThemeData(
|
||||||
|
colorScheme: ColorScheme.fromSeed(
|
||||||
|
seedColor: Colors.deepPurple,
|
||||||
|
brightness: Brightness.light,
|
||||||
|
),
|
||||||
|
// ... other theme properties
|
||||||
|
);
|
||||||
|
```
|
||||||
|
* **Color Palette:** Include a wide range of color concentrations and hues in
|
||||||
|
the palette to create a vibrant and energetic look and feel.
|
||||||
|
* **Component Themes:** Use specific theme properties (e.g., `appBarTheme`,
|
||||||
|
`elevatedButtonTheme`) to customize the appearance of individual Material
|
||||||
|
components.
|
||||||
|
* **Custom Fonts:** For custom fonts, use the `google_fonts` package. Define a
|
||||||
|
`TextTheme` to apply fonts consistently.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
// 1. Add the dependency
|
||||||
|
// flutter pub add google_fonts
|
||||||
|
|
||||||
|
// 2. Define a TextTheme with a custom font
|
||||||
|
final TextTheme appTextTheme = TextTheme(
|
||||||
|
displayLarge: GoogleFonts.oswald(fontSize: 57, fontWeight: FontWeight.bold),
|
||||||
|
titleLarge: GoogleFonts.roboto(fontSize: 22, fontWeight: FontWeight.w500),
|
||||||
|
bodyMedium: GoogleFonts.openSans(fontSize: 14),
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Assets and Images
|
||||||
|
* **Image Guidelines:** If images are needed, make them relevant and meaningful,
|
||||||
|
with appropriate size, layout, and licensing (e.g., freely available). Provide
|
||||||
|
placeholder images if real ones are not available.
|
||||||
|
* **Asset Declaration:** Declare all asset paths in your `pubspec.yaml` file.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
flutter:
|
||||||
|
uses-material-design: true
|
||||||
|
assets:
|
||||||
|
- assets/images/
|
||||||
|
```
|
||||||
|
|
||||||
|
* **Local Images:** Use `Image.asset` for local images from your asset
|
||||||
|
bundle.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
Image.asset('assets/images/placeholder.png')
|
||||||
|
```
|
||||||
|
* **Network images:** Use NetworkImage for images loaded from the network.
|
||||||
|
* **Cached images:** For cached images, use NetworkImage a package like
|
||||||
|
`cached_network_image`.
|
||||||
|
* **Custom Icons:** Use `ImageIcon` to display an icon from an `ImageProvider`,
|
||||||
|
useful for custom icons not in the `Icons` class.
|
||||||
|
* **Network Images:** Use `Image.network` to display images from a URL, and
|
||||||
|
always include `loadingBuilder` and `errorBuilder` for a better user
|
||||||
|
experience.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
// When using network images, always provide an errorBuilder.
|
||||||
|
Image.network(
|
||||||
|
'https://picsum.photos/200/300',
|
||||||
|
loadingBuilder: (context, child, progress) {
|
||||||
|
if (progress == null) return child;
|
||||||
|
return const Center(child: CircularProgressIndicator());
|
||||||
|
},
|
||||||
|
errorBuilder: (context, error, stackTrace) {
|
||||||
|
return const Icon(Icons.error);
|
||||||
|
},
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### UI Theming and Styling Code
|
||||||
197
docs/flutter-rules-ui.md
Normal file
197
docs/flutter-rules-ui.md
Normal file
@ -0,0 +1,197 @@
|
|||||||
|
# Flutter AI rules — UI: theming, layout and overlays
|
||||||
|
|
||||||
|
Material theming, WidgetStateProperty, layout, and overlays.
|
||||||
|
|
||||||
|
_Verbatim from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md), split across four files only to keep each under the repo's 250-line
|
||||||
|
cap. Re-fetch periodically to stay current; do not hand-edit._
|
||||||
|
|
||||||
|
* **Responsiveness:** Use `LayoutBuilder` or `MediaQuery` to create responsive
|
||||||
|
UIs.
|
||||||
|
* **Text:** Use `Theme.of(context).textTheme` for text styles.
|
||||||
|
* **Text Fields:** Configure `textCapitalization`, `keyboardType`, and
|
||||||
|
`placeholder`.
|
||||||
|
|
||||||
|
### Material Theming Best Practices
|
||||||
|
|
||||||
|
#### Embrace `ThemeData` and Material 3
|
||||||
|
|
||||||
|
* **Use `ColorScheme.fromSeed()`:** Use this to generate a complete, harmonious
|
||||||
|
color palette for both light and dark modes from a single seed color.
|
||||||
|
* **Define Light and Dark Themes:** Provide both `theme` and `darkTheme` to your
|
||||||
|
`MaterialApp` to support system brightness settings seamlessly.
|
||||||
|
* **Centralize Component Styles:** Customize specific component themes (e.g.,
|
||||||
|
`elevatedButtonTheme`, `cardTheme`, `appBarTheme`) within `ThemeData` to
|
||||||
|
ensure consistency.
|
||||||
|
* **Dark/Light Mode and Theme Toggle:** Implement support for both light and
|
||||||
|
dark themes using `theme` and `darkTheme` properties of `MaterialApp`. The
|
||||||
|
`themeMode` property can be dynamically controlled (e.g., via a
|
||||||
|
`ChangeNotifierProvider`) to allow for toggling between `ThemeMode.light`,
|
||||||
|
`ThemeMode.dark`, or `ThemeMode.system`.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
// main.dart
|
||||||
|
MaterialApp(
|
||||||
|
theme: ThemeData(
|
||||||
|
colorScheme: ColorScheme.fromSeed(
|
||||||
|
seedColor: Colors.deepPurple,
|
||||||
|
brightness: Brightness.light,
|
||||||
|
),
|
||||||
|
textTheme: const TextTheme(
|
||||||
|
displayLarge: TextStyle(fontSize: 57.0, fontWeight: FontWeight.bold),
|
||||||
|
bodyMedium: TextStyle(fontSize: 14.0, height: 1.4),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
darkTheme: ThemeData(
|
||||||
|
colorScheme: ColorScheme.fromSeed(
|
||||||
|
seedColor: Colors.deepPurple,
|
||||||
|
brightness: Brightness.dark,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
home: const MyHomePage(),
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Implement Design Tokens with `ThemeExtension`
|
||||||
|
|
||||||
|
For custom styles that aren't part of the standard `ThemeData`, use
|
||||||
|
`ThemeExtension` to define reusable design tokens.
|
||||||
|
|
||||||
|
* **Create a Custom Theme Extension:** Define a class that extends
|
||||||
|
`ThemeExtension<T>` and include your custom properties.
|
||||||
|
* **Implement `copyWith` and `lerp`:** These methods are required for the
|
||||||
|
extension to work correctly with theme transitions.
|
||||||
|
* **Register in `ThemeData`:** Add your custom extension to the `extensions`
|
||||||
|
list in your `ThemeData`.
|
||||||
|
* **Access Tokens in Widgets:** Use `Theme.of(context).extension<MyColors>()!`
|
||||||
|
to access your custom tokens.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
// 1. Define the extension
|
||||||
|
@immutable
|
||||||
|
class MyColors extends ThemeExtension<MyColors> {
|
||||||
|
const MyColors({required this.success, required this.danger});
|
||||||
|
|
||||||
|
final Color? success;
|
||||||
|
final Color? danger;
|
||||||
|
|
||||||
|
@override
|
||||||
|
ThemeExtension<MyColors> copyWith({Color? success, Color? danger}) {
|
||||||
|
return MyColors(success: success ?? this.success, danger: danger ?? this.danger);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
ThemeExtension<MyColors> lerp(ThemeExtension<MyColors>? other, double t) {
|
||||||
|
if (other is! MyColors) return this;
|
||||||
|
return MyColors(
|
||||||
|
success: Color.lerp(success, other.success, t),
|
||||||
|
danger: Color.lerp(danger, other.danger, t),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Register it in ThemeData
|
||||||
|
theme: ThemeData(
|
||||||
|
extensions: const <ThemeExtension<dynamic>>[
|
||||||
|
MyColors(success: Colors.green, danger: Colors.red),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
|
||||||
|
// 3. Use it in a widget
|
||||||
|
Container(
|
||||||
|
color: Theme.of(context).extension<MyColors>()!.success,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Styling with `WidgetStateProperty`
|
||||||
|
|
||||||
|
* **`WidgetStateProperty.resolveWith`:** Provide a function that receives a
|
||||||
|
`Set<WidgetState>` and returns the appropriate value for the current state.
|
||||||
|
* **`WidgetStateProperty.all`:** A shorthand for when the value is the same for
|
||||||
|
all states.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
// Example: Creating a button style that changes color when pressed.
|
||||||
|
final ButtonStyle myButtonStyle = ButtonStyle(
|
||||||
|
backgroundColor: WidgetStateProperty.resolveWith<Color>(
|
||||||
|
(Set<WidgetState> states) {
|
||||||
|
if (states.contains(WidgetState.pressed)) {
|
||||||
|
return Colors.green; // Color when pressed
|
||||||
|
}
|
||||||
|
return Colors.red; // Default color
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Layout Best Practices
|
||||||
|
|
||||||
|
#### Building Flexible and Overflow-Safe Layouts
|
||||||
|
|
||||||
|
##### For Rows and Columns
|
||||||
|
|
||||||
|
* **`Expanded`:** Use to make a child widget fill the remaining available space
|
||||||
|
along the main axis.
|
||||||
|
* **`Flexible`:** Use when you want a widget to shrink to fit, but not
|
||||||
|
necessarily grow. Don't combine `Flexible` and `Expanded` in the same `Row` or
|
||||||
|
`Column`.
|
||||||
|
* **`Wrap`:** Use when you have a series of widgets that would overflow a `Row`
|
||||||
|
or `Column`, and you want them to move to the next line.
|
||||||
|
|
||||||
|
##### For General Content
|
||||||
|
|
||||||
|
* **`SingleChildScrollView`:** Use when your content is intrinsically larger
|
||||||
|
than the viewport, but is a fixed size.
|
||||||
|
* **`ListView` / `GridView`:** For long lists or grids of content, always use a
|
||||||
|
builder constructor (`.builder`).
|
||||||
|
* **`FittedBox`:** Use to scale or fit a single child widget within its parent.
|
||||||
|
* **`LayoutBuilder`:** Use for complex, responsive layouts to make decisions
|
||||||
|
based on the available space.
|
||||||
|
|
||||||
|
#### Layering Widgets with Stack
|
||||||
|
|
||||||
|
* **`Positioned`:** Use to precisely place a child within a `Stack` by anchoring it to the edges.
|
||||||
|
* **`Align`:** Use to position a child within a `Stack` using alignments like `Alignment.center`.
|
||||||
|
|
||||||
|
#### Advanced Layout with Overlays
|
||||||
|
|
||||||
|
* **`OverlayPortal`:** Use this widget to show UI elements (like custom
|
||||||
|
dropdowns or tooltips) "on top" of everything else. It manages the
|
||||||
|
`OverlayEntry` for you.
|
||||||
|
|
||||||
|
```dart
|
||||||
|
class MyDropdown extends StatefulWidget {
|
||||||
|
const MyDropdown({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<MyDropdown> createState() => _MyDropdownState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _MyDropdownState extends State<MyDropdown> {
|
||||||
|
final _controller = OverlayPortalController();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return OverlayPortal(
|
||||||
|
controller: _controller,
|
||||||
|
overlayChildBuilder: (BuildContext context) {
|
||||||
|
return const Positioned(
|
||||||
|
top: 50,
|
||||||
|
left: 10,
|
||||||
|
child: Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: EdgeInsets.all(8.0),
|
||||||
|
child: Text('I am an overlay!'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
child: ElevatedButton(
|
||||||
|
onPressed: _controller.toggle,
|
||||||
|
child: const Text('Toggle Overlay'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Color Scheme Best Practices
|
||||||
38
lib/data/note_import.dart
Normal file
38
lib/data/note_import.dart
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
/// Two small companions of [NoteRepository]: the result of an import, and
|
||||||
|
/// the in-memory store its test constructor uses.
|
||||||
|
///
|
||||||
|
/// Split out of `note_repository.dart` for file size; that file re-exports
|
||||||
|
/// this one.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
|
||||||
|
/// Summary of an [NoteRepository.importNotes] run, for user feedback.
|
||||||
|
class ImportOutcome {
|
||||||
|
/// Creates an [ImportOutcome] from its per-category counts.
|
||||||
|
const ImportOutcome({
|
||||||
|
required this.added,
|
||||||
|
required this.updated,
|
||||||
|
required this.skipped,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Notes that did not exist locally and were created.
|
||||||
|
final int added;
|
||||||
|
|
||||||
|
/// Existing notes overwritten because the import was newer.
|
||||||
|
final int updated;
|
||||||
|
|
||||||
|
/// Notes skipped because the local copy was the same age or newer.
|
||||||
|
final int skipped;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// In-memory [LogPersistence] for [NoteRepository.openInMemory] (tests).
|
||||||
|
class MemoryPersistence implements LogPersistence {
|
||||||
|
String? _text;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> read() async => _text;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> write(String text) async => _text = text;
|
||||||
|
}
|
||||||
168
lib/data/note_query.dart
Normal file
168
lib/data/note_query.dart
Normal file
@ -0,0 +1,168 @@
|
|||||||
|
/// How notes are selected and ordered: the sort modes, the filter, and the
|
||||||
|
/// pure predicates behind them.
|
||||||
|
///
|
||||||
|
/// Split out of `note_repository.dart` for file size; that file re-exports
|
||||||
|
/// this one, so callers import it as before. Everything here is pure -- it
|
||||||
|
/// takes notes and a filter and returns a decision -- which is what made it
|
||||||
|
/// the natural seam.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
|
||||||
|
/// How the history list should be ordered.
|
||||||
|
enum NoteSort {
|
||||||
|
/// Newest created first.
|
||||||
|
createdDesc,
|
||||||
|
|
||||||
|
/// Most recently modified first.
|
||||||
|
modifiedDesc,
|
||||||
|
|
||||||
|
/// A-Z by note text.
|
||||||
|
alphabetical,
|
||||||
|
|
||||||
|
/// Highest [Priority] first.
|
||||||
|
priorityDesc,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An immutable set of constraints for querying notes.
|
||||||
|
///
|
||||||
|
/// All fields combine with logical AND. Empty/null fields impose no
|
||||||
|
/// constraint. Lives in the data layer so the filtering it drives never leaks
|
||||||
|
/// into the UI. Construct copies with [copyWith] when toggling one facet.
|
||||||
|
class NoteFilter {
|
||||||
|
/// Creates a [NoteFilter] from its constraint fields.
|
||||||
|
const NoteFilter({
|
||||||
|
this.query = '',
|
||||||
|
this.priorities = const {},
|
||||||
|
this.statuses = const {},
|
||||||
|
this.createdFrom,
|
||||||
|
this.createdTo,
|
||||||
|
this.updatedFrom,
|
||||||
|
this.updatedTo,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Case-insensitive substring matched against the note body.
|
||||||
|
final String query;
|
||||||
|
|
||||||
|
/// Notes must have one of these priorities. Empty means "any priority".
|
||||||
|
final Set<Priority> priorities;
|
||||||
|
|
||||||
|
/// Notes must have one of these statuses. Empty means "any status".
|
||||||
|
final Set<Status> statuses;
|
||||||
|
|
||||||
|
/// Inclusive lower bound (by calendar day) on the creation date.
|
||||||
|
final DateTime? createdFrom;
|
||||||
|
|
||||||
|
/// Inclusive upper bound (by calendar day) on the creation date.
|
||||||
|
final DateTime? createdTo;
|
||||||
|
|
||||||
|
/// Inclusive lower bound (by calendar day) on the last-updated date.
|
||||||
|
final DateTime? updatedFrom;
|
||||||
|
|
||||||
|
/// Inclusive upper bound (by calendar day) on the last-updated date.
|
||||||
|
final DateTime? updatedTo;
|
||||||
|
|
||||||
|
/// True when no constraint is active (the unfiltered, full list).
|
||||||
|
bool get isEmpty =>
|
||||||
|
query.trim().isEmpty &&
|
||||||
|
priorities.isEmpty &&
|
||||||
|
statuses.isEmpty &&
|
||||||
|
createdFrom == null &&
|
||||||
|
createdTo == null &&
|
||||||
|
updatedFrom == null &&
|
||||||
|
updatedTo == null;
|
||||||
|
|
||||||
|
/// Number of distinct active facets, for an "N filters" badge in the UI.
|
||||||
|
int get activeCount {
|
||||||
|
var n = 0;
|
||||||
|
if (query.trim().isNotEmpty) n++;
|
||||||
|
if (priorities.isNotEmpty) n++;
|
||||||
|
if (statuses.isNotEmpty) n++;
|
||||||
|
if (createdFrom != null || createdTo != null) n++;
|
||||||
|
if (updatedFrom != null || updatedTo != null) n++;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a copy with selected facets replaced. A `null` argument keeps
|
||||||
|
/// the current value; clearing a date is done via the dedicated clear
|
||||||
|
/// flags so `null` can mean "unchanged".
|
||||||
|
NoteFilter copyWith({
|
||||||
|
String? query,
|
||||||
|
Set<Priority>? priorities,
|
||||||
|
Set<Status>? statuses,
|
||||||
|
DateTime? createdFrom,
|
||||||
|
DateTime? createdTo,
|
||||||
|
DateTime? updatedFrom,
|
||||||
|
DateTime? updatedTo,
|
||||||
|
bool clearCreated = false,
|
||||||
|
bool clearUpdated = false,
|
||||||
|
}) {
|
||||||
|
return NoteFilter(
|
||||||
|
query: query ?? this.query,
|
||||||
|
priorities: priorities ?? this.priorities,
|
||||||
|
statuses: statuses ?? this.statuses,
|
||||||
|
createdFrom: clearCreated ? null : (createdFrom ?? this.createdFrom),
|
||||||
|
createdTo: clearCreated ? null : (createdTo ?? this.createdTo),
|
||||||
|
updatedFrom: clearUpdated ? null : (updatedFrom ?? this.updatedFrom),
|
||||||
|
updatedTo: clearUpdated ? null : (updatedTo ?? this.updatedTo),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether [note] passes every clause of [filter].
|
||||||
|
///
|
||||||
|
/// Clauses are AND-combined, and an empty clause matches everything -- an
|
||||||
|
/// empty priority set means "any priority", not "no priorities".
|
||||||
|
bool matchesFilter(Note note, NoteFilter filter) {
|
||||||
|
final query = filter.query.trim().toLowerCase();
|
||||||
|
if (query.isNotEmpty && !note.text.toLowerCase().contains(query)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (filter.priorities.isNotEmpty &&
|
||||||
|
!filter.priorities.contains(note.priority)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (filter.statuses.isNotEmpty && !filter.statuses.contains(note.status)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!_withinDays(note.createdAt, filter.createdFrom, filter.createdTo)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!_withinDays(note.updatedAt, filter.updatedFrom, filter.updatedTo)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inclusive day-granularity range check, matching the old SQL bounds:
|
||||||
|
/// `from` includes its whole day; `to` includes its whole day.
|
||||||
|
bool _withinDays(DateTime value, DateTime? from, DateTime? to) {
|
||||||
|
if (from != null && value.isBefore(_startOfDay(from))) return false;
|
||||||
|
if (to != null &&
|
||||||
|
!value.isBefore(_startOfDay(to).add(const Duration(days: 1)))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The comparator implementing [sort].
|
||||||
|
Comparator<Note> comparatorFor(NoteSort sort) {
|
||||||
|
switch (sort) {
|
||||||
|
case NoteSort.createdDesc:
|
||||||
|
return (a, b) => b.createdAt.compareTo(a.createdAt);
|
||||||
|
case NoteSort.modifiedDesc:
|
||||||
|
return (a, b) => b.updatedAt.compareTo(a.updatedAt);
|
||||||
|
case NoteSort.alphabetical:
|
||||||
|
return (a, b) => a.text.toLowerCase().compareTo(b.text.toLowerCase());
|
||||||
|
case NoteSort.priorityDesc:
|
||||||
|
return (a, b) {
|
||||||
|
final byPriority = b.priority.value.compareTo(a.priority.value);
|
||||||
|
return byPriority != 0
|
||||||
|
? byPriority
|
||||||
|
: b.updatedAt.compareTo(a.updatedAt);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Midnight (local) of [t]'s calendar day.
|
||||||
|
DateTime _startOfDay(DateTime t) => DateTime(t.year, t.month, t.day);
|
||||||
@ -2,6 +2,11 @@ import 'dart:async';
|
|||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:todo/data/note.dart';
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_import.dart';
|
||||||
|
import 'package:todo/data/note_query.dart';
|
||||||
|
|
||||||
|
export 'package:todo/data/note_import.dart';
|
||||||
|
export 'package:todo/data/note_query.dart';
|
||||||
|
|
||||||
// Deliberately free of `dart:io`: the desktop app is a web build, and a single
|
// Deliberately free of `dart:io`: the desktop app is a web build, and a single
|
||||||
// `dart:io` import anywhere in the graph makes the whole app fail to compile
|
// `dart:io` import anywhere in the graph makes the whole app fail to compile
|
||||||
@ -9,43 +14,6 @@ import 'package:todo/data/note.dart';
|
|||||||
// conditional export in `repository_factory.dart`; the legacy sqlite migration
|
// conditional export in `repository_factory.dart`; the legacy sqlite migration
|
||||||
// lives in the io-only `legacy_sqlite_migration.dart`.
|
// lives in the io-only `legacy_sqlite_migration.dart`.
|
||||||
|
|
||||||
/// How the history list should be ordered.
|
|
||||||
enum NoteSort {
|
|
||||||
/// Newest created first.
|
|
||||||
createdDesc,
|
|
||||||
|
|
||||||
/// Most recently modified first.
|
|
||||||
modifiedDesc,
|
|
||||||
|
|
||||||
/// A-Z by note text.
|
|
||||||
alphabetical,
|
|
||||||
|
|
||||||
/// Highest [Priority] first.
|
|
||||||
priorityDesc,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Summary of an [NoteRepository.importNotes] run, for user feedback.
|
|
||||||
class ImportOutcome {
|
|
||||||
/// Creates an [ImportOutcome] from its per-category counts.
|
|
||||||
const ImportOutcome({
|
|
||||||
required this.added,
|
|
||||||
required this.updated,
|
|
||||||
required this.skipped,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Notes that did not exist locally and were created.
|
|
||||||
final int added;
|
|
||||||
|
|
||||||
/// Existing notes overwritten because the import was newer.
|
|
||||||
final int updated;
|
|
||||||
|
|
||||||
/// Notes skipped because the local copy was the same age or newer.
|
|
||||||
final int skipped;
|
|
||||||
|
|
||||||
/// Total notes considered in the import.
|
|
||||||
int get total => added + updated + skipped;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Local-first persistence for [Note]s, backed by the shared `crdt_sync`
|
/// Local-first persistence for [Note]s, backed by the shared `crdt_sync`
|
||||||
/// [LogStore] (was `sqlite_crdt`).
|
/// [LogStore] (was `sqlite_crdt`).
|
||||||
///
|
///
|
||||||
@ -110,7 +78,7 @@ class NoteRepository {
|
|||||||
static Future<NoteRepository> openInMemory({
|
static Future<NoteRepository> openInMemory({
|
||||||
String nodeId = 'test-node',
|
String nodeId = 'test-node',
|
||||||
}) async {
|
}) async {
|
||||||
final store = LogStore(persistence: _MemoryPersistence(), nodeId: nodeId);
|
final store = LogStore(persistence: MemoryPersistence(), nodeId: nodeId);
|
||||||
await store.load();
|
await store.load();
|
||||||
return NoteRepository._(store, nodeId);
|
return NoteRepository._(store, nodeId);
|
||||||
}
|
}
|
||||||
@ -273,157 +241,8 @@ class NoteRepository {
|
|||||||
int _liveCount() => _store.values.where((r) => !r.deleted).length;
|
int _liveCount() => _store.values.where((r) => !r.deleted).length;
|
||||||
|
|
||||||
List<Note> _query(NoteSort sort, NoteFilter filter) {
|
List<Note> _query(NoteSort sort, NoteFilter filter) {
|
||||||
final notes = _liveNotes().where((n) => _matches(n, filter)).toList()
|
final notes = _liveNotes().where((n) => matchesFilter(n, filter)).toList()
|
||||||
..sort(_comparator(sort));
|
..sort(comparatorFor(sort));
|
||||||
return notes;
|
return notes;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool _matches(Note note, NoteFilter filter) {
|
|
||||||
final query = filter.query.trim().toLowerCase();
|
|
||||||
if (query.isNotEmpty && !note.text.toLowerCase().contains(query)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (filter.priorities.isNotEmpty &&
|
|
||||||
!filter.priorities.contains(note.priority)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (filter.statuses.isNotEmpty && !filter.statuses.contains(note.status)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!_withinDays(note.createdAt, filter.createdFrom, filter.createdTo)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!_withinDays(note.updatedAt, filter.updatedFrom, filter.updatedTo)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Inclusive day-granularity range check, matching the old SQL bounds:
|
|
||||||
/// `from` includes its whole day; `to` includes its whole day.
|
|
||||||
static bool _withinDays(DateTime value, DateTime? from, DateTime? to) {
|
|
||||||
if (from != null && value.isBefore(_startOfDay(from))) return false;
|
|
||||||
if (to != null &&
|
|
||||||
!value.isBefore(_startOfDay(to).add(const Duration(days: 1)))) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
static Comparator<Note> _comparator(NoteSort sort) {
|
|
||||||
switch (sort) {
|
|
||||||
case NoteSort.createdDesc:
|
|
||||||
return (a, b) => b.createdAt.compareTo(a.createdAt);
|
|
||||||
case NoteSort.modifiedDesc:
|
|
||||||
return (a, b) => b.updatedAt.compareTo(a.updatedAt);
|
|
||||||
case NoteSort.alphabetical:
|
|
||||||
return (a, b) => a.text.toLowerCase().compareTo(b.text.toLowerCase());
|
|
||||||
case NoteSort.priorityDesc:
|
|
||||||
return (a, b) {
|
|
||||||
final byPriority = b.priority.value.compareTo(a.priority.value);
|
|
||||||
return byPriority != 0
|
|
||||||
? byPriority
|
|
||||||
: b.updatedAt.compareTo(a.updatedAt);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Midnight (local) of [t]'s calendar day.
|
|
||||||
static DateTime _startOfDay(DateTime t) => DateTime(t.year, t.month, t.day);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// In-memory [LogPersistence] for [NoteRepository.openInMemory] (tests).
|
|
||||||
class _MemoryPersistence implements LogPersistence {
|
|
||||||
String? _text;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<String?> read() async => _text;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> write(String text) async => _text = text;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An immutable set of constraints for querying notes.
|
|
||||||
///
|
|
||||||
/// All fields combine with logical AND. Empty/null fields impose no
|
|
||||||
/// constraint. Lives in the data layer so the filtering it drives never leaks
|
|
||||||
/// into the UI. Construct copies with [copyWith] when toggling one facet.
|
|
||||||
class NoteFilter {
|
|
||||||
/// Creates a [NoteFilter] from its constraint fields.
|
|
||||||
const NoteFilter({
|
|
||||||
this.query = '',
|
|
||||||
this.priorities = const {},
|
|
||||||
this.statuses = const {},
|
|
||||||
this.createdFrom,
|
|
||||||
this.createdTo,
|
|
||||||
this.updatedFrom,
|
|
||||||
this.updatedTo,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Case-insensitive substring matched against the note body.
|
|
||||||
final String query;
|
|
||||||
|
|
||||||
/// Notes must have one of these priorities. Empty means "any priority".
|
|
||||||
final Set<Priority> priorities;
|
|
||||||
|
|
||||||
/// Notes must have one of these statuses. Empty means "any status".
|
|
||||||
final Set<Status> statuses;
|
|
||||||
|
|
||||||
/// Inclusive lower bound (by calendar day) on the creation date.
|
|
||||||
final DateTime? createdFrom;
|
|
||||||
|
|
||||||
/// Inclusive upper bound (by calendar day) on the creation date.
|
|
||||||
final DateTime? createdTo;
|
|
||||||
|
|
||||||
/// Inclusive lower bound (by calendar day) on the last-updated date.
|
|
||||||
final DateTime? updatedFrom;
|
|
||||||
|
|
||||||
/// Inclusive upper bound (by calendar day) on the last-updated date.
|
|
||||||
final DateTime? updatedTo;
|
|
||||||
|
|
||||||
/// True when no constraint is active (the unfiltered, full list).
|
|
||||||
bool get isEmpty =>
|
|
||||||
query.trim().isEmpty &&
|
|
||||||
priorities.isEmpty &&
|
|
||||||
statuses.isEmpty &&
|
|
||||||
createdFrom == null &&
|
|
||||||
createdTo == null &&
|
|
||||||
updatedFrom == null &&
|
|
||||||
updatedTo == null;
|
|
||||||
|
|
||||||
/// Number of distinct active facets, for an "N filters" badge in the UI.
|
|
||||||
int get activeCount {
|
|
||||||
var n = 0;
|
|
||||||
if (query.trim().isNotEmpty) n++;
|
|
||||||
if (priorities.isNotEmpty) n++;
|
|
||||||
if (statuses.isNotEmpty) n++;
|
|
||||||
if (createdFrom != null || createdTo != null) n++;
|
|
||||||
if (updatedFrom != null || updatedTo != null) n++;
|
|
||||||
return n;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a copy with selected facets replaced. A `null` argument keeps
|
|
||||||
/// the current value; clearing a date is done via the dedicated clear
|
|
||||||
/// flags so `null` can mean "unchanged".
|
|
||||||
NoteFilter copyWith({
|
|
||||||
String? query,
|
|
||||||
Set<Priority>? priorities,
|
|
||||||
Set<Status>? statuses,
|
|
||||||
DateTime? createdFrom,
|
|
||||||
DateTime? createdTo,
|
|
||||||
DateTime? updatedFrom,
|
|
||||||
DateTime? updatedTo,
|
|
||||||
bool clearCreated = false,
|
|
||||||
bool clearUpdated = false,
|
|
||||||
}) {
|
|
||||||
return NoteFilter(
|
|
||||||
query: query ?? this.query,
|
|
||||||
priorities: priorities ?? this.priorities,
|
|
||||||
statuses: statuses ?? this.statuses,
|
|
||||||
createdFrom: clearCreated ? null : (createdFrom ?? this.createdFrom),
|
|
||||||
createdTo: clearCreated ? null : (createdTo ?? this.createdTo),
|
|
||||||
updatedFrom: clearUpdated ? null : (updatedFrom ?? this.updatedFrom),
|
|
||||||
updatedTo: clearUpdated ? null : (updatedTo ?? this.updatedTo),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
/// Structured note templates and the pure text <-> sections conversion.
|
/// Structured note templates: the section types and the template data.
|
||||||
///
|
///
|
||||||
/// The whole point of a template is that the user fills it, then copies the
|
/// The whole point of a template is that the user fills it, then copies the
|
||||||
/// note verbatim into an LLM, and the LLM has everything it needs to start
|
/// note verbatim into an LLM, and the LLM has everything it needs to start
|
||||||
@ -12,18 +12,18 @@
|
|||||||
/// verbatim to an LLM, so the description of what each section means must
|
/// verbatim to an LLM, so the description of what each section means must
|
||||||
/// travel with it.
|
/// travel with it.
|
||||||
///
|
///
|
||||||
/// Design invariants (see the round-trip tests):
|
/// The conversion itself ([assemble], [parse], [noteTitle], [isBareLink]) lives
|
||||||
/// * The **template** defines which sections exist; the stored text only
|
/// in `note_template_parser.dart` and is re-exported below, so importing this
|
||||||
/// carries values. Parsing an unknown/legacy note never invents sections.
|
/// file still gets the whole template API in one import.
|
||||||
/// * `assemble(parse(text))` is idempotent for any text that *conforms* to a
|
|
||||||
/// template, so opening and closing a structured note never mutates it.
|
|
||||||
/// * Text that does **not** conform (freeform notes, the old `what —` format,
|
|
||||||
/// the pre-2026-07 twelve-section spec, hand-mangled raw edits) is reported
|
|
||||||
/// as such so the UI can fall back to a raw editor and show it verbatim —
|
|
||||||
/// we never force non-conforming text into the guided stepper and never
|
|
||||||
/// drop a line we couldn't place.
|
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
// Imported as well as exported: `export` re-publishes the parser to this
|
||||||
|
// library's importers but does not bring its names into scope here, and
|
||||||
|
// NoteTemplate.forDraft calls isBareLink.
|
||||||
|
import 'package:todo/data/note_template_parser.dart';
|
||||||
|
|
||||||
|
export 'note_template_parser.dart';
|
||||||
|
|
||||||
/// One field of a structured template.
|
/// One field of a structured template.
|
||||||
class TemplateSection {
|
class TemplateSection {
|
||||||
/// Creates a [TemplateSection] from its field/label/helper text.
|
/// Creates a [TemplateSection] from its field/label/helper text.
|
||||||
@ -201,170 +201,3 @@ class NoteTemplate {
|
|||||||
static NoteTemplate forDraft(String text) =>
|
static NoteTemplate forDraft(String text) =>
|
||||||
isBareLink(text) ? blank : defaultTemplate;
|
isBareLink(text) ? blank : defaultTemplate;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Matches a single `http(s)://…` token.
|
|
||||||
final RegExp _linkPattern = RegExp(r'^https?://\S+$');
|
|
||||||
|
|
||||||
/// Whether [text] is nothing but one or more links.
|
|
||||||
///
|
|
||||||
/// Deliberately strict: one word of context ("read this https://…") means the
|
|
||||||
/// note has prose in it and is no longer a bare link.
|
|
||||||
bool isBareLink(String text) {
|
|
||||||
final tokens = text.trim().split(RegExp(r'\s+'))
|
|
||||||
..removeWhere((t) => t.isEmpty);
|
|
||||||
if (tokens.isEmpty) return false;
|
|
||||||
return tokens.every(_linkPattern.hasMatch);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Result of parsing stored text against a template.
|
|
||||||
class ParsedNote {
|
|
||||||
/// Creates a [ParsedNote] from its parsed [values] and [conforms] flag.
|
|
||||||
const ParsedNote({required this.values, required this.conforms});
|
|
||||||
|
|
||||||
/// Section-key -> value (trimmed). Sections absent from the text map to ''.
|
|
||||||
final Map<String, String> values;
|
|
||||||
|
|
||||||
/// Whether [text] cleanly matched [template]. When false the UI must show
|
|
||||||
/// the text in a raw editor rather than the guided stepper.
|
|
||||||
final bool conforms;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds the stored note text from section [values], dropping empty sections
|
|
||||||
/// so the pasted note carries no blank scaffold for the LLM to wade through.
|
|
||||||
///
|
|
||||||
/// [template] fixes the section order; [values] is keyed by section key. Each
|
|
||||||
/// present section becomes a `## label` heading, an italic guidance line, and
|
|
||||||
/// the value.
|
|
||||||
String assemble(NoteTemplate template, Map<String, String> values) {
|
|
||||||
if (template.isFreeform) return (values['body'] ?? '').trimRight();
|
|
||||||
|
|
||||||
final blocks = <String>[];
|
|
||||||
final title = (values['title'] ?? '').trim();
|
|
||||||
if (title.isNotEmpty) blocks.add('# $title');
|
|
||||||
|
|
||||||
for (final section in template.sections) {
|
|
||||||
if (section.isTitle) continue;
|
|
||||||
final value = (values[section.key] ?? '').trim();
|
|
||||||
if (value.isEmpty) continue; // drop empty sections
|
|
||||||
blocks.add('## ${section.label}\n_${section.helper}_\n\n$value');
|
|
||||||
}
|
|
||||||
return blocks.join('\n\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parses stored [text] into section values for the given [template].
|
|
||||||
///
|
|
||||||
/// Freeform templates always conform: the whole text is the `body` value.
|
|
||||||
/// For structured templates the text conforms only if it uses the Markdown
|
|
||||||
/// section headings, those headings are known and in template order without
|
|
||||||
/// repeats, and nothing but the `#` title sits before the first section.
|
|
||||||
/// Anything else (freeform, the old `what —` format) is reported as
|
|
||||||
/// non-conforming so the caller can show it raw, untouched.
|
|
||||||
ParsedNote parse(NoteTemplate template, String text) {
|
|
||||||
if (template.isFreeform) {
|
|
||||||
return ParsedNote(values: {'body': text}, conforms: true);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Index of each non-title section in template order, used to detect
|
|
||||||
// out-of-order or duplicate headings.
|
|
||||||
final order = <String, int>{};
|
|
||||||
var oi = 0;
|
|
||||||
for (final s in template.sections) {
|
|
||||||
if (!s.isTitle) order[s.key] = oi++;
|
|
||||||
}
|
|
||||||
|
|
||||||
final values = <String, String>{for (final s in template.sections) s.key: ''};
|
|
||||||
final lines = text.split('\n');
|
|
||||||
|
|
||||||
final titleLines = <String>[];
|
|
||||||
String? currentKey; // open section accumulating its block lines
|
|
||||||
final blocks = <String, List<String>>{};
|
|
||||||
var lastOrder = -1;
|
|
||||||
var sawSection = false;
|
|
||||||
var conforms = true;
|
|
||||||
|
|
||||||
for (final line in lines) {
|
|
||||||
final heading = _matchHeading(line, template);
|
|
||||||
if (heading != null) {
|
|
||||||
sawSection = true;
|
|
||||||
final idx = order[heading.key]!;
|
|
||||||
if (idx <= lastOrder) conforms = false; // out of order / duplicate
|
|
||||||
lastOrder = idx;
|
|
||||||
currentKey = heading.key;
|
|
||||||
blocks[heading.key] = <String>[];
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// A heading the template retired means the note predates the current
|
|
||||||
// section set. Keep the line as content (we never drop one) but refuse to
|
|
||||||
// call the note conforming, so the UI shows it raw instead of letting the
|
|
||||||
// stepper fold the retired section into its neighbour on the next save.
|
|
||||||
if (_isRetiredHeading(line)) conforms = false;
|
|
||||||
if (currentKey != null) {
|
|
||||||
blocks[currentKey]!.add(line);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// Still before the first section: only the `#` title and blanks belong.
|
|
||||||
final trimmed = line.trim();
|
|
||||||
if (trimmed.isEmpty) continue;
|
|
||||||
if (trimmed.startsWith('# ') && !trimmed.startsWith('## ')) {
|
|
||||||
titleLines.add(trimmed.substring(2).trim());
|
|
||||||
} else {
|
|
||||||
conforms = false; // stray content before the first section
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
values['title'] = titleLines.join('\n').trim();
|
|
||||||
for (final entry in blocks.entries) {
|
|
||||||
values[entry.key] = _stripGuidance(entry.value).trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
// A structured note with no recognised section headings is really freeform.
|
|
||||||
if (!sawSection) conforms = false;
|
|
||||||
|
|
||||||
return ParsedNote(values: values, conforms: conforms);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The note's display title: the `#` heading text without its `#` marker, or
|
|
||||||
/// the first non-empty line for freeform notes.
|
|
||||||
String noteTitle(String text) {
|
|
||||||
for (final line in text.split('\n')) {
|
|
||||||
final trimmed = line.trim();
|
|
||||||
if (trimmed.isEmpty) continue;
|
|
||||||
return trimmed.replaceFirst(RegExp(r'^#+\s*'), '');
|
|
||||||
}
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the section whose `## label` heading is on [line], or null. Only
|
|
||||||
/// known section labels are treated as headings, so a `## subheading` the user
|
|
||||||
/// wrote inside a value is preserved as content rather than splitting the note.
|
|
||||||
TemplateSection? _matchHeading(String line, NoteTemplate template) {
|
|
||||||
if (!line.startsWith('## ')) return null;
|
|
||||||
final label = line.substring(3).trim();
|
|
||||||
for (final s in template.sections) {
|
|
||||||
if (!s.isTitle && s.label == label) return s;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether [line] is a `## heading` naming a section the template retired.
|
|
||||||
bool _isRetiredHeading(String line) {
|
|
||||||
if (!line.startsWith('## ')) return false;
|
|
||||||
return NoteTemplate.retiredLabels.contains(line.substring(3).trim());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drops the leading blank lines and the single italic guidance line (if any)
|
|
||||||
/// from a section's block, leaving just the user's value.
|
|
||||||
String _stripGuidance(List<String> lines) {
|
|
||||||
final out = List<String>.from(lines);
|
|
||||||
var i = 0;
|
|
||||||
while (i < out.length && out[i].trim().isEmpty) {
|
|
||||||
i++;
|
|
||||||
}
|
|
||||||
if (i < out.length) {
|
|
||||||
final t = out[i].trim();
|
|
||||||
if (t.length >= 2 && t.startsWith('_') && t.endsWith('_')) {
|
|
||||||
out.removeAt(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out.join('\n');
|
|
||||||
}
|
|
||||||
|
|||||||
186
lib/data/note_template_parser.dart
Normal file
186
lib/data/note_template_parser.dart
Normal file
@ -0,0 +1,186 @@
|
|||||||
|
/// The pure text <-> sections conversion for [NoteTemplate].
|
||||||
|
///
|
||||||
|
/// Split out of `note_template.dart` (which now owns only the template types
|
||||||
|
/// and the template data) purely for file size; `note_template.dart` re-exports
|
||||||
|
/// everything here, so callers import that one file as before.
|
||||||
|
///
|
||||||
|
/// Design invariants (see the round-trip tests):
|
||||||
|
/// * The **template** defines which sections exist; the stored text only
|
||||||
|
/// carries values. Parsing an unknown/legacy note never invents sections.
|
||||||
|
/// * `assemble(parse(text))` is idempotent for any text that *conforms* to a
|
||||||
|
/// template, so opening and closing a structured note never mutates it.
|
||||||
|
/// * Text that does **not** conform (freeform notes, the old `what —` format,
|
||||||
|
/// the pre-2026-07 twelve-section spec, hand-mangled raw edits) is reported
|
||||||
|
/// as such so the UI can fall back to a raw editor and show it verbatim —
|
||||||
|
/// we never force non-conforming text into the guided stepper and never
|
||||||
|
/// drop a line we couldn't place.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
|
||||||
|
/// Matches a single `http(s)://…` token.
|
||||||
|
final RegExp _linkPattern = RegExp(r'^https?://\S+$');
|
||||||
|
|
||||||
|
/// Whether [text] is nothing but one or more links.
|
||||||
|
///
|
||||||
|
/// Deliberately strict: one word of context ("read this https://…") means the
|
||||||
|
/// note has prose in it and is no longer a bare link.
|
||||||
|
bool isBareLink(String text) {
|
||||||
|
final tokens = text.trim().split(RegExp(r'\s+'))
|
||||||
|
..removeWhere((t) => t.isEmpty);
|
||||||
|
if (tokens.isEmpty) return false;
|
||||||
|
return tokens.every(_linkPattern.hasMatch);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of parsing stored text against a template.
|
||||||
|
class ParsedNote {
|
||||||
|
/// Creates a [ParsedNote] from its parsed [values] and [conforms] flag.
|
||||||
|
const ParsedNote({required this.values, required this.conforms});
|
||||||
|
|
||||||
|
/// Section-key -> value (trimmed). Sections absent from the text map to ''.
|
||||||
|
final Map<String, String> values;
|
||||||
|
|
||||||
|
/// Whether the text cleanly matched the template. When false the UI must
|
||||||
|
/// show the text in a raw editor rather than the guided stepper.
|
||||||
|
final bool conforms;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the stored note text from section [values], dropping empty sections
|
||||||
|
/// so the pasted note carries no blank scaffold for the LLM to wade through.
|
||||||
|
///
|
||||||
|
/// [template] fixes the section order; [values] is keyed by section key. Each
|
||||||
|
/// present section becomes a `## label` heading, an italic guidance line, and
|
||||||
|
/// the value.
|
||||||
|
String assemble(NoteTemplate template, Map<String, String> values) {
|
||||||
|
if (template.isFreeform) return (values['body'] ?? '').trimRight();
|
||||||
|
|
||||||
|
final blocks = <String>[];
|
||||||
|
final title = (values['title'] ?? '').trim();
|
||||||
|
if (title.isNotEmpty) blocks.add('# $title');
|
||||||
|
|
||||||
|
for (final section in template.sections) {
|
||||||
|
if (section.isTitle) continue;
|
||||||
|
final value = (values[section.key] ?? '').trim();
|
||||||
|
if (value.isEmpty) continue; // drop empty sections
|
||||||
|
blocks.add('## ${section.label}\n_${section.helper}_\n\n$value');
|
||||||
|
}
|
||||||
|
return blocks.join('\n\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses stored [text] into section values for the given [template].
|
||||||
|
///
|
||||||
|
/// Freeform templates always conform: the whole text is the `body` value.
|
||||||
|
/// For structured templates the text conforms only if it uses the Markdown
|
||||||
|
/// section headings, those headings are known and in template order without
|
||||||
|
/// repeats, and nothing but the `#` title sits before the first section.
|
||||||
|
/// Anything else (freeform, the old `what —` format) is reported as
|
||||||
|
/// non-conforming so the caller can show it raw, untouched.
|
||||||
|
ParsedNote parse(NoteTemplate template, String text) {
|
||||||
|
if (template.isFreeform) {
|
||||||
|
return ParsedNote(values: {'body': text}, conforms: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Index of each non-title section in template order, used to detect
|
||||||
|
// out-of-order or duplicate headings.
|
||||||
|
final order = <String, int>{};
|
||||||
|
var oi = 0;
|
||||||
|
for (final s in template.sections) {
|
||||||
|
if (!s.isTitle) order[s.key] = oi++;
|
||||||
|
}
|
||||||
|
|
||||||
|
final values = <String, String>{for (final s in template.sections) s.key: ''};
|
||||||
|
final lines = text.split('\n');
|
||||||
|
|
||||||
|
final titleLines = <String>[];
|
||||||
|
String? currentKey; // open section accumulating its block lines
|
||||||
|
final blocks = <String, List<String>>{};
|
||||||
|
var lastOrder = -1;
|
||||||
|
var sawSection = false;
|
||||||
|
var conforms = true;
|
||||||
|
|
||||||
|
for (final line in lines) {
|
||||||
|
final heading = _matchHeading(line, template);
|
||||||
|
if (heading != null) {
|
||||||
|
sawSection = true;
|
||||||
|
final idx = order[heading.key]!;
|
||||||
|
if (idx <= lastOrder) conforms = false; // out of order / duplicate
|
||||||
|
lastOrder = idx;
|
||||||
|
currentKey = heading.key;
|
||||||
|
blocks[heading.key] = <String>[];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// A heading the template retired means the note predates the current
|
||||||
|
// section set. Keep the line as content (we never drop one) but refuse to
|
||||||
|
// call the note conforming, so the UI shows it raw instead of letting the
|
||||||
|
// stepper fold the retired section into its neighbour on the next save.
|
||||||
|
if (_isRetiredHeading(line)) conforms = false;
|
||||||
|
if (currentKey != null) {
|
||||||
|
blocks[currentKey]!.add(line);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Still before the first section: only the `#` title and blanks belong.
|
||||||
|
final trimmed = line.trim();
|
||||||
|
if (trimmed.isEmpty) continue;
|
||||||
|
if (trimmed.startsWith('# ') && !trimmed.startsWith('## ')) {
|
||||||
|
titleLines.add(trimmed.substring(2).trim());
|
||||||
|
} else {
|
||||||
|
conforms = false; // stray content before the first section
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
values['title'] = titleLines.join('\n').trim();
|
||||||
|
for (final entry in blocks.entries) {
|
||||||
|
values[entry.key] = _stripGuidance(entry.value).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// A structured note with no recognised section headings is really freeform.
|
||||||
|
if (!sawSection) conforms = false;
|
||||||
|
|
||||||
|
return ParsedNote(values: values, conforms: conforms);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The note's display title: the `#` heading text without its `#` marker, or
|
||||||
|
/// the first non-empty line for freeform notes.
|
||||||
|
String noteTitle(String text) {
|
||||||
|
for (final line in text.split('\n')) {
|
||||||
|
final trimmed = line.trim();
|
||||||
|
if (trimmed.isEmpty) continue;
|
||||||
|
return trimmed.replaceFirst(RegExp(r'^#+\s*'), '');
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the section whose `## label` heading is on [line], or null. Only
|
||||||
|
/// known section labels are treated as headings, so a `## subheading` the user
|
||||||
|
/// wrote inside a value is preserved as content rather than splitting the note.
|
||||||
|
TemplateSection? _matchHeading(String line, NoteTemplate template) {
|
||||||
|
if (!line.startsWith('## ')) return null;
|
||||||
|
final label = line.substring(3).trim();
|
||||||
|
for (final s in template.sections) {
|
||||||
|
if (!s.isTitle && s.label == label) return s;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether [line] is a `## heading` naming a section the template retired.
|
||||||
|
bool _isRetiredHeading(String line) {
|
||||||
|
if (!line.startsWith('## ')) return false;
|
||||||
|
return NoteTemplate.retiredLabels.contains(line.substring(3).trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops the leading blank lines and the single italic guidance line (if any)
|
||||||
|
/// from a section's block, leaving just the user's value.
|
||||||
|
String _stripGuidance(List<String> lines) {
|
||||||
|
final out = List<String>.from(lines);
|
||||||
|
var i = 0;
|
||||||
|
while (i < out.length && out[i].trim().isEmpty) {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
if (i < out.length) {
|
||||||
|
final t = out[i].trim();
|
||||||
|
if (t.length >= 2 && t.startsWith('_') && t.endsWith('_')) {
|
||||||
|
out.removeAt(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.join('\n');
|
||||||
|
}
|
||||||
71
lib/desktop/browser_launcher.dart
Normal file
71
lib/desktop/browser_launcher.dart
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
/// Finding and launching the Chrome window the desktop app runs in.
|
||||||
|
///
|
||||||
|
/// Split out of `bin/todo_desktop.dart` for file size. The profile directory
|
||||||
|
/// is fixed on purpose: the GitHub token (localStorage) and the notes
|
||||||
|
/// (IndexedDB) are keyed by origin and live in that profile, so a moving
|
||||||
|
/// profile dir would silently log the user out and hide their notes.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
|
||||||
|
/// Port must stay fixed: the browser keys `localStorage` (the GitHub token)
|
||||||
|
/// and IndexedDB (the notes) by origin, so a different port looks like a
|
||||||
|
/// different app with no token and no notes.
|
||||||
|
const kWrapperPort = 8730;
|
||||||
|
|
||||||
|
/// Browser profile directory for the desktop app.
|
||||||
|
///
|
||||||
|
/// Must stay stable: the GitHub token (localStorage) and the notes (IndexedDB)
|
||||||
|
/// live inside it, so a changing path silently logs the user out and hides
|
||||||
|
/// their notes. It doubles as the marker for "a window is still attached".
|
||||||
|
String profileDir(String home) =>
|
||||||
|
p.join(home, '.local', 'share', 'todo-desktop', 'profile');
|
||||||
|
|
||||||
|
/// Returns the first Chrome-family browser on this machine, or ''.
|
||||||
|
String findBrowser() {
|
||||||
|
// Ordered by preference, and deliberately broad: this machine runs Thorium
|
||||||
|
// behind /opt/google/chrome, and has a policy that uninstalls the `chromium`
|
||||||
|
// package, so assuming any single browser is wrong. TODO_BROWSER overrides.
|
||||||
|
final candidates = [
|
||||||
|
Platform.environment['TODO_BROWSER'] ?? '',
|
||||||
|
'/opt/google/chrome/chrome',
|
||||||
|
'/opt/thorium-browser/thorium-browser',
|
||||||
|
'/usr/bin/google-chrome-stable',
|
||||||
|
'/usr/bin/chromium',
|
||||||
|
'/usr/bin/brave',
|
||||||
|
];
|
||||||
|
return candidates.firstWhere(
|
||||||
|
(path) => path.isNotEmpty && File(path).existsSync(),
|
||||||
|
orElse: () => '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Launches the app in a Chrome-family browser with a **stable** profile
|
||||||
|
/// directory, since the token and notes live in that profile.
|
||||||
|
///
|
||||||
|
/// Returns true when the browser ran long enough to have owned the session.
|
||||||
|
Future<bool> launchBrowser(String home) async {
|
||||||
|
final browser = findBrowser();
|
||||||
|
if (browser.isEmpty) {
|
||||||
|
stderr.writeln(
|
||||||
|
'No Chrome-family browser found; open '
|
||||||
|
'http://localhost:$kWrapperPort manually.',
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
final process = await Process.start(browser, [
|
||||||
|
'--app=http://localhost:$kWrapperPort',
|
||||||
|
'--user-data-dir=${profileDir(home)}',
|
||||||
|
// Sets WM_CLASS, which the .desktop entry matches on via StartupWMClass.
|
||||||
|
// Without it the window inherits the browser's class and the taskbar shows
|
||||||
|
// a browser icon instead of todo's.
|
||||||
|
'--class=todo',
|
||||||
|
'--no-first-run',
|
||||||
|
]);
|
||||||
|
|
||||||
|
final started = DateTime.now();
|
||||||
|
await process.exitCode;
|
||||||
|
return DateTime.now().difference(started) > const Duration(seconds: 5);
|
||||||
|
}
|
||||||
100
lib/desktop/linux_system_probe.dart
Normal file
100
lib/desktop/linux_system_probe.dart
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
/// The real-host [SystemProbe]: `ss` for the listener, `/proc` for the rest.
|
||||||
|
///
|
||||||
|
/// Split out of `port_guard.dart` for file size, and it is the natural seam:
|
||||||
|
/// everything here touches the live host, while `port_guard.dart` keeps the
|
||||||
|
/// pure decision logic that tests drive with a fake probe.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:todo/desktop/port_guard.dart';
|
||||||
|
|
||||||
|
/// NUL separates the arguments inside `/proc/<pid>/cmdline`.
|
||||||
|
final String _argumentSeparator = String.fromCharCode(0);
|
||||||
|
|
||||||
|
/// [SystemProbe] backed by `ss` and `/proc`.
|
||||||
|
///
|
||||||
|
/// The desktop wrapper only ever runs on Linux — the desktop app is the web
|
||||||
|
/// build served locally — so reading `/proc` directly is safe here.
|
||||||
|
class LinuxSystemProbe implements SystemProbe {
|
||||||
|
/// Creates the default host probe.
|
||||||
|
///
|
||||||
|
/// [ssExecutable] exists so a test can point at a missing binary and exercise
|
||||||
|
/// the "no `ss` on PATH" path.
|
||||||
|
const LinuxSystemProbe({this.ssExecutable = 'ss'});
|
||||||
|
|
||||||
|
/// Name of the socket-listing tool used to find the port owner.
|
||||||
|
final String ssExecutable;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<int?> listenerPid(int port) async {
|
||||||
|
try {
|
||||||
|
final result = await Process.run(ssExecutable, ['-tlnp']);
|
||||||
|
final out = result.stdout;
|
||||||
|
return out is String ? parseListenerPid(out, port) : null;
|
||||||
|
} on ProcessException {
|
||||||
|
// No `ss` on PATH: report "unknown" and let the caller fail closed.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<ProcessDescription?> describe(int pid) async {
|
||||||
|
final cmdline = readCmdline(pid);
|
||||||
|
if (cmdline == null) return null;
|
||||||
|
String exe;
|
||||||
|
try {
|
||||||
|
exe = Link('/proc/$pid/exe').targetSync();
|
||||||
|
} on FileSystemException {
|
||||||
|
// Unreadable for another user's process; the cmdline still identifies it.
|
||||||
|
exe = '';
|
||||||
|
}
|
||||||
|
return ProcessDescription(exeTarget: exe, cmdline: cmdline);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<List<String>>> processCmdlines() async {
|
||||||
|
final cmdlines = <List<String>>[];
|
||||||
|
for (final entry in Directory('/proc').listSync()) {
|
||||||
|
final pid = int.tryParse(p.basename(entry.path));
|
||||||
|
if (pid == null) continue;
|
||||||
|
final cmdline = readCmdline(pid);
|
||||||
|
if (cmdline != null) cmdlines.add(cmdline);
|
||||||
|
}
|
||||||
|
return cmdlines;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> portInUse(int port) async {
|
||||||
|
try {
|
||||||
|
final socket = await ServerSocket.bind(
|
||||||
|
InternetAddress.loopbackIPv4,
|
||||||
|
port,
|
||||||
|
);
|
||||||
|
await socket.close();
|
||||||
|
return false;
|
||||||
|
} on SocketException {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool signal(int pid, ProcessSignal signal) => Process.killPid(pid, signal);
|
||||||
|
|
||||||
|
/// Reads `/proc/<pid>/cmdline` as an argument vector.
|
||||||
|
///
|
||||||
|
/// Returns null when the process is gone. Kernel threads yield an empty list,
|
||||||
|
/// and the trailing separator is dropped so exact-token matching holds.
|
||||||
|
static List<String>? readCmdline(int pid) {
|
||||||
|
try {
|
||||||
|
return File('/proc/$pid/cmdline')
|
||||||
|
.readAsStringSync()
|
||||||
|
.split(_argumentSeparator)
|
||||||
|
.where((token) => token.isNotEmpty)
|
||||||
|
.toList();
|
||||||
|
} on FileSystemException {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -4,8 +4,11 @@ import 'dart:io';
|
|||||||
|
|
||||||
import 'package:path/path.dart' as p;
|
import 'package:path/path.dart' as p;
|
||||||
|
|
||||||
/// NUL separates the arguments inside `/proc/<pid>/cmdline`.
|
// The real-host probe lives in its own file (size), but PortGuard defaults to
|
||||||
final String _argumentSeparator = String.fromCharCode(0);
|
// it and callers expect one import, so it is re-exported here.
|
||||||
|
import 'package:todo/desktop/linux_system_probe.dart';
|
||||||
|
|
||||||
|
export 'package:todo/desktop/linux_system_probe.dart';
|
||||||
|
|
||||||
/// What the launcher should do when the fixed wrapper port is already bound.
|
/// What the launcher should do when the fixed wrapper port is already bound.
|
||||||
///
|
///
|
||||||
@ -227,89 +230,3 @@ class PortGuard {
|
|||||||
return !await probe.portInUse(port);
|
return !await probe.portInUse(port);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [SystemProbe] backed by `ss` and `/proc`.
|
|
||||||
///
|
|
||||||
/// The desktop wrapper only ever runs on Linux — the desktop app is the web
|
|
||||||
/// build served locally — so reading `/proc` directly is safe here.
|
|
||||||
class LinuxSystemProbe implements SystemProbe {
|
|
||||||
/// Creates the default host probe.
|
|
||||||
///
|
|
||||||
/// [ssExecutable] exists so a test can point at a missing binary and exercise
|
|
||||||
/// the "no `ss` on PATH" path.
|
|
||||||
const LinuxSystemProbe({this.ssExecutable = 'ss'});
|
|
||||||
|
|
||||||
/// Name of the socket-listing tool used to find the port owner.
|
|
||||||
final String ssExecutable;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<int?> listenerPid(int port) async {
|
|
||||||
try {
|
|
||||||
final result = await Process.run(ssExecutable, ['-tlnp']);
|
|
||||||
final out = result.stdout;
|
|
||||||
return out is String ? parseListenerPid(out, port) : null;
|
|
||||||
} on ProcessException {
|
|
||||||
// No `ss` on PATH: report "unknown" and let the caller fail closed.
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<ProcessDescription?> describe(int pid) async {
|
|
||||||
final cmdline = readCmdline(pid);
|
|
||||||
if (cmdline == null) return null;
|
|
||||||
String exe;
|
|
||||||
try {
|
|
||||||
exe = Link('/proc/$pid/exe').targetSync();
|
|
||||||
} on FileSystemException {
|
|
||||||
// Unreadable for another user's process; the cmdline still identifies it.
|
|
||||||
exe = '';
|
|
||||||
}
|
|
||||||
return ProcessDescription(exeTarget: exe, cmdline: cmdline);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<List<List<String>>> processCmdlines() async {
|
|
||||||
final cmdlines = <List<String>>[];
|
|
||||||
for (final entry in Directory('/proc').listSync()) {
|
|
||||||
final pid = int.tryParse(p.basename(entry.path));
|
|
||||||
if (pid == null) continue;
|
|
||||||
final cmdline = readCmdline(pid);
|
|
||||||
if (cmdline != null) cmdlines.add(cmdline);
|
|
||||||
}
|
|
||||||
return cmdlines;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<bool> portInUse(int port) async {
|
|
||||||
try {
|
|
||||||
final socket = await ServerSocket.bind(
|
|
||||||
InternetAddress.loopbackIPv4,
|
|
||||||
port,
|
|
||||||
);
|
|
||||||
await socket.close();
|
|
||||||
return false;
|
|
||||||
} on SocketException {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
bool signal(int pid, ProcessSignal signal) => Process.killPid(pid, signal);
|
|
||||||
|
|
||||||
/// Reads `/proc/<pid>/cmdline` as an argument vector.
|
|
||||||
///
|
|
||||||
/// Returns null when the process is gone. Kernel threads yield an empty list,
|
|
||||||
/// and the trailing separator is dropped so exact-token matching holds.
|
|
||||||
static List<String>? readCmdline(int pid) {
|
|
||||||
try {
|
|
||||||
return File('/proc/$pid/cmdline')
|
|
||||||
.readAsStringSync()
|
|
||||||
.split(_argumentSeparator)
|
|
||||||
.where((token) => token.isNotEmpty)
|
|
||||||
.toList();
|
|
||||||
} on FileSystemException {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@ -5,6 +5,8 @@ import 'dart:io';
|
|||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:path/path.dart' as p;
|
import 'package:path/path.dart' as p;
|
||||||
|
|
||||||
|
part 'wrapper_sync_routes.dart';
|
||||||
|
|
||||||
/// Route serving `todo`'s own seeded Firebase session (a `FirebaseCredentials`
|
/// Route serving `todo`'s own seeded Firebase session (a `FirebaseCredentials`
|
||||||
/// JSON blob), alongside [kSyncAccountPath]'s email/password pair.
|
/// JSON blob), alongside [kSyncAccountPath]'s email/password pair.
|
||||||
///
|
///
|
||||||
@ -140,121 +142,6 @@ class WrapperServer {
|
|||||||
return _static(request, path);
|
return _static(request, path);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Serves the shared sync account so a desktop install can self-provision.
|
|
||||||
///
|
|
||||||
/// Off unless CRDT_SYNC_SERVE_ACCOUNT is set: this hands out a credential
|
|
||||||
/// with database write access to anything that can reach the port, so it is
|
|
||||||
/// something you switch on once to set an install up, not a standing route.
|
|
||||||
/// 404 (rather than 403) when disabled, so a probe cannot tell the route
|
|
||||||
/// exists.
|
|
||||||
///
|
|
||||||
/// The account is read from the same ~/.config/crdt-sync/ pair the Python
|
|
||||||
/// daemons already use, so there is one source of truth per machine rather
|
|
||||||
/// than a per-app copy.
|
|
||||||
Future<void> _syncAccount(HttpRequest request) async {
|
|
||||||
if (!serveSyncAccount) {
|
|
||||||
request.response.statusCode = HttpStatus.notFound;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final configFile = File(p.join(syncConfigDir, 'firebase.json'));
|
|
||||||
final passwordFile = File(p.join(syncConfigDir, 'password'));
|
|
||||||
if (!configFile.existsSync() || !passwordFile.existsSync()) {
|
|
||||||
stderr.writeln(
|
|
||||||
'Sync account requested but ~/.config/crdt-sync/ is incomplete — '
|
|
||||||
'the desktop app will keep asking for credentials.',
|
|
||||||
);
|
|
||||||
request.response.statusCode = HttpStatus.notFound;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final email =
|
|
||||||
(jsonDecode(await configFile.readAsString())
|
|
||||||
as Map<String, dynamic>)['email'];
|
|
||||||
if (email is! String || email.isEmpty) {
|
|
||||||
stderr.writeln('firebase.json has no usable "email" — not serving it.');
|
|
||||||
request.response.statusCode = HttpStatus.notFound;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
request.response.headers.contentType = ContentType.json;
|
|
||||||
request.response.write(
|
|
||||||
jsonEncode({
|
|
||||||
'email': email,
|
|
||||||
'password': (await passwordFile.readAsString()).trim(),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Serves `todo`'s own seeded Firebase session, so a fresh desktop install
|
|
||||||
/// can authenticate without ever seeing a password field and without a
|
|
||||||
/// human setting an env var first.
|
|
||||||
///
|
|
||||||
/// Reachable by default (unlike [_syncAccount], which stays behind
|
|
||||||
/// [serveSyncAccount]/[kSyncAccountEnvVar]) but only until the first
|
|
||||||
/// successful serve: this hands out a credential with database write
|
|
||||||
/// access to anything that can reach the port, shared with five other
|
|
||||||
/// apps, so the window it is actually reachable in must be as small as
|
|
||||||
/// "until the app finishes booting", not "for as long as the wrapper
|
|
||||||
/// runs". 404 (not 403) both when already served and when disabled, so a
|
|
||||||
/// probe cannot tell which case it hit.
|
|
||||||
///
|
|
||||||
/// Consumed once by `loadAccount()`'s wrapper fallback and written
|
|
||||||
/// straight into the keystore; never a standing source the app re-reads on
|
|
||||||
/// every launch. That matters here specifically: `seed_session.py` may
|
|
||||||
/// later rotate this file's refresh token for an unrelated app's re-seed
|
|
||||||
/// run, and Firebase invalidates the previous token when it does --
|
|
||||||
/// serving a stale token to a device that already adopted the live one
|
|
||||||
/// would just hand back a token neither side can use.
|
|
||||||
Future<void> _syncCredentials(HttpRequest request) async {
|
|
||||||
if (_todoCredentialsServed) {
|
|
||||||
request.response.statusCode = HttpStatus.notFound;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final credentialsFile = File(todoCredentialsPath);
|
|
||||||
if (!credentialsFile.existsSync()) {
|
|
||||||
request.response.statusCode = HttpStatus.notFound;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final Map<String, dynamic> credentials;
|
|
||||||
try {
|
|
||||||
credentials =
|
|
||||||
jsonDecode(await credentialsFile.readAsString())
|
|
||||||
as Map<String, dynamic>;
|
|
||||||
} on FormatException {
|
|
||||||
stderr.writeln(
|
|
||||||
'$todoCredentialsPath is not valid JSON — not serving it.',
|
|
||||||
);
|
|
||||||
request.response.statusCode = HttpStatus.notFound;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (credentials['id_token'] is! String ||
|
|
||||||
credentials['refresh_token'] is! String ||
|
|
||||||
credentials['expires_at'] is! String) {
|
|
||||||
stderr.writeln(
|
|
||||||
'$todoCredentialsPath is missing id_token/refresh_token/expires_at '
|
|
||||||
'— not serving it.',
|
|
||||||
);
|
|
||||||
request.response.statusCode = HttpStatus.notFound;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// The email is a display nicety (so Settings shows an address instead of
|
|
||||||
// a blank), not a credential -- read from the shared config, not from
|
|
||||||
// todoCredentialsPath, which has no email field of its own.
|
|
||||||
String? email;
|
|
||||||
final configFile = File(p.join(syncConfigDir, 'firebase.json'));
|
|
||||||
if (configFile.existsSync()) {
|
|
||||||
final config =
|
|
||||||
jsonDecode(await configFile.readAsString()) as Map<String, dynamic>;
|
|
||||||
final configEmail = config['email'];
|
|
||||||
if (configEmail is String && configEmail.isNotEmpty) {
|
|
||||||
email = configEmail;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
request.response.headers.contentType = ContentType.json;
|
|
||||||
request.response.write(jsonEncode({...credentials, 'email': email}));
|
|
||||||
// After, not before writing the response: a request that fails partway
|
|
||||||
// through must remain retryable rather than burning the one serve.
|
|
||||||
_todoCredentialsServed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// GET returns the file's contents (404 when absent); POST overwrites it.
|
/// GET returns the file's contents (404 when absent); POST overwrites it.
|
||||||
Future<void> _file(HttpRequest request, String filePath) async {
|
Future<void> _file(HttpRequest request, String filePath) async {
|
||||||
final file = File(filePath);
|
final file = File(filePath);
|
||||||
|
|||||||
124
lib/desktop/wrapper_sync_routes.dart
Normal file
124
lib/desktop/wrapper_sync_routes.dart
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
/// The wrapper's two credential-provisioning routes.
|
||||||
|
///
|
||||||
|
/// Split out of `wrapper_server.dart` for file size. Both serve a file from
|
||||||
|
/// the desktop's own config directory to the web app running in Chrome --
|
||||||
|
/// the seam that lets a desktop install provision itself instead of the
|
||||||
|
/// account being retyped per machine.
|
||||||
|
part of 'wrapper_server.dart';
|
||||||
|
|
||||||
|
extension _SyncRoutes on WrapperServer {
|
||||||
|
/// Serves the shared sync account so a desktop install can self-provision.
|
||||||
|
///
|
||||||
|
/// Off unless CRDT_SYNC_SERVE_ACCOUNT is set: this hands out a credential
|
||||||
|
/// with database write access to anything that can reach the port, so it is
|
||||||
|
/// something you switch on once to set an install up, not a standing route.
|
||||||
|
/// 404 (rather than 403) when disabled, so a probe cannot tell the route
|
||||||
|
/// exists.
|
||||||
|
///
|
||||||
|
/// The account is read from the same ~/.config/crdt-sync/ pair the Python
|
||||||
|
/// daemons already use, so there is one source of truth per machine rather
|
||||||
|
/// than a per-app copy.
|
||||||
|
Future<void> _syncAccount(HttpRequest request) async {
|
||||||
|
if (!serveSyncAccount) {
|
||||||
|
request.response.statusCode = HttpStatus.notFound;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final configFile = File(p.join(syncConfigDir, 'firebase.json'));
|
||||||
|
final passwordFile = File(p.join(syncConfigDir, 'password'));
|
||||||
|
if (!configFile.existsSync() || !passwordFile.existsSync()) {
|
||||||
|
stderr.writeln(
|
||||||
|
'Sync account requested but ~/.config/crdt-sync/ is incomplete — '
|
||||||
|
'the desktop app will keep asking for credentials.',
|
||||||
|
);
|
||||||
|
request.response.statusCode = HttpStatus.notFound;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final email =
|
||||||
|
(jsonDecode(await configFile.readAsString())
|
||||||
|
as Map<String, dynamic>)['email'];
|
||||||
|
if (email is! String || email.isEmpty) {
|
||||||
|
stderr.writeln('firebase.json has no usable "email" — not serving it.');
|
||||||
|
request.response.statusCode = HttpStatus.notFound;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
request.response.headers.contentType = ContentType.json;
|
||||||
|
request.response.write(
|
||||||
|
jsonEncode({
|
||||||
|
'email': email,
|
||||||
|
'password': (await passwordFile.readAsString()).trim(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serves `todo`'s own seeded Firebase session, so a fresh desktop install
|
||||||
|
/// can authenticate without ever seeing a password field and without a
|
||||||
|
/// human setting an env var first.
|
||||||
|
///
|
||||||
|
/// Reachable by default (unlike [_syncAccount], which stays behind
|
||||||
|
/// [serveSyncAccount]/[kSyncAccountEnvVar]) but only until the first
|
||||||
|
/// successful serve: this hands out a credential with database write
|
||||||
|
/// access to anything that can reach the port, shared with five other
|
||||||
|
/// apps, so the window it is actually reachable in must be as small as
|
||||||
|
/// "until the app finishes booting", not "for as long as the wrapper
|
||||||
|
/// runs". 404 (not 403) both when already served and when disabled, so a
|
||||||
|
/// probe cannot tell which case it hit.
|
||||||
|
///
|
||||||
|
/// Consumed once by `loadAccount()`'s wrapper fallback and written
|
||||||
|
/// straight into the keystore; never a standing source the app re-reads on
|
||||||
|
/// every launch. That matters here specifically: `seed_session.py` may
|
||||||
|
/// later rotate this file's refresh token for an unrelated app's re-seed
|
||||||
|
/// run, and Firebase invalidates the previous token when it does --
|
||||||
|
/// serving a stale token to a device that already adopted the live one
|
||||||
|
/// would just hand back a token neither side can use.
|
||||||
|
Future<void> _syncCredentials(HttpRequest request) async {
|
||||||
|
if (_todoCredentialsServed) {
|
||||||
|
request.response.statusCode = HttpStatus.notFound;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final credentialsFile = File(todoCredentialsPath);
|
||||||
|
if (!credentialsFile.existsSync()) {
|
||||||
|
request.response.statusCode = HttpStatus.notFound;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final Map<String, dynamic> credentials;
|
||||||
|
try {
|
||||||
|
credentials =
|
||||||
|
jsonDecode(await credentialsFile.readAsString())
|
||||||
|
as Map<String, dynamic>;
|
||||||
|
} on FormatException {
|
||||||
|
stderr.writeln(
|
||||||
|
'$todoCredentialsPath is not valid JSON — not serving it.',
|
||||||
|
);
|
||||||
|
request.response.statusCode = HttpStatus.notFound;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (credentials['id_token'] is! String ||
|
||||||
|
credentials['refresh_token'] is! String ||
|
||||||
|
credentials['expires_at'] is! String) {
|
||||||
|
stderr.writeln(
|
||||||
|
'$todoCredentialsPath is missing id_token/refresh_token/expires_at '
|
||||||
|
'— not serving it.',
|
||||||
|
);
|
||||||
|
request.response.statusCode = HttpStatus.notFound;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The email is a display nicety (so Settings shows an address instead of
|
||||||
|
// a blank), not a credential -- read from the shared config, not from
|
||||||
|
// todoCredentialsPath, which has no email field of its own.
|
||||||
|
String? email;
|
||||||
|
final configFile = File(p.join(syncConfigDir, 'firebase.json'));
|
||||||
|
if (configFile.existsSync()) {
|
||||||
|
final config =
|
||||||
|
jsonDecode(await configFile.readAsString()) as Map<String, dynamic>;
|
||||||
|
final configEmail = config['email'];
|
||||||
|
if (configEmail is String && configEmail.isNotEmpty) {
|
||||||
|
email = configEmail;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
request.response.headers.contentType = ContentType.json;
|
||||||
|
request.response.write(jsonEncode({...credentials, 'email': email}));
|
||||||
|
// After, not before writing the response: a request that fails partway
|
||||||
|
// through must remain retryable rather than burning the one serve.
|
||||||
|
_todoCredentialsServed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
156
lib/sync/firebase_account_store.dart
Normal file
156
lib/sync/firebase_account_store.dart
Normal file
@ -0,0 +1,156 @@
|
|||||||
|
/// Where the per-device Firebase account and session live: the OS keystore.
|
||||||
|
///
|
||||||
|
/// Split out of `firebase_backend.dart` for file size; that file re-exports
|
||||||
|
/// this one, so callers import it as before.
|
||||||
|
///
|
||||||
|
/// Nothing here reads `~/.config/crdt-sync/` directly — that is the
|
||||||
|
/// desktop/Python half, reached over the local wrapper's HTTP routes. On
|
||||||
|
/// Android there is no such file.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:developer';
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:todo/desktop/wrapper_server.dart' show kSyncCredentialsPath;
|
||||||
|
|
||||||
|
/// Same options the GitHub token uses: off Android's deprecated
|
||||||
|
/// `encryptedSharedPreferences` path, and libsecret on Linux.
|
||||||
|
const _secure = FlutterSecureStorage();
|
||||||
|
|
||||||
|
// Everything below reaches the OS keystore through a platform channel, which
|
||||||
|
// `flutter test` has no binding for -- the same reason `main.dart` and
|
||||||
|
// `openRepository()` are excluded. The logic these wrap (parsing, the
|
||||||
|
// public/private split, sign-in) lives in `crdt_sync` and is covered there at
|
||||||
|
// 100%; what is left here is the two-line adapter.
|
||||||
|
// coverage:ignore-start
|
||||||
|
|
||||||
|
/// The keystore-backed home for the Firebase refresh token.
|
||||||
|
SecureCredentialStore credentialStore() => SecureCredentialStore(
|
||||||
|
read: (key) => _secure.read(key: key),
|
||||||
|
write: (key, value) => _secure.write(key: key, value: value),
|
||||||
|
delete: (key) => _secure.delete(key: key),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Reads the per-device account, or null when sync has not been set up.
|
||||||
|
///
|
||||||
|
/// Falls back to the local wrapper when the store is empty, so a desktop
|
||||||
|
/// install can provision itself instead of the account being retyped per
|
||||||
|
/// machine. Tries the seeded Firebase session first (`/sync-credentials`,
|
||||||
|
/// `~/.config/todo/firebase_auth.json` via `seed_session.py --app todo`) --
|
||||||
|
/// the only thing that actually authenticates, since the shared account's
|
||||||
|
/// password grant is retired fleet-wide (see `link_google.py`/
|
||||||
|
/// `seed_session.py` in `~/utils/crdt-sync`) -- then the legacy
|
||||||
|
/// email/password route (`/sync-account`, `~/.config/crdt-sync/`) as a
|
||||||
|
/// fallback for a machine that has not been re-seeded yet. Whichever
|
||||||
|
/// succeeds is written to the store on first success, so the route is
|
||||||
|
/// consulted once rather than being load-bearing forever.
|
||||||
|
///
|
||||||
|
/// [httpClient] is injectable for tests; production opens and closes its own
|
||||||
|
/// per attempted route.
|
||||||
|
Future<FirebaseAccount?> loadAccount({http.Client? httpClient}) async {
|
||||||
|
try {
|
||||||
|
final stored = FirebaseAccount.tryParse(
|
||||||
|
await _secure.read(key: kFirebaseAccountKey),
|
||||||
|
);
|
||||||
|
if (stored != null) return stored;
|
||||||
|
// Disconnect must stick: without this the next launch would silently
|
||||||
|
// re-adopt the account and the button would look broken.
|
||||||
|
if (await _secure.read(key: kSyncAccountOptOutKey) != null) return null;
|
||||||
|
final seeded = await _adoptCredentialsFromWrapper(
|
||||||
|
Uri.base,
|
||||||
|
client: httpClient,
|
||||||
|
);
|
||||||
|
if (seeded != null) return seeded;
|
||||||
|
final provisioned = await accountFromWrapper(Uri.base, client: httpClient);
|
||||||
|
if (provisioned != null) await saveAccount(provisioned);
|
||||||
|
return provisioned;
|
||||||
|
// Broader than Exception on purpose: an Android build has no wrapper, so
|
||||||
|
// `Uri.base` is `file:///` and accountFromWrapper raises an ArgumentError
|
||||||
|
// ("No host specified in URI") -- an Error, which `on Exception` does not
|
||||||
|
// catch. That escaped openFirebase() and killed the whole sync tick, so a
|
||||||
|
// signed-in phone pulled nothing at all.
|
||||||
|
} on Object catch (error, stackTrace) {
|
||||||
|
// Still "not configured" rather than crashing the settings screen -- but
|
||||||
|
// never silent: this hid *why* provisioning failed, which is
|
||||||
|
// indistinguishable from "no account set" until you say so.
|
||||||
|
log(
|
||||||
|
'loadAccount failed; treating this device as not configured',
|
||||||
|
level: 1000,
|
||||||
|
error: error,
|
||||||
|
stackTrace: stackTrace,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetches `todo`'s seeded session from the wrapper's `/sync-credentials`
|
||||||
|
/// route and adopts it: stores the refresh token in [credentialStore] and
|
||||||
|
/// writes an account marker so the Settings screen shows an address instead
|
||||||
|
/// of a blank. Returns the marker on success, null on any failure (route
|
||||||
|
/// disabled, file absent, malformed body, no wrapper at all) -- the caller's
|
||||||
|
/// fallback is simply "not configured".
|
||||||
|
///
|
||||||
|
/// [client] is injectable for tests; production opens and closes its own.
|
||||||
|
Future<FirebaseAccount?> _adoptCredentialsFromWrapper(
|
||||||
|
Uri base, {
|
||||||
|
http.Client? client,
|
||||||
|
}) async {
|
||||||
|
final httpClient = client ?? http.Client();
|
||||||
|
try {
|
||||||
|
final response = await httpClient.get(base.resolve(kSyncCredentialsPath));
|
||||||
|
if (response.statusCode != 200) return null;
|
||||||
|
final body = jsonDecode(utf8.decode(response.bodyBytes));
|
||||||
|
if (body is! Map<String, dynamic>) return null;
|
||||||
|
if (body['id_token'] is! String ||
|
||||||
|
body['refresh_token'] is! String ||
|
||||||
|
body['expires_at'] is! String) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
await credentialStore().save(FirebaseCredentials.fromJson(body));
|
||||||
|
final email = body['email'];
|
||||||
|
final account = FirebaseAccount(
|
||||||
|
email: email is String ? email : '',
|
||||||
|
password: '',
|
||||||
|
);
|
||||||
|
await saveAccount(account);
|
||||||
|
return account;
|
||||||
|
} on Exception {
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
if (client == null) httpClient.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the account from the keystore only, with no wrapper fallback.
|
||||||
|
///
|
||||||
|
/// [loadAccount] falls back to the desktop wrapper's `/sync-account` route
|
||||||
|
/// when the keystore is empty, which on Android resolves to `file:///` and
|
||||||
|
/// throws `No host specified in URI`. Callers that only want to read back an
|
||||||
|
/// account they just wrote — where a fallback would be wrong anyway — use
|
||||||
|
/// this instead.
|
||||||
|
Future<FirebaseAccount?> storedAccount() async =>
|
||||||
|
FirebaseAccount.tryParse(await _secure.read(key: kFirebaseAccountKey));
|
||||||
|
|
||||||
|
/// Stores the per-device account. Keystore only — never prefs, never source.
|
||||||
|
Future<void> saveAccount(FirebaseAccount account) =>
|
||||||
|
_secure.write(key: kFirebaseAccountKey, value: account.toJsonString());
|
||||||
|
|
||||||
|
/// Forgets the account and any cached session.
|
||||||
|
Future<void> clearAccount() async {
|
||||||
|
await _secure.delete(key: kFirebaseAccountKey);
|
||||||
|
// Suppress wrapper re-provisioning; see loadAccount().
|
||||||
|
await _secure.write(key: kSyncAccountOptOutKey, value: 'true');
|
||||||
|
await credentialStore().clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops the account marker alone, leaving the opt-out flag unset.
|
||||||
|
///
|
||||||
|
/// Used when a marker is found with no session behind it: not
|
||||||
|
/// [clearAccount], which also sets the opt-out flag and would stop the
|
||||||
|
/// desktop wrapper re-provisioning after the next sign-in.
|
||||||
|
Future<void> clearAccountMarkerOnly() =>
|
||||||
|
_secure.delete(key: kFirebaseAccountKey);
|
||||||
|
|
||||||
|
// coverage:ignore-end
|
||||||
@ -1,308 +1,24 @@
|
|||||||
/// Wiring for the Firebase backend, during and after the GitHub cutover.
|
/// Wiring for the Firebase backend, during and after the GitHub cutover.
|
||||||
///
|
///
|
||||||
/// Split by what is safe to publish, because this repo is public:
|
/// A barrel over the three files this was split into for size. Import this one
|
||||||
|
/// and you get the whole backend API, exactly as before the split:
|
||||||
///
|
///
|
||||||
/// * [kProject] holds the Web API key and database URL. Both are public
|
/// * `firebase_project.dart` — [kProject], the public project identifiers.
|
||||||
/// identifiers that already ship inside the APK; the security rules, not
|
/// * `firebase_account_store.dart` — the account and refresh token, in the OS
|
||||||
/// their secrecy, are what protect the data.
|
/// keystore, plus the desktop wrapper's self-provisioning fallback.
|
||||||
/// * The account email and password are entered once per device and kept in
|
/// * `firebase_client.dart` — opening a signed-in client, and reporting
|
||||||
/// the OS keystore, next to the GitHub token this app already stores there.
|
/// whether this device can authenticate at all.
|
||||||
|
///
|
||||||
|
/// Split by what is safe to publish, because this repo is public: the project
|
||||||
|
/// identifiers already ship inside the APK and are protected by the security
|
||||||
|
/// rules rather than by secrecy, while the account email and password are
|
||||||
|
/// entered once per device and kept in the OS keystore, next to the GitHub
|
||||||
|
/// token this app already stores there.
|
||||||
///
|
///
|
||||||
/// Nothing here reads `~/.config/crdt-sync/` — that is the desktop/Python
|
/// Nothing here reads `~/.config/crdt-sync/` — that is the desktop/Python
|
||||||
/// half. On Android there is no such file.
|
/// half. On Android there is no such file.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:convert';
|
export 'firebase_account_store.dart';
|
||||||
import 'dart:developer';
|
export 'firebase_client.dart';
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
export 'firebase_project.dart';
|
||||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
import 'package:todo/desktop/wrapper_server.dart' show kSyncCredentialsPath;
|
|
||||||
import 'package:todo/sync/google_sign_in_backend.dart';
|
|
||||||
|
|
||||||
/// The shared `kuhy-syncs` project.
|
|
||||||
///
|
|
||||||
/// `databaseUrl` is the **regional** host. The plain `*.firebaseio.com` form
|
|
||||||
/// answers 404 with a `correctUrl` body rather than an obvious error, which
|
|
||||||
/// reads like an auth failure and wastes a debugging session.
|
|
||||||
const kProject = FirebaseProject(
|
|
||||||
apiKey: 'AIzaSyCF_sA3xCMehAYXK8eND-rAygb9NXXW_8E',
|
|
||||||
databaseUrl:
|
|
||||||
'https://kuhy-syncs-default-rtdb.europe-west1.firebasedatabase.app',
|
|
||||||
);
|
|
||||||
|
|
||||||
/// Same options the GitHub token uses: off Android's deprecated
|
|
||||||
/// `encryptedSharedPreferences` path, and libsecret on Linux.
|
|
||||||
const _secure = FlutterSecureStorage();
|
|
||||||
|
|
||||||
// Everything below reaches the OS keystore through a platform channel, which
|
|
||||||
// `flutter test` has no binding for -- the same reason `main.dart` and
|
|
||||||
// `openRepository()` are excluded. The logic these wrap (parsing, the
|
|
||||||
// public/private split, sign-in) lives in `crdt_sync` and is covered there at
|
|
||||||
// 100%; what is left here is the two-line adapter.
|
|
||||||
// coverage:ignore-start
|
|
||||||
|
|
||||||
/// The keystore-backed home for the Firebase refresh token.
|
|
||||||
SecureCredentialStore credentialStore() => SecureCredentialStore(
|
|
||||||
read: (key) => _secure.read(key: key),
|
|
||||||
write: (key, value) => _secure.write(key: key, value: value),
|
|
||||||
delete: (key) => _secure.delete(key: key),
|
|
||||||
);
|
|
||||||
|
|
||||||
/// Reads the per-device account, or null when sync has not been set up.
|
|
||||||
///
|
|
||||||
/// Falls back to the local wrapper when the store is empty, so a desktop
|
|
||||||
/// install can provision itself instead of the account being retyped per
|
|
||||||
/// machine. Tries the seeded Firebase session first (`/sync-credentials`,
|
|
||||||
/// `~/.config/todo/firebase_auth.json` via `seed_session.py --app todo`) --
|
|
||||||
/// the only thing that actually authenticates, since the shared account's
|
|
||||||
/// password grant is retired fleet-wide (see `link_google.py`/
|
|
||||||
/// `seed_session.py` in `~/utils/crdt-sync`) -- then the legacy
|
|
||||||
/// email/password route (`/sync-account`, `~/.config/crdt-sync/`) as a
|
|
||||||
/// fallback for a machine that has not been re-seeded yet. Whichever
|
|
||||||
/// succeeds is written to the store on first success, so the route is
|
|
||||||
/// consulted once rather than being load-bearing forever.
|
|
||||||
///
|
|
||||||
/// [httpClient] is injectable for tests; production opens and closes its own
|
|
||||||
/// per attempted route.
|
|
||||||
Future<FirebaseAccount?> loadAccount({http.Client? httpClient}) async {
|
|
||||||
try {
|
|
||||||
final stored = FirebaseAccount.tryParse(
|
|
||||||
await _secure.read(key: kFirebaseAccountKey),
|
|
||||||
);
|
|
||||||
if (stored != null) return stored;
|
|
||||||
// Disconnect must stick: without this the next launch would silently
|
|
||||||
// re-adopt the account and the button would look broken.
|
|
||||||
if (await _secure.read(key: kSyncAccountOptOutKey) != null) return null;
|
|
||||||
final seeded = await _adoptCredentialsFromWrapper(
|
|
||||||
Uri.base,
|
|
||||||
client: httpClient,
|
|
||||||
);
|
|
||||||
if (seeded != null) return seeded;
|
|
||||||
final provisioned = await accountFromWrapper(Uri.base, client: httpClient);
|
|
||||||
if (provisioned != null) await saveAccount(provisioned);
|
|
||||||
return provisioned;
|
|
||||||
// Broader than Exception on purpose: an Android build has no wrapper, so
|
|
||||||
// `Uri.base` is `file:///` and accountFromWrapper raises an ArgumentError
|
|
||||||
// ("No host specified in URI") -- an Error, which `on Exception` does not
|
|
||||||
// catch. That escaped openFirebase() and killed the whole sync tick, so a
|
|
||||||
// signed-in phone pulled nothing at all.
|
|
||||||
} on Object catch (error, stackTrace) {
|
|
||||||
// Still "not configured" rather than crashing the settings screen -- but
|
|
||||||
// never silent: this hid *why* provisioning failed, which is
|
|
||||||
// indistinguishable from "no account set" until you say so.
|
|
||||||
log(
|
|
||||||
'loadAccount failed; treating this device as not configured',
|
|
||||||
level: 1000,
|
|
||||||
error: error,
|
|
||||||
stackTrace: stackTrace,
|
|
||||||
);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fetches `todo`'s seeded session from the wrapper's `/sync-credentials`
|
|
||||||
/// route and adopts it: stores the refresh token in [credentialStore] and
|
|
||||||
/// writes an account marker so the Settings screen shows an address instead
|
|
||||||
/// of a blank. Returns the marker on success, null on any failure (route
|
|
||||||
/// disabled, file absent, malformed body, no wrapper at all) -- the caller's
|
|
||||||
/// fallback is simply "not configured".
|
|
||||||
///
|
|
||||||
/// [client] is injectable for tests; production opens and closes its own.
|
|
||||||
Future<FirebaseAccount?> _adoptCredentialsFromWrapper(
|
|
||||||
Uri base, {
|
|
||||||
http.Client? client,
|
|
||||||
}) async {
|
|
||||||
final httpClient = client ?? http.Client();
|
|
||||||
try {
|
|
||||||
final response = await httpClient.get(base.resolve(kSyncCredentialsPath));
|
|
||||||
if (response.statusCode != 200) return null;
|
|
||||||
final body = jsonDecode(utf8.decode(response.bodyBytes));
|
|
||||||
if (body is! Map<String, dynamic>) return null;
|
|
||||||
if (body['id_token'] is! String ||
|
|
||||||
body['refresh_token'] is! String ||
|
|
||||||
body['expires_at'] is! String) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
await credentialStore().save(FirebaseCredentials.fromJson(body));
|
|
||||||
final email = body['email'];
|
|
||||||
final account = FirebaseAccount(
|
|
||||||
email: email is String ? email : '',
|
|
||||||
password: '',
|
|
||||||
);
|
|
||||||
await saveAccount(account);
|
|
||||||
return account;
|
|
||||||
} on Exception {
|
|
||||||
return null;
|
|
||||||
} finally {
|
|
||||||
if (client == null) httpClient.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads the account from the keystore only, with no wrapper fallback.
|
|
||||||
///
|
|
||||||
/// [loadAccount] falls back to the desktop wrapper's `/sync-account` route
|
|
||||||
/// when the keystore is empty, which on Android resolves to `file:///` and
|
|
||||||
/// throws `No host specified in URI`. Callers that only want to read back an
|
|
||||||
/// account they just wrote — where a fallback would be wrong anyway — use
|
|
||||||
/// this instead.
|
|
||||||
Future<FirebaseAccount?> storedAccount() async =>
|
|
||||||
FirebaseAccount.tryParse(await _secure.read(key: kFirebaseAccountKey));
|
|
||||||
|
|
||||||
/// Stores the per-device account. Keystore only — never prefs, never source.
|
|
||||||
Future<void> saveAccount(FirebaseAccount account) =>
|
|
||||||
_secure.write(key: kFirebaseAccountKey, value: account.toJsonString());
|
|
||||||
|
|
||||||
/// Forgets the account and any cached session.
|
|
||||||
Future<void> clearAccount() async {
|
|
||||||
await _secure.delete(key: kFirebaseAccountKey);
|
|
||||||
// Suppress wrapper re-provisioning; see loadAccount().
|
|
||||||
await _secure.write(key: kSyncAccountOptOutKey, value: 'true');
|
|
||||||
await credentialStore().clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a signed-in Firebase client, or null when not configured.
|
|
||||||
///
|
|
||||||
/// Signs in with the stored password only when there is no cached refresh
|
|
||||||
/// token, so the usual path costs no authentication round trip.
|
|
||||||
Future<FirebaseRestClient?> openFirebase() async {
|
|
||||||
final account = await loadAccount();
|
|
||||||
if (account == null) {
|
|
||||||
// A stored refresh token IS a signed-in device, even with no account
|
|
||||||
// marker beside it. Treating the marker as the source of truth is what
|
|
||||||
// made a phone with a live session sync over GitHub and 401 forever --
|
|
||||||
// the credential was in the keystore the whole time, unused.
|
|
||||||
return _clientFromStoredSession();
|
|
||||||
}
|
|
||||||
return firebaseClientFor(
|
|
||||||
config: kProject.configFor(account.email),
|
|
||||||
store: credentialStore(),
|
|
||||||
// A Google-provisioned account stores an empty password. Passing '' would
|
|
||||||
// make firebaseClientFor treat it as a usable credential and sign in with
|
|
||||||
// it, which fails; null correctly means "no password on this device".
|
|
||||||
password: account.password.isEmpty ? null : account.password,
|
|
||||||
// Deliberately NOT passing googleIdToken here. This path runs from
|
|
||||||
// background timers and, in some apps, before runApp -- offering Google
|
|
||||||
// would let a non-interactive tick raise the OS account picker with no
|
|
||||||
// user action behind it. Interactive sign-in goes through
|
|
||||||
// openFirebaseWithGoogle instead.
|
|
||||||
expectedUid: kSyncUid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Signs in with Google alone, for a device that has no account stored yet.
|
|
||||||
///
|
|
||||||
/// This is the one-tap path: [openFirebase] needs an account in the keystore
|
|
||||||
/// to know which email to use, but a fresh install has none. The Google token
|
|
||||||
/// carries the identity, so nothing needs to be typed -- and on success the
|
|
||||||
/// email is written to the keystore so every later launch takes the ordinary
|
|
||||||
/// path.
|
|
||||||
///
|
|
||||||
/// Returns null when the user dismisses the picker or the token is refused;
|
|
||||||
/// throws [FirebaseAuthError] when Google succeeds but resolves to the wrong
|
|
||||||
/// uid, which is a misconfiguration worth surfacing rather than swallowing.
|
|
||||||
///
|
|
||||||
/// On success the account is written to the keystore using the email
|
|
||||||
/// **Firebase reports**, not one read from the UI: a fresh install has no
|
|
||||||
/// email anywhere on the device, so taking it from a text field would persist
|
|
||||||
/// an empty account and send the next launch down the password path with ''.
|
|
||||||
Future<FirebaseRestClient?> openFirebaseWithGoogle({
|
|
||||||
Future<String?> Function()? tokenFetcher,
|
|
||||||
Future<void> Function(FirebaseAccount)? accountSaver,
|
|
||||||
http.Client? httpClient,
|
|
||||||
}) async {
|
|
||||||
final token = await (tokenFetcher ?? googleIdToken)();
|
|
||||||
if (token == null) return null;
|
|
||||||
final auth = FirebaseTokenProvider(
|
|
||||||
apiKey: kProject.apiKey,
|
|
||||||
store: credentialStore(),
|
|
||||||
httpClient: httpClient,
|
|
||||||
);
|
|
||||||
final email = await auth.signInWithGoogle(
|
|
||||||
idToken: token,
|
|
||||||
expectedUid: kSyncUid,
|
|
||||||
);
|
|
||||||
// Saved unconditionally, and deliberately not gated on `email`:
|
|
||||||
// `signInWithIdp` omits that field whenever the Google account hides it, and
|
|
||||||
// gating the write on it returned a working client while persisting nothing,
|
|
||||||
// so the next launch looked unconfigured and fell back to GitHub-only.
|
|
||||||
// The session itself is already durable here -- signInWithGoogle stored the
|
|
||||||
// refresh token -- and that token, not the address, is the credential.
|
|
||||||
// password is empty on purpose: this device has a refresh token and no
|
|
||||||
// password to store. loadAccount() treats the account as configured, and
|
|
||||||
// openFirebase() re-signs-in with Google rather than with an empty
|
|
||||||
// password -- see the googleIdToken argument it passes.
|
|
||||||
await (accountSaver ?? saveAccount)(
|
|
||||||
FirebaseAccount(email: email ?? '', password: ''),
|
|
||||||
);
|
|
||||||
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether this device can actually authenticate against Firebase.
|
|
||||||
///
|
|
||||||
/// True when either half of the state is present: the account marker
|
|
||||||
/// [loadAccount] reads, or a stored refresh token. The token is the half that
|
|
||||||
/// matters -- it is what signs requests -- so reporting the marker alone calls
|
|
||||||
/// a working device "not connected", which is exactly how a phone that was in
|
|
||||||
/// fact syncing looked broken.
|
|
||||||
///
|
|
||||||
/// The marker alone is not enough, though. A revoked refresh token makes the
|
|
||||||
/// library clear the session, and a marker left behind by the sign-in that
|
|
||||||
/// created it would still report "Connected" while every sync failed with
|
|
||||||
/// TOKEN_EXPIRED -- the desktop symptom seen on 2026-08-11. So when a marker
|
|
||||||
/// exists but the session is gone, the marker is the stale half: drop it.
|
|
||||||
Future<bool> isFirebaseConfigured() async {
|
|
||||||
try {
|
|
||||||
final auth = FirebaseTokenProvider(
|
|
||||||
apiKey: kProject.apiKey,
|
|
||||||
store: credentialStore(),
|
|
||||||
);
|
|
||||||
if (await auth.hasSession()) return true;
|
|
||||||
// storedAccount, not loadAccount: on Android the latter falls back to the
|
|
||||||
// desktop wrapper's /sync-account route, which resolves to file:/// and
|
|
||||||
// throws "No host specified in URI" -- observed on the phone, where it
|
|
||||||
// turned a successful sign-in into "Google sign-in failed".
|
|
||||||
if (await storedAccount() == null) return false;
|
|
||||||
// A marker with no session behind it cannot sign a single request. Drop
|
|
||||||
// just the marker so the settings screen offers a sign-in instead of a
|
|
||||||
// dead banner -- not clearAccount(), which also sets the opt-out flag and
|
|
||||||
// would stop the desktop wrapper re-provisioning after the next sign-in.
|
|
||||||
await _secure.delete(key: kFirebaseAccountKey);
|
|
||||||
return false;
|
|
||||||
} on Object catch (error, stackTrace) {
|
|
||||||
log(
|
|
||||||
'session probe failed; reporting this device as not configured',
|
|
||||||
level: 1000,
|
|
||||||
error: error,
|
|
||||||
stackTrace: stackTrace,
|
|
||||||
);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a client built from the keystore's refresh token alone, or null.
|
|
||||||
///
|
|
||||||
/// The recovery path for a device that has a live session but no account
|
|
||||||
/// marker -- the state a Google sign-in used to leave behind. Costs one
|
|
||||||
/// keystore read and no network round trip when there is no session, so it is
|
|
||||||
/// safe on the background-tick path [openFirebase] also serves.
|
|
||||||
Future<FirebaseRestClient?> _clientFromStoredSession() async {
|
|
||||||
try {
|
|
||||||
final auth = FirebaseTokenProvider(
|
|
||||||
apiKey: kProject.apiKey,
|
|
||||||
store: credentialStore(),
|
|
||||||
);
|
|
||||||
if (!await auth.hasSession()) return null;
|
|
||||||
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
|
|
||||||
} on Object catch (error, stackTrace) {
|
|
||||||
log(
|
|
||||||
'stored-session recovery failed; falling back to the GitHub mirror',
|
|
||||||
level: 1000,
|
|
||||||
error: error,
|
|
||||||
stackTrace: stackTrace,
|
|
||||||
);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// coverage:ignore-end
|
|
||||||
|
|||||||
162
lib/sync/firebase_client.dart
Normal file
162
lib/sync/firebase_client.dart
Normal file
@ -0,0 +1,162 @@
|
|||||||
|
/// Opening a signed-in Firebase client, and reporting whether one is possible.
|
||||||
|
///
|
||||||
|
/// Split out of `firebase_backend.dart` for file size; that file re-exports
|
||||||
|
/// this one, so callers import it as before. The credentials these read live
|
||||||
|
/// in the OS keystore — see `firebase_account_store.dart`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:developer';
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:todo/sync/firebase_account_store.dart';
|
||||||
|
import 'package:todo/sync/firebase_project.dart';
|
||||||
|
import 'package:todo/sync/google_sign_in_backend.dart';
|
||||||
|
|
||||||
|
// Reaches the OS keystore through a platform channel, which `flutter test`
|
||||||
|
// has no binding for; see the note in firebase_account_store.dart.
|
||||||
|
// coverage:ignore-start
|
||||||
|
|
||||||
|
/// Returns a signed-in Firebase client, or null when not configured.
|
||||||
|
///
|
||||||
|
/// Signs in with the stored password only when there is no cached refresh
|
||||||
|
/// token, so the usual path costs no authentication round trip.
|
||||||
|
Future<FirebaseRestClient?> openFirebase() async {
|
||||||
|
final account = await loadAccount();
|
||||||
|
if (account == null) {
|
||||||
|
// A stored refresh token IS a signed-in device, even with no account
|
||||||
|
// marker beside it. Treating the marker as the source of truth is what
|
||||||
|
// made a phone with a live session sync over GitHub and 401 forever --
|
||||||
|
// the credential was in the keystore the whole time, unused.
|
||||||
|
return _clientFromStoredSession();
|
||||||
|
}
|
||||||
|
return firebaseClientFor(
|
||||||
|
config: kProject.configFor(account.email),
|
||||||
|
store: credentialStore(),
|
||||||
|
// A Google-provisioned account stores an empty password. Passing '' would
|
||||||
|
// make firebaseClientFor treat it as a usable credential and sign in with
|
||||||
|
// it, which fails; null correctly means "no password on this device".
|
||||||
|
password: account.password.isEmpty ? null : account.password,
|
||||||
|
// Deliberately NOT passing googleIdToken here. This path runs from
|
||||||
|
// background timers and, in some apps, before runApp -- offering Google
|
||||||
|
// would let a non-interactive tick raise the OS account picker with no
|
||||||
|
// user action behind it. Interactive sign-in goes through
|
||||||
|
// openFirebaseWithGoogle instead.
|
||||||
|
expectedUid: kSyncUid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Signs in with Google alone, for a device that has no account stored yet.
|
||||||
|
///
|
||||||
|
/// This is the one-tap path: [openFirebase] needs an account in the keystore
|
||||||
|
/// to know which email to use, but a fresh install has none. The Google token
|
||||||
|
/// carries the identity, so nothing needs to be typed -- and on success the
|
||||||
|
/// email is written to the keystore so every later launch takes the ordinary
|
||||||
|
/// path.
|
||||||
|
///
|
||||||
|
/// Returns null when the user dismisses the picker or the token is refused;
|
||||||
|
/// throws [FirebaseAuthError] when Google succeeds but resolves to the wrong
|
||||||
|
/// uid, which is a misconfiguration worth surfacing rather than swallowing.
|
||||||
|
///
|
||||||
|
/// On success the account is written to the keystore using the email
|
||||||
|
/// **Firebase reports**, not one read from the UI: a fresh install has no
|
||||||
|
/// email anywhere on the device, so taking it from a text field would persist
|
||||||
|
/// an empty account and send the next launch down the password path with ''.
|
||||||
|
Future<FirebaseRestClient?> openFirebaseWithGoogle({
|
||||||
|
Future<String?> Function()? tokenFetcher,
|
||||||
|
Future<void> Function(FirebaseAccount)? accountSaver,
|
||||||
|
http.Client? httpClient,
|
||||||
|
}) async {
|
||||||
|
final token = await (tokenFetcher ?? googleIdToken)();
|
||||||
|
if (token == null) return null;
|
||||||
|
final auth = FirebaseTokenProvider(
|
||||||
|
apiKey: kProject.apiKey,
|
||||||
|
store: credentialStore(),
|
||||||
|
httpClient: httpClient,
|
||||||
|
);
|
||||||
|
final email = await auth.signInWithGoogle(
|
||||||
|
idToken: token,
|
||||||
|
expectedUid: kSyncUid,
|
||||||
|
);
|
||||||
|
// Saved unconditionally, and deliberately not gated on `email`:
|
||||||
|
// `signInWithIdp` omits that field whenever the Google account hides it, and
|
||||||
|
// gating the write on it returned a working client while persisting nothing,
|
||||||
|
// so the next launch looked unconfigured and fell back to GitHub-only.
|
||||||
|
// The session itself is already durable here -- signInWithGoogle stored the
|
||||||
|
// refresh token -- and that token, not the address, is the credential.
|
||||||
|
// password is empty on purpose: this device has a refresh token and no
|
||||||
|
// password to store. loadAccount() treats the account as configured, and
|
||||||
|
// openFirebase() re-signs-in with Google rather than with an empty
|
||||||
|
// password -- see the googleIdToken argument it passes.
|
||||||
|
await (accountSaver ?? saveAccount)(
|
||||||
|
FirebaseAccount(email: email ?? '', password: ''),
|
||||||
|
);
|
||||||
|
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this device can actually authenticate against Firebase.
|
||||||
|
///
|
||||||
|
/// True when either half of the state is present: the account marker
|
||||||
|
/// [loadAccount] reads, or a stored refresh token. The token is the half that
|
||||||
|
/// matters -- it is what signs requests -- so reporting the marker alone calls
|
||||||
|
/// a working device "not connected", which is exactly how a phone that was in
|
||||||
|
/// fact syncing looked broken.
|
||||||
|
///
|
||||||
|
/// The marker alone is not enough, though. A revoked refresh token makes the
|
||||||
|
/// library clear the session, and a marker left behind by the sign-in that
|
||||||
|
/// created it would still report "Connected" while every sync failed with
|
||||||
|
/// TOKEN_EXPIRED -- the desktop symptom seen on 2026-08-11. So when a marker
|
||||||
|
/// exists but the session is gone, the marker is the stale half: drop it.
|
||||||
|
Future<bool> isFirebaseConfigured() async {
|
||||||
|
try {
|
||||||
|
final auth = FirebaseTokenProvider(
|
||||||
|
apiKey: kProject.apiKey,
|
||||||
|
store: credentialStore(),
|
||||||
|
);
|
||||||
|
if (await auth.hasSession()) return true;
|
||||||
|
// storedAccount, not loadAccount: on Android the latter falls back to the
|
||||||
|
// desktop wrapper's /sync-account route, which resolves to file:/// and
|
||||||
|
// throws "No host specified in URI" -- observed on the phone, where it
|
||||||
|
// turned a successful sign-in into "Google sign-in failed".
|
||||||
|
if (await storedAccount() == null) return false;
|
||||||
|
// A marker with no session behind it cannot sign a single request. Drop
|
||||||
|
// just the marker so the settings screen offers a sign-in instead of a
|
||||||
|
// dead banner.
|
||||||
|
await clearAccountMarkerOnly();
|
||||||
|
return false;
|
||||||
|
} on Object catch (error, stackTrace) {
|
||||||
|
log(
|
||||||
|
'session probe failed; reporting this device as not configured',
|
||||||
|
level: 1000,
|
||||||
|
error: error,
|
||||||
|
stackTrace: stackTrace,
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a client built from the keystore's refresh token alone, or null.
|
||||||
|
///
|
||||||
|
/// The recovery path for a device that has a live session but no account
|
||||||
|
/// marker -- the state a Google sign-in used to leave behind. Costs one
|
||||||
|
/// keystore read and no network round trip when there is no session, so it is
|
||||||
|
/// safe on the background-tick path [openFirebase] also serves.
|
||||||
|
Future<FirebaseRestClient?> _clientFromStoredSession() async {
|
||||||
|
try {
|
||||||
|
final auth = FirebaseTokenProvider(
|
||||||
|
apiKey: kProject.apiKey,
|
||||||
|
store: credentialStore(),
|
||||||
|
);
|
||||||
|
if (!await auth.hasSession()) return null;
|
||||||
|
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
|
||||||
|
} on Object catch (error, stackTrace) {
|
||||||
|
log(
|
||||||
|
'stored-session recovery failed; falling back to the GitHub mirror',
|
||||||
|
level: 1000,
|
||||||
|
error: error,
|
||||||
|
stackTrace: stackTrace,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// coverage:ignore-end
|
||||||
24
lib/sync/firebase_project.dart
Normal file
24
lib/sync/firebase_project.dart
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
/// The shared Firebase project identifiers.
|
||||||
|
///
|
||||||
|
/// Its own file because both halves of the backend (the account store and the
|
||||||
|
/// client factory) need it, and neither should have to import the other.
|
||||||
|
///
|
||||||
|
/// Safe to publish, and this repo is public: [kProject] holds the Web API key
|
||||||
|
/// and database URL, both public identifiers that already ship inside the APK.
|
||||||
|
/// The security rules, not their secrecy, are what protect the data. The
|
||||||
|
/// account credentials live in the OS keystore instead — see
|
||||||
|
/// `firebase_account_store.dart`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
|
||||||
|
/// The shared `kuhy-syncs` project.
|
||||||
|
///
|
||||||
|
/// `databaseUrl` is the **regional** host. The plain `*.firebaseio.com` form
|
||||||
|
/// answers 404 with a `correctUrl` body rather than an obvious error, which
|
||||||
|
/// reads like an auth failure and wastes a debugging session.
|
||||||
|
const kProject = FirebaseProject(
|
||||||
|
apiKey: 'AIzaSyCF_sA3xCMehAYXK8eND-rAygb9NXXW_8E',
|
||||||
|
databaseUrl:
|
||||||
|
'https://kuhy-syncs-default-rtdb.europe-west1.firebasedatabase.app',
|
||||||
|
);
|
||||||
121
lib/ui/capture_app_bar.dart
Normal file
121
lib/ui/capture_app_bar.dart
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
/// The capture screen's app bar: note count, and the four actions.
|
||||||
|
///
|
||||||
|
/// Split out of `capture_screen.dart` for file size. Callback-only — the
|
||||||
|
/// screen still owns every action; this just lays the row out.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/frame_stats.dart';
|
||||||
|
|
||||||
|
/// App bar for the capture screen.
|
||||||
|
class CaptureAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||||
|
/// Creates the capture screen's app bar.
|
||||||
|
const CaptureAppBar({
|
||||||
|
required this.repository,
|
||||||
|
required this.advanced,
|
||||||
|
required this.syncing,
|
||||||
|
required this.onNewNote,
|
||||||
|
required this.onSync,
|
||||||
|
required this.onOpenList,
|
||||||
|
required this.onOpenSettings,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Store whose note count is shown live.
|
||||||
|
final NoteRepository repository;
|
||||||
|
|
||||||
|
/// Whether advanced mode is on; hides the manual Sync action when off.
|
||||||
|
final bool advanced;
|
||||||
|
|
||||||
|
/// Whether a sync is in flight, which disables and spins the Sync action.
|
||||||
|
final bool syncing;
|
||||||
|
|
||||||
|
/// Saves the current draft and clears the box for a new one.
|
||||||
|
final VoidCallback onNewNote;
|
||||||
|
|
||||||
|
/// Runs a manual sync.
|
||||||
|
final VoidCallback onSync;
|
||||||
|
|
||||||
|
/// Opens the notes list.
|
||||||
|
final VoidCallback onOpenList;
|
||||||
|
|
||||||
|
/// Opens the settings screen.
|
||||||
|
final VoidCallback onOpenSettings;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return AppBar(
|
||||||
|
actions: [
|
||||||
|
// TEMPORARY: forces continuous frame production so raster cost
|
||||||
|
// can be sampled at each window size. Armed by
|
||||||
|
// TODO_FRAME_STATS=1, which is never set under the test
|
||||||
|
// runner, so the branch is unreachable.
|
||||||
|
// coverage:ignore-start
|
||||||
|
if (frameStatsEnabled)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.only(right: 8),
|
||||||
|
child: Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 18,
|
||||||
|
height: 18,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// coverage:ignore-end
|
||||||
|
// Live count of stored notes, proving local persistence.
|
||||||
|
StreamBuilder<int>(
|
||||||
|
stream: repository.watchCount(),
|
||||||
|
builder: (context, snapshot) {
|
||||||
|
final count = snapshot.data ?? 0;
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(right: 4),
|
||||||
|
child: Center(
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
const Icon(Icons.list_alt_outlined, size: 18),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Text('$count'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'New note',
|
||||||
|
onPressed: onNewNote,
|
||||||
|
icon: const Icon(Icons.add),
|
||||||
|
),
|
||||||
|
if (advanced)
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Sync',
|
||||||
|
onPressed: syncing ? null : onSync,
|
||||||
|
icon: syncing
|
||||||
|
? const SizedBox(
|
||||||
|
width: 18,
|
||||||
|
height: 18,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
)
|
||||||
|
: const Icon(Icons.sync),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Notes',
|
||||||
|
onPressed: onOpenList,
|
||||||
|
icon: const Icon(Icons.list),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Settings',
|
||||||
|
onPressed: onOpenSettings,
|
||||||
|
icon: const Icon(Icons.settings),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
111
lib/ui/capture_draft.dart
Normal file
111
lib/ui/capture_draft.dart
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
/// The capture screen's in-progress note, and how it reaches storage.
|
||||||
|
///
|
||||||
|
/// Split out of `capture_screen.dart` for file size. It is the model behind
|
||||||
|
/// the app's central invariant — every keystroke is already persisted — so it
|
||||||
|
/// is kept free of Flutter state: the screen decides when to rebuild, this
|
||||||
|
/// decides what is saved.
|
||||||
|
///
|
||||||
|
/// The row is created lazily, on the first non-empty keystroke, so an
|
||||||
|
/// untouched template never reaches storage.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/sync/local_backup.dart';
|
||||||
|
import 'package:todo/sync/local_backup_factory.dart';
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
/// Holds the draft being captured and writes it through to [repository].
|
||||||
|
class CaptureDraft {
|
||||||
|
/// Creates a draft writing to [repository].
|
||||||
|
CaptureDraft(this.repository);
|
||||||
|
|
||||||
|
/// Where the draft is persisted on every change.
|
||||||
|
final NoteRepository repository;
|
||||||
|
|
||||||
|
final Uuid _uuid = const Uuid();
|
||||||
|
|
||||||
|
/// When the draft was last written locally; null until the first save.
|
||||||
|
final ValueNotifier<DateTime?> lastSavedAt = ValueNotifier<DateTime?>(null);
|
||||||
|
|
||||||
|
String _text = '';
|
||||||
|
String? _id;
|
||||||
|
DateTime? _createdAt;
|
||||||
|
|
||||||
|
/// The draft's priority, applied to every write.
|
||||||
|
Priority priority = Priority.defaultValue;
|
||||||
|
|
||||||
|
/// The draft's status, applied to every write.
|
||||||
|
Status status = Status.todo;
|
||||||
|
|
||||||
|
/// Persists [text], creating the note row on the first non-empty keystroke.
|
||||||
|
///
|
||||||
|
/// Returns whether the row was created by this call, so the caller can log
|
||||||
|
/// it once rather than on every keystroke.
|
||||||
|
Future<bool> write(String text, {required bool Function() live}) async {
|
||||||
|
_text = text;
|
||||||
|
var created = false;
|
||||||
|
if (_id == null) {
|
||||||
|
// A note is only created once the user actually fills something in, so
|
||||||
|
// an empty template (no section typed yet) never hits storage.
|
||||||
|
if (text.trim().isEmpty) return false;
|
||||||
|
_id = _uuid.v4();
|
||||||
|
_createdAt = DateTime.now();
|
||||||
|
created = true;
|
||||||
|
}
|
||||||
|
await _save(live: live);
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-saves when only priority/status changed.
|
||||||
|
///
|
||||||
|
/// Does nothing before the row exists: the new value is already held here
|
||||||
|
/// and will be applied by the first keystroke that creates it.
|
||||||
|
Future<void> persistMetadata({required bool Function() live}) async {
|
||||||
|
if (_id == null) return;
|
||||||
|
await _save(live: live);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _save({required bool Function() live}) async {
|
||||||
|
final now = DateTime.now();
|
||||||
|
await repository.upsert(
|
||||||
|
Note(
|
||||||
|
id: _id!,
|
||||||
|
text: _text,
|
||||||
|
priority: priority,
|
||||||
|
status: status,
|
||||||
|
createdAt: _createdAt!,
|
||||||
|
updatedAt: now,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (live()) lastSavedAt.value = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forgets the current draft so the next keystroke starts a new note.
|
||||||
|
///
|
||||||
|
/// Nothing is lost: every keystroke was already persisted, which is why
|
||||||
|
/// the field going blank is the only feedback the screen needs to give.
|
||||||
|
void reset() {
|
||||||
|
_text = '';
|
||||||
|
_id = null;
|
||||||
|
_createdAt = null;
|
||||||
|
priority = Priority.defaultValue;
|
||||||
|
status = Status.todo;
|
||||||
|
lastSavedAt.value = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Releases the notifier.
|
||||||
|
void dispose() => lastSavedAt.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
// coverage:ignore-start
|
||||||
|
// Platform file IO for the local backup: BACKLOG.md under ~/todo on desktop
|
||||||
|
// (the path the user's workflow already reads), or the app documents dir on
|
||||||
|
// mobile (which Android Auto Backup includes). Exercised by running the app;
|
||||||
|
// tests inject an in-memory LocalBackup instead.
|
||||||
|
/// The local backup implementation for whichever platform this is.
|
||||||
|
LocalBackup platformLocalBackup(NoteRepository repository) =>
|
||||||
|
createLocalBackup(repository);
|
||||||
|
// coverage:ignore-end
|
||||||
122
lib/ui/capture_meta_row.dart
Normal file
122
lib/ui/capture_meta_row.dart
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
/// The capture screen's metadata controls: the priority/status row and the
|
||||||
|
/// generic dropdown behind it.
|
||||||
|
///
|
||||||
|
/// Split out of `capture_status.dart` for file size. Public only because Dart
|
||||||
|
/// privacy is library-scoped.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
|
||||||
|
/// A compact labelled dropdown for picking an enum value (priority/status).
|
||||||
|
///
|
||||||
|
/// Generic over the enum type [T] so the same control drives both pickers
|
||||||
|
/// without duplication; [labelOf] maps a value to its display string.
|
||||||
|
class MetaDropdown<T> extends StatelessWidget {
|
||||||
|
/// Creates a dropdown showing [value] out of [values].
|
||||||
|
const MetaDropdown({
|
||||||
|
required this.label,
|
||||||
|
required this.value,
|
||||||
|
required this.values,
|
||||||
|
required this.labelOf,
|
||||||
|
required this.onChanged,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Label shown above the control.
|
||||||
|
final String label;
|
||||||
|
|
||||||
|
/// Currently selected value.
|
||||||
|
final T value;
|
||||||
|
|
||||||
|
/// Every selectable value.
|
||||||
|
final List<T> values;
|
||||||
|
|
||||||
|
/// Maps a value to its display string.
|
||||||
|
final String Function(T) labelOf;
|
||||||
|
|
||||||
|
/// Called with the newly picked value.
|
||||||
|
final ValueChanged<T> onChanged;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return InputDecorator(
|
||||||
|
decoration: InputDecoration(
|
||||||
|
labelText: label,
|
||||||
|
isDense: true,
|
||||||
|
border: const OutlineInputBorder(),
|
||||||
|
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||||
|
),
|
||||||
|
child: DropdownButtonHideUnderline(
|
||||||
|
child: DropdownButton<T>(
|
||||||
|
value: value,
|
||||||
|
isDense: true,
|
||||||
|
isExpanded: true,
|
||||||
|
items: [
|
||||||
|
for (final v in values)
|
||||||
|
DropdownMenuItem<T>(value: v, child: Text(labelOf(v))),
|
||||||
|
],
|
||||||
|
onChanged: (v) {
|
||||||
|
if (v != null) onChanged(v);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The draft's priority and status pickers, side by side.
|
||||||
|
///
|
||||||
|
/// Hidden together with the editor's own chrome while the bare guided
|
||||||
|
/// stepper or its entry wizard is up, so the top of the screen stays free of
|
||||||
|
/// noise -- the screen decides that; this only lays the row out.
|
||||||
|
class CaptureMetaRow extends StatelessWidget {
|
||||||
|
/// Creates the metadata row for the current draft values.
|
||||||
|
const CaptureMetaRow({
|
||||||
|
required this.priority,
|
||||||
|
required this.status,
|
||||||
|
required this.onPriorityChanged,
|
||||||
|
required this.onStatusChanged,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The draft's current priority.
|
||||||
|
final Priority priority;
|
||||||
|
|
||||||
|
/// The draft's current status.
|
||||||
|
final Status status;
|
||||||
|
|
||||||
|
/// Called with a newly picked priority.
|
||||||
|
final ValueChanged<Priority> onPriorityChanged;
|
||||||
|
|
||||||
|
/// Called with a newly picked status.
|
||||||
|
final ValueChanged<Status> onStatusChanged;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: MetaDropdown<Priority>(
|
||||||
|
label: 'Priority',
|
||||||
|
value: priority,
|
||||||
|
values: Priority.values,
|
||||||
|
labelOf: (p) => p.label,
|
||||||
|
onChanged: onPriorityChanged,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: MetaDropdown<Status>(
|
||||||
|
label: 'Status',
|
||||||
|
value: status,
|
||||||
|
values: Status.values,
|
||||||
|
labelOf: (s) => s.label,
|
||||||
|
onChanged: onStatusChanged,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -2,86 +2,30 @@ import 'dart:async';
|
|||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
|
||||||
import 'package:todo/analytics/analytics_event.dart';
|
import 'package:todo/analytics/analytics_event.dart';
|
||||||
import 'package:todo/analytics/analytics_service.dart';
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
import 'package:todo/data/app_settings.dart';
|
import 'package:todo/data/app_settings.dart';
|
||||||
import 'package:todo/data/note.dart';
|
import 'package:todo/data/note.dart';
|
||||||
import 'package:todo/data/note_repository.dart';
|
import 'package:todo/data/note_repository.dart';
|
||||||
import 'package:todo/data/note_template.dart';
|
import 'package:todo/data/note_template.dart';
|
||||||
import 'package:todo/frame_stats.dart';
|
|
||||||
import 'package:todo/sync/firebase_backend.dart';
|
import 'package:todo/sync/firebase_backend.dart';
|
||||||
import 'package:todo/sync/local_backup.dart';
|
import 'package:todo/sync/local_backup.dart';
|
||||||
import 'package:todo/sync/local_backup_factory.dart';
|
|
||||||
import 'package:todo/sync/run_sync.dart';
|
|
||||||
import 'package:todo/sync/sync_service.dart';
|
|
||||||
import 'package:todo/sync/sync_settings.dart';
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
|
import 'package:todo/ui/capture_app_bar.dart';
|
||||||
|
import 'package:todo/ui/capture_draft.dart';
|
||||||
|
import 'package:todo/ui/capture_meta_row.dart';
|
||||||
|
import 'package:todo/ui/capture_status.dart';
|
||||||
|
import 'package:todo/ui/capture_status_footer.dart';
|
||||||
|
import 'package:todo/ui/capture_sync_runner.dart';
|
||||||
import 'package:todo/ui/note_editor.dart';
|
import 'package:todo/ui/note_editor.dart';
|
||||||
import 'package:todo/ui/notes_list_screen.dart';
|
import 'package:todo/ui/notes_list_screen.dart';
|
||||||
import 'package:todo/ui/settings_screen.dart';
|
import 'package:todo/ui/settings_screen.dart';
|
||||||
import 'package:uuid/uuid.dart';
|
|
||||||
|
|
||||||
/// The landing screen: an always-focused text box for jotting an idea.
|
part 'capture_screen_sync.dart';
|
||||||
///
|
part 'capture_screen_widget.dart';
|
||||||
/// Per the product goal "no interruptions, immediate", text is persisted
|
|
||||||
/// to local storage on *every* keystroke. A note row is created lazily on
|
|
||||||
/// the first character typed, then updated in place. The "new note" action
|
|
||||||
/// finalises the current idea and clears the field for the next one.
|
|
||||||
class CaptureScreen extends StatefulWidget {
|
|
||||||
/// Creates a [CaptureScreen] backed by [repository].
|
|
||||||
const CaptureScreen({
|
|
||||||
required this.repository,
|
|
||||||
required this.appSettings,
|
|
||||||
this.analytics,
|
|
||||||
this.httpClient,
|
|
||||||
this.localBackup,
|
|
||||||
this.firebaseFactory,
|
|
||||||
this.stateStore,
|
|
||||||
super.key,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// The store the captured note is persisted to on every keystroke.
|
|
||||||
final NoteRepository repository;
|
|
||||||
|
|
||||||
/// App-wide preferences, currently just `advancedMode`: whether the
|
|
||||||
/// priority/status row and the routine save/sync status line are shown.
|
|
||||||
/// A sync failure is always surfaced regardless of this flag.
|
|
||||||
final ValueNotifier<AppSettings> appSettings;
|
|
||||||
|
|
||||||
/// Interaction-only usage analytics (taps, navigation, sync outcomes —
|
|
||||||
/// never note text). Null in tests that don't exercise it, so the prefs
|
|
||||||
/// round-trip `logEvent` does on every call never has to be awaited by a
|
|
||||||
/// test that didn't ask for it.
|
|
||||||
final AnalyticsService? analytics;
|
|
||||||
|
|
||||||
/// Builds the Firebase backend. Injected so tests can supply a fake, or
|
|
||||||
/// null to assert the pre-migration GitHub-only path still works.
|
|
||||||
final Future<FirebaseRestClient?> Function()? firebaseFactory;
|
|
||||||
|
|
||||||
/// Revision cache. Injected so tests need no application-support directory.
|
|
||||||
final SyncStateStore? stateStore;
|
|
||||||
|
|
||||||
/// Injectable HTTP client for the sync path. Production leaves this null
|
|
||||||
/// (the GitHubClient creates its own); tests pass a mock so the configured
|
|
||||||
/// sync flow can be exercised without real network access.
|
|
||||||
final http.Client? httpClient;
|
|
||||||
|
|
||||||
/// Injectable local-disk backup. Production leaves this null (a platform
|
|
||||||
/// file-backed instance is created); tests pass a fake with in-memory IO.
|
|
||||||
final LocalBackup? localBackup;
|
|
||||||
|
|
||||||
/// How long focus must stay lost before a background sync fires. Public so
|
|
||||||
/// tests can pump exactly past it.
|
|
||||||
static const autoSyncDebounce = Duration(seconds: 5);
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<CaptureScreen> createState() => _CaptureScreenState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _CaptureScreenState extends State<CaptureScreen>
|
class _CaptureScreenState extends State<CaptureScreen>
|
||||||
with WidgetsBindingObserver {
|
with WidgetsBindingObserver {
|
||||||
static const _uuid = Uuid();
|
|
||||||
|
|
||||||
/// Single-flight guard so a launch sync and a background sync never overlap.
|
/// Single-flight guard so a launch sync and a background sync never overlap.
|
||||||
bool _autoSyncing = false;
|
bool _autoSyncing = false;
|
||||||
|
|
||||||
@ -92,25 +36,19 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
|
|
||||||
/// Latest assembled text from the editor; persisted on change and re-saved
|
/// Latest assembled text from the editor; persisted on change and re-saved
|
||||||
/// when only priority/status change.
|
/// when only priority/status change.
|
||||||
String _draftText = '';
|
|
||||||
|
|
||||||
/// Bumped on save to recreate the editor with a fresh, empty template.
|
/// Bumped on save to recreate the editor with a fresh, empty template.
|
||||||
int _editorGeneration = 0;
|
int _editorGeneration = 0;
|
||||||
|
|
||||||
/// Id of the note currently being edited, or null before the first
|
/// Id of the note currently being edited, or null before the first
|
||||||
/// keystroke of a fresh draft.
|
/// keystroke of a fresh draft.
|
||||||
String? _draftId;
|
|
||||||
DateTime? _draftCreatedAt;
|
|
||||||
|
|
||||||
/// Time of the last local save, shown in the tiny save indicator. A notifier
|
/// Time of the last local save, shown in the tiny save indicator. A notifier
|
||||||
/// (not a `setState` field) so a keystroke updates only that one line of text
|
/// (not a `setState` field) so a keystroke updates only that one line of text
|
||||||
/// instead of rebuilding the AppBar, dropdowns, and editor every character.
|
/// instead of rebuilding the AppBar, dropdowns, and editor every character.
|
||||||
final ValueNotifier<DateTime?> _lastSavedAt = ValueNotifier<DateTime?>(null);
|
|
||||||
|
|
||||||
/// Priority/status applied to the current draft. Chosen before or during
|
/// Priority/status applied to the current draft. Chosen before or during
|
||||||
/// typing; persisted on the first keystroke and on every later change.
|
/// typing; persisted on the first keystroke and on every later change.
|
||||||
Priority _draftPriority = Priority.defaultValue;
|
|
||||||
Status _draftStatus = Status.todo;
|
|
||||||
|
|
||||||
SyncSettings? _settings;
|
SyncSettings? _settings;
|
||||||
bool _syncing = false;
|
bool _syncing = false;
|
||||||
@ -118,16 +56,25 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
/// Outcome of the most recent sync attempt (manual or automatic), driving
|
/// Outcome of the most recent sync attempt (manual or automatic), driving
|
||||||
/// the tiny status line under the editor. Persisted so a failure that
|
/// the tiny status line under the editor. Persisted so a failure that
|
||||||
/// happened just before the app closed is still visible on next launch.
|
/// happened just before the app closed is still visible on next launch.
|
||||||
final ValueNotifier<SyncStatus?> _lastSync = ValueNotifier<SyncStatus?>(null);
|
/// The note being captured, and its write-through to storage.
|
||||||
|
late final CaptureDraft _draft = CaptureDraft(widget.repository);
|
||||||
|
|
||||||
|
final SyncStatusStore _syncStatus = SyncStatusStore();
|
||||||
|
|
||||||
|
/// Runs sync passes and records their outcome; see [CaptureSyncRunner].
|
||||||
|
late final CaptureSyncRunner _runner = CaptureSyncRunner(
|
||||||
|
repository: widget.repository,
|
||||||
|
status: _syncStatus,
|
||||||
|
analytics: widget.analytics,
|
||||||
|
httpClient: widget.httpClient,
|
||||||
|
firebaseFactory: widget.firebaseFactory,
|
||||||
|
stateStore: widget.stateStore,
|
||||||
|
);
|
||||||
|
|
||||||
/// Debounces focus-loss sync triggers so desktop alt-tab flicker doesn't
|
/// Debounces focus-loss sync triggers so desktop alt-tab flicker doesn't
|
||||||
/// hammer GitHub with a request per focus change.
|
/// hammer GitHub with a request per focus change.
|
||||||
Timer? _autoSyncDebounce;
|
Timer? _autoSyncDebounce;
|
||||||
|
|
||||||
static const _kLastSyncTime = 'sync.lastTime';
|
|
||||||
static const _kLastSyncOk = 'sync.lastOk';
|
|
||||||
static const _kLastSyncDetail = 'sync.lastDetail';
|
|
||||||
|
|
||||||
/// Hides the Priority/Status row while the editor's own bare-guided chrome
|
/// Hides the Priority/Status row while the editor's own bare-guided chrome
|
||||||
/// (template/mode selectors) is also hidden, so the two stay in lockstep.
|
/// (template/mode selectors) is also hidden, so the two stay in lockstep.
|
||||||
bool _chromeVisible = true;
|
bool _chromeVisible = true;
|
||||||
@ -135,26 +82,12 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
/// When this session started, for the duration on the `app_close` event.
|
/// When this session started, for the duration on the `app_close` event.
|
||||||
final DateTime _sessionStart = DateTime.now();
|
final DateTime _sessionStart = DateTime.now();
|
||||||
|
|
||||||
/// Logs an interaction event without blocking the caller on the prefs
|
|
||||||
/// round-trip `AnalyticsService.logEvent` does. A no-op when
|
|
||||||
/// [CaptureScreen.analytics] is null (tests that don't exercise it).
|
|
||||||
void _logEvent(String name, {Map<String, Object?> params = const {}}) {
|
|
||||||
final analytics = widget.analytics;
|
|
||||||
if (analytics == null) return;
|
|
||||||
unawaited(
|
|
||||||
analytics.logEvent(
|
|
||||||
AnalyticsEvent(name: name, timestamp: DateTime.now(), params: params),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_logEvent('app_open');
|
_logEvent('app_open');
|
||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
_localBackup =
|
_localBackup = widget.localBackup ?? platformLocalBackup(widget.repository);
|
||||||
widget.localBackup ?? _platformLocalBackup(widget.repository);
|
|
||||||
// Recover from the local backup first (covers an empty DB after a wipe),
|
// Recover from the local backup first (covers an empty DB after a wipe),
|
||||||
// then keep the backup current as notes change. The change tick is O(1) per
|
// then keep the backup current as notes change. The change tick is O(1) per
|
||||||
// write; the backup pulls the notes itself only when its debounce fires.
|
// write; the backup pulls the notes itself only when its debounce fires.
|
||||||
@ -189,74 +122,33 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
_autoSyncDebounce?.cancel();
|
_autoSyncDebounce?.cancel();
|
||||||
unawaited(_changesSub?.cancel());
|
unawaited(_changesSub?.cancel());
|
||||||
_localBackup.dispose();
|
_localBackup.dispose();
|
||||||
_lastSavedAt.dispose();
|
_draft.dispose();
|
||||||
_lastSync.dispose();
|
_syncStatus.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reloads the persisted last-sync outcome so the status line survives a
|
@override
|
||||||
/// restart (a failure just before closing must not disappear).
|
Widget build(BuildContext context) {
|
||||||
Future<void> _restoreSyncStatus() async {
|
return ValueListenableBuilder<AppSettings>(
|
||||||
final prefs = await SharedPreferences.getInstance();
|
valueListenable: widget.appSettings,
|
||||||
final time = DateTime.tryParse(prefs.getString(_kLastSyncTime) ?? '');
|
builder: (context, settings, _) {
|
||||||
if (!mounted || time == null || _lastSync.value != null) return;
|
final advanced = settings.advancedMode;
|
||||||
_lastSync.value = SyncStatus(
|
return Scaffold(
|
||||||
time: time,
|
appBar: CaptureAppBar(
|
||||||
ok: prefs.getBool(_kLastSyncOk) ?? true,
|
repository: widget.repository,
|
||||||
detail: prefs.getString(_kLastSyncDetail) ?? '',
|
advanced: advanced,
|
||||||
|
syncing: _syncing,
|
||||||
|
onNewNote: _saveAndReset,
|
||||||
|
onSync: _sync,
|
||||||
|
onOpenList: _openList,
|
||||||
|
onOpenSettings: _openSettings,
|
||||||
|
),
|
||||||
|
body: _captureBody(advanced: advanced),
|
||||||
|
);
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Records a sync outcome in the UI notifier and persists it.
|
|
||||||
Future<void> _recordSyncStatus({
|
|
||||||
required bool ok,
|
|
||||||
required String detail,
|
|
||||||
}) async {
|
|
||||||
final status = SyncStatus(time: DateTime.now(), ok: ok, detail: detail);
|
|
||||||
if (mounted) _lastSync.value = status;
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
|
||||||
await prefs.setString(_kLastSyncTime, status.time.toIso8601String());
|
|
||||||
await prefs.setBool(_kLastSyncOk, ok);
|
|
||||||
await prefs.setString(_kLastSyncDetail, detail);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Human-readable one-liner for a sync outcome, shared by the snackbar and
|
|
||||||
/// the status line. Skipped files are called out so a peer device silently
|
|
||||||
/// dropping out of the merge is visible.
|
|
||||||
///
|
|
||||||
/// Firebase-vs-GitHub-only is called out too, and first, because it used
|
|
||||||
/// to read identically either way: "Synced ... merged N device(s))" while
|
|
||||||
/// disconnected from Firebase looked exactly like success, which is
|
|
||||||
/// precisely how a desktop stuck syncing over the GitHub mirror alone
|
|
||||||
/// went unnoticed for days.
|
|
||||||
static String _describe(SyncResult result) {
|
|
||||||
final skipped = result.skippedFiles.length;
|
|
||||||
final backend = result.firebaseConnected
|
|
||||||
? ''
|
|
||||||
: 'GitHub-only (Firebase not connected) — ';
|
|
||||||
return '$backend'
|
|
||||||
'merged ${result.mergedDevices} device(s)'
|
|
||||||
'${skipped == 0 ? '' : ', skipped $skipped unreadable file(s)'}';
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Restores notes from the local backup file, but only into an empty DB so a
|
|
||||||
/// stale backup never clobbers existing notes (merge-by-id stays safe too).
|
|
||||||
Future<void> _recoverFromBackup() async {
|
|
||||||
final existing = await widget.repository.listNotes();
|
|
||||||
if (existing.isNotEmpty) return;
|
|
||||||
final recovered = await _localBackup.recover();
|
|
||||||
if (recovered.isNotEmpty) await widget.repository.importNotes(recovered);
|
|
||||||
}
|
|
||||||
|
|
||||||
// coverage:ignore-start
|
|
||||||
// Platform file IO for the local backup: BACKLOG.md under ~/todo on desktop
|
|
||||||
// (the path the user's workflow already reads), or the app documents dir on
|
|
||||||
// mobile (which Android Auto Backup includes). Exercised by running the app;
|
|
||||||
// tests inject an in-memory LocalBackup instead.
|
|
||||||
static LocalBackup _platformLocalBackup(NoteRepository repository) =>
|
|
||||||
createLocalBackup(repository);
|
|
||||||
// coverage:ignore-end
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||||
// Push on background so the remote (the durable store) stays near-current.
|
// Push on background so the remote (the durable store) stays near-current.
|
||||||
@ -282,53 +174,6 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Best-effort background sync: no snackbar, skips when unconfigured, and
|
|
||||||
/// never overlaps itself. Failures are not swallowed silently — the outcome
|
|
||||||
/// lands in the status line so drift can't go unnoticed for days.
|
|
||||||
Future<void> _autoSync() async {
|
|
||||||
final settings = _settings;
|
|
||||||
if (_autoSyncing || settings == null) return;
|
|
||||||
// Either backend counts. `isConfigured` means "has a GitHub token", so
|
|
||||||
// gating on it alone silently skips every sync on a device connected
|
|
||||||
// only to Firebase -- and once the mirror is retired that is every
|
|
||||||
// device.
|
|
||||||
if (!settings.isConfigured && await openFirebase() == null) return;
|
|
||||||
_autoSyncing = true;
|
|
||||||
try {
|
|
||||||
final run = await runSync(
|
|
||||||
widget.repository,
|
|
||||||
settings,
|
|
||||||
appSettings: widget.appSettings.value,
|
|
||||||
analytics: widget.analytics,
|
|
||||||
httpClient: widget.httpClient,
|
|
||||||
firebaseFactory: widget.firebaseFactory,
|
|
||||||
stateStore: widget.stateStore,
|
|
||||||
);
|
|
||||||
_adoptReconciledSettings(run.appSettings);
|
|
||||||
final detail = _describe(run.syncResult);
|
|
||||||
await _recordSyncStatus(ok: true, detail: detail);
|
|
||||||
_logEvent(
|
|
||||||
'sync_result',
|
|
||||||
params: {'ok': true, 'auto': true, 'detail': detail},
|
|
||||||
);
|
|
||||||
} on Exception catch (e) {
|
|
||||||
// Offline or a transient GitHub error: still no snackbar (this path
|
|
||||||
// must never interrupt capture), but the status line shows it.
|
|
||||||
await _recordSyncStatus(ok: false, detail: '$e');
|
|
||||||
_logEvent('sync_result', params: {'ok': false, 'auto': true});
|
|
||||||
} finally {
|
|
||||||
_autoSyncing = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Applies a settings snapshot reconciled during a sync pass, when it is
|
|
||||||
/// newer than what this screen already holds (the toggle in Settings may
|
|
||||||
/// have written a newer value locally in between, which must win).
|
|
||||||
void _adoptReconciledSettings(AppSettings? reconciled) {
|
|
||||||
if (!mounted) return;
|
|
||||||
widget.appSettings.value = widget.appSettings.value.adopt(reconciled);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Opens the settings screen and adopts any saved configuration.
|
/// Opens the settings screen and adopts any saved configuration.
|
||||||
Future<void> _openSettings() async {
|
Future<void> _openSettings() async {
|
||||||
_logEvent('screen_view', params: {'screen': 'settings'});
|
_logEvent('screen_view', params: {'screen': 'settings'});
|
||||||
@ -353,17 +198,6 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
setState(() => _settings = fresh);
|
setState(() => _settings = fresh);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _openList() {
|
|
||||||
_logEvent('screen_view', params: {'screen': 'notes_list'});
|
|
||||||
unawaited(
|
|
||||||
Navigator.of(context).push<void>(
|
|
||||||
MaterialPageRoute(
|
|
||||||
builder: (_) => NotesListScreen(repository: widget.repository),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs a full sync, routing to settings first if not yet configured.
|
/// Runs a full sync, routing to settings first if not yet configured.
|
||||||
Future<void> _sync() async {
|
Future<void> _sync() async {
|
||||||
final settings = _settings ?? await SyncSettings.load();
|
final settings = _settings ?? await SyncSettings.load();
|
||||||
@ -374,366 +208,39 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
}
|
}
|
||||||
setState(() => _syncing = true);
|
setState(() => _syncing = true);
|
||||||
try {
|
try {
|
||||||
final run = await runSync(
|
final outcome = await _runner.run(
|
||||||
widget.repository,
|
settings: settings,
|
||||||
settings,
|
|
||||||
appSettings: widget.appSettings.value,
|
appSettings: widget.appSettings.value,
|
||||||
analytics: widget.analytics,
|
live: () => mounted,
|
||||||
httpClient: widget.httpClient,
|
|
||||||
firebaseFactory: widget.firebaseFactory,
|
|
||||||
stateStore: widget.stateStore,
|
|
||||||
);
|
);
|
||||||
_adoptReconciledSettings(run.appSettings);
|
if (outcome.ok) _adoptReconciledSettings(outcome.reconciled);
|
||||||
final detail = _describe(run.syncResult);
|
|
||||||
await _recordSyncStatus(ok: true, detail: detail);
|
|
||||||
_logEvent(
|
_logEvent(
|
||||||
'sync_result',
|
'sync_result',
|
||||||
params: {'ok': true, 'auto': false, 'detail': detail},
|
params: {
|
||||||
|
'ok': outcome.ok,
|
||||||
|
'auto': false,
|
||||||
|
if (outcome.ok) 'detail': outcome.detail,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
_showSnack(
|
||||||
|
outcome.ok
|
||||||
|
? 'Synced: ${outcome.detail}'
|
||||||
|
: 'Sync failed: ${outcome.detail}',
|
||||||
);
|
);
|
||||||
_showSnack('Synced: $detail');
|
|
||||||
} on Exception catch (e) {
|
|
||||||
await _recordSyncStatus(ok: false, detail: '$e');
|
|
||||||
_logEvent('sync_result', params: {'ok': false, 'auto': false});
|
|
||||||
_showSnack('Sync failed: $e');
|
|
||||||
} finally {
|
} finally {
|
||||||
if (mounted) setState(() => _syncing = false);
|
if (mounted) setState(() => _syncing = false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _showSnack(String message) {
|
/// Mirrors the editor's chrome visibility so this screen's own
|
||||||
if (!mounted) return;
|
/// priority/status row hides and shows in step with it.
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
void _setChromeVisible(bool visible) {
|
||||||
SnackBar(content: Text(message), duration: const Duration(seconds: 2)),
|
setState(() => _chromeVisible = visible);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Persists the current text on every change. Creates the note row on
|
/// setState, reachable from this screen's `part` files.
|
||||||
/// the first non-empty keystroke so empty drafts never hit storage.
|
///
|
||||||
Future<void> _onChanged(String text) async {
|
/// setState is protected to State subclasses, so an extension in a part
|
||||||
_draftText = text;
|
/// cannot call it directly even though it is the same library.
|
||||||
if (_draftId == null) {
|
void _rebuild(VoidCallback change) => setState(change);
|
||||||
// A note is only created once the user actually fills something in, so
|
|
||||||
// an empty template (no section typed yet) never hits storage.
|
|
||||||
if (text.trim().isEmpty) return;
|
|
||||||
_draftId = _uuid.v4();
|
|
||||||
_draftCreatedAt = DateTime.now();
|
|
||||||
_logEvent('note_created');
|
|
||||||
}
|
|
||||||
final now = DateTime.now();
|
|
||||||
await widget.repository.upsert(
|
|
||||||
Note(
|
|
||||||
id: _draftId!,
|
|
||||||
text: text,
|
|
||||||
priority: _draftPriority,
|
|
||||||
status: _draftStatus,
|
|
||||||
createdAt: _draftCreatedAt!,
|
|
||||||
updatedAt: now,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if (mounted) _lastSavedAt.value = now;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Applies a new priority to the draft, persisting immediately if a note
|
|
||||||
/// row already exists (otherwise it is applied on the first keystroke).
|
|
||||||
Future<void> _setPriority(Priority priority) async {
|
|
||||||
_logEvent(
|
|
||||||
'priority_changed',
|
|
||||||
params: {'from': _draftPriority.name, 'to': priority.name},
|
|
||||||
);
|
|
||||||
setState(() => _draftPriority = priority);
|
|
||||||
await _persistDraftMeta();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Applies a new status to the draft, persisting immediately if a note
|
|
||||||
/// row already exists.
|
|
||||||
Future<void> _setStatus(Status status) async {
|
|
||||||
_logEvent(
|
|
||||||
'status_changed',
|
|
||||||
params: {'from': _draftStatus.name, 'to': status.name},
|
|
||||||
);
|
|
||||||
setState(() => _draftStatus = status);
|
|
||||||
await _persistDraftMeta();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Re-saves the draft's metadata when only priority/status changed.
|
|
||||||
Future<void> _persistDraftMeta() async {
|
|
||||||
if (_draftId == null) return;
|
|
||||||
final now = DateTime.now();
|
|
||||||
await widget.repository.upsert(
|
|
||||||
Note(
|
|
||||||
id: _draftId!,
|
|
||||||
text: _draftText,
|
|
||||||
priority: _draftPriority,
|
|
||||||
status: _draftStatus,
|
|
||||||
createdAt: _draftCreatedAt!,
|
|
||||||
updatedAt: now,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if (mounted) _lastSavedAt.value = now;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Finalises the current idea and resets the field to a fresh template.
|
|
||||||
/// The field going blank is the only feedback needed — autosave already
|
|
||||||
/// persisted every keystroke, so there is nothing left to confirm.
|
|
||||||
void _saveAndReset() {
|
|
||||||
_logEvent('new_note_reset');
|
|
||||||
setState(() {
|
|
||||||
_editorGeneration++; // recreate the editor with a fresh template
|
|
||||||
_draftText = '';
|
|
||||||
_draftId = null;
|
|
||||||
_draftCreatedAt = null;
|
|
||||||
_draftPriority = Priority.defaultValue;
|
|
||||||
_draftStatus = Status.todo;
|
|
||||||
_chromeVisible = true;
|
|
||||||
});
|
|
||||||
_lastSavedAt.value = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final theme = Theme.of(context);
|
|
||||||
return ValueListenableBuilder<AppSettings>(
|
|
||||||
valueListenable: widget.appSettings,
|
|
||||||
builder: (context, settings, _) {
|
|
||||||
final advanced = settings.advancedMode;
|
|
||||||
return Scaffold(
|
|
||||||
appBar: AppBar(
|
|
||||||
actions: [
|
|
||||||
// TEMPORARY: forces continuous frame production so raster cost
|
|
||||||
// can be sampled at each window size. Armed by
|
|
||||||
// TODO_FRAME_STATS=1, which is never set under the test
|
|
||||||
// runner, so the branch is unreachable.
|
|
||||||
// coverage:ignore-start
|
|
||||||
if (frameStatsEnabled)
|
|
||||||
const Padding(
|
|
||||||
padding: EdgeInsets.only(right: 8),
|
|
||||||
child: Center(
|
|
||||||
child: SizedBox(
|
|
||||||
width: 18,
|
|
||||||
height: 18,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
// coverage:ignore-end
|
|
||||||
// Live count of stored notes, proving local persistence.
|
|
||||||
StreamBuilder<int>(
|
|
||||||
stream: widget.repository.watchCount(),
|
|
||||||
builder: (context, snapshot) {
|
|
||||||
final count = snapshot.data ?? 0;
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.only(right: 4),
|
|
||||||
child: Center(
|
|
||||||
child: Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
const Icon(Icons.list_alt_outlined, size: 18),
|
|
||||||
const SizedBox(width: 4),
|
|
||||||
Text('$count'),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
IconButton(
|
|
||||||
tooltip: 'New note',
|
|
||||||
onPressed: _saveAndReset,
|
|
||||||
icon: const Icon(Icons.add),
|
|
||||||
),
|
|
||||||
if (advanced)
|
|
||||||
IconButton(
|
|
||||||
tooltip: 'Sync',
|
|
||||||
onPressed: _syncing ? null : _sync,
|
|
||||||
icon: _syncing
|
|
||||||
? const SizedBox(
|
|
||||||
width: 18,
|
|
||||||
height: 18,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
)
|
|
||||||
: const Icon(Icons.sync),
|
|
||||||
),
|
|
||||||
IconButton(
|
|
||||||
tooltip: 'Notes',
|
|
||||||
onPressed: _openList,
|
|
||||||
icon: const Icon(Icons.list),
|
|
||||||
),
|
|
||||||
IconButton(
|
|
||||||
tooltip: 'Settings',
|
|
||||||
onPressed: _openSettings,
|
|
||||||
icon: const Icon(Icons.settings),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
body: Padding(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
// Hidden together with the editor's own chrome while the
|
|
||||||
// bare guided stepper or its entry wizard is up, so the top
|
|
||||||
// of the screen stays free of noise. Also hidden outright
|
|
||||||
// when advanced mode is off.
|
|
||||||
if (advanced && _chromeVisible) ...[
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: _MetaDropdown<Priority>(
|
|
||||||
label: 'Priority',
|
|
||||||
value: _draftPriority,
|
|
||||||
values: Priority.values,
|
|
||||||
labelOf: (p) => p.label,
|
|
||||||
onChanged: _setPriority,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
Expanded(
|
|
||||||
child: _MetaDropdown<Status>(
|
|
||||||
label: 'Status',
|
|
||||||
value: _draftStatus,
|
|
||||||
values: Status.values,
|
|
||||||
labelOf: (s) => s.label,
|
|
||||||
onChanged: _setStatus,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
],
|
|
||||||
Expanded(
|
|
||||||
// The key lives on this Expanded, not on NoteEditor itself:
|
|
||||||
// the Row above is conditionally present, which shifts
|
|
||||||
// this Expanded's position in the Column whenever
|
|
||||||
// advancedMode changes at runtime. A key one level too
|
|
||||||
// deep (previously on NoteEditor) doesn't survive that
|
|
||||||
// reposition — Flutter can't match it at the new index,
|
|
||||||
// so it tears down and remounts NoteEditor with an empty
|
|
||||||
// draft, discarding whatever the user was typing.
|
|
||||||
key: ValueKey(_editorGeneration),
|
|
||||||
child: NoteEditor(
|
|
||||||
initialTemplate: NoteTemplate.defaultTemplate,
|
|
||||||
initialMode: NoteEditorMode.raw,
|
|
||||||
advancedMode: advanced,
|
|
||||||
priority: _draftPriority,
|
|
||||||
onPriorityChanged: _setPriority,
|
|
||||||
onChromeVisibleChanged: (visible) =>
|
|
||||||
setState(() => _chromeVisible = visible),
|
|
||||||
autofocus: true,
|
|
||||||
onChanged: _onChanged,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
// Sync is automatic; routine "saved"/"synced" chatter is not
|
|
||||||
// worth showing. Only a sync failure is surfaced, since that
|
|
||||||
// is the one state the user might need to act on.
|
|
||||||
ValueListenableBuilder<SyncStatus?>(
|
|
||||||
valueListenable: _lastSync,
|
|
||||||
builder: (context, status, _) {
|
|
||||||
if (status == null || status.ok) {
|
|
||||||
return const SizedBox.shrink();
|
|
||||||
}
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.only(top: 8),
|
|
||||||
child: Text(
|
|
||||||
'Sync failed at ${_formatTime(status.time)} · '
|
|
||||||
'${status.detail}',
|
|
||||||
style: theme.textTheme.bodySmall?.copyWith(
|
|
||||||
color: theme.colorScheme.error,
|
|
||||||
),
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
if (advanced)
|
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.only(top: 4),
|
|
||||||
child: ValueListenableBuilder<DateTime?>(
|
|
||||||
valueListenable: _lastSavedAt,
|
|
||||||
builder: (context, savedAt, _) => Text(
|
|
||||||
savedAt == null
|
|
||||||
? 'Autosaves as you type'
|
|
||||||
: 'Saved locally at ${_formatTime(savedAt)}',
|
|
||||||
style: theme.textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Formats a timestamp as zero-padded HH:mm:ss for the save indicator.
|
|
||||||
String _formatTime(DateTime t) {
|
|
||||||
String two(int n) => n.toString().padLeft(2, '0');
|
|
||||||
return '${two(t.hour)}:${two(t.minute)}:${two(t.second)}';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Outcome of a sync attempt, shown in the capture screen's status line.
|
|
||||||
class SyncStatus {
|
|
||||||
/// Creates a [SyncStatus] from a completed sync attempt's outcome.
|
|
||||||
const SyncStatus({
|
|
||||||
required this.time,
|
|
||||||
required this.ok,
|
|
||||||
required this.detail,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// When the attempt finished.
|
|
||||||
final DateTime time;
|
|
||||||
|
|
||||||
/// Whether the sync succeeded.
|
|
||||||
final bool ok;
|
|
||||||
|
|
||||||
/// One-line summary: merged/skipped counts on success, the error otherwise.
|
|
||||||
final String detail;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A compact labelled dropdown for picking an enum value (priority/status).
|
|
||||||
///
|
|
||||||
/// Generic over the enum type [T] so the same control drives both pickers
|
|
||||||
/// without duplication; [labelOf] maps a value to its display string.
|
|
||||||
class _MetaDropdown<T> extends StatelessWidget {
|
|
||||||
const _MetaDropdown({
|
|
||||||
required this.label,
|
|
||||||
required this.value,
|
|
||||||
required this.values,
|
|
||||||
required this.labelOf,
|
|
||||||
required this.onChanged,
|
|
||||||
});
|
|
||||||
|
|
||||||
final String label;
|
|
||||||
final T value;
|
|
||||||
final List<T> values;
|
|
||||||
final String Function(T) labelOf;
|
|
||||||
final ValueChanged<T> onChanged;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return InputDecorator(
|
|
||||||
decoration: InputDecoration(
|
|
||||||
labelText: label,
|
|
||||||
isDense: true,
|
|
||||||
border: const OutlineInputBorder(),
|
|
||||||
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
|
||||||
),
|
|
||||||
child: DropdownButtonHideUnderline(
|
|
||||||
child: DropdownButton<T>(
|
|
||||||
value: value,
|
|
||||||
isDense: true,
|
|
||||||
isExpanded: true,
|
|
||||||
items: [
|
|
||||||
for (final v in values)
|
|
||||||
DropdownMenuItem<T>(value: v, child: Text(labelOf(v))),
|
|
||||||
],
|
|
||||||
onChanged: (v) {
|
|
||||||
if (v != null) onChanged(v);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
193
lib/ui/capture_screen_sync.dart
Normal file
193
lib/ui/capture_screen_sync.dart
Normal file
@ -0,0 +1,193 @@
|
|||||||
|
/// The capture screen's sync and navigation behaviour: the lifecycle hook
|
||||||
|
/// that triggers a background push, the manual and automatic sync paths, and
|
||||||
|
/// the two screens this one opens.
|
||||||
|
///
|
||||||
|
/// A `part` of `capture_screen.dart` because every method here reads private
|
||||||
|
/// state (`_settings`, `_syncing`, `_runner`) that Dart scopes to the library.
|
||||||
|
/// The work itself lives in [CaptureSyncRunner]; what stays here is when to
|
||||||
|
/// run it and what the user is shown.
|
||||||
|
part of 'capture_screen.dart';
|
||||||
|
|
||||||
|
extension _CaptureSyncBehaviour on _CaptureScreenState {
|
||||||
|
/// Best-effort background sync: no snackbar, skips when unconfigured, and
|
||||||
|
/// never overlaps itself. Failures are not swallowed silently — the outcome
|
||||||
|
/// lands in the status line so drift can't go unnoticed for days.
|
||||||
|
Future<void> _autoSync() async {
|
||||||
|
final settings = _settings;
|
||||||
|
if (_autoSyncing || settings == null) return;
|
||||||
|
// Either backend counts. `isConfigured` means "has a GitHub token", so
|
||||||
|
// gating on it alone silently skips every sync on a device connected
|
||||||
|
// only to Firebase -- and once the mirror is retired that is every
|
||||||
|
// device.
|
||||||
|
if (!settings.isConfigured && await openFirebase() == null) return;
|
||||||
|
_autoSyncing = true;
|
||||||
|
try {
|
||||||
|
// Offline or a transient GitHub error is reported the same way as
|
||||||
|
// success here: no snackbar (this path must never interrupt capture),
|
||||||
|
// just the status line the runner has already written.
|
||||||
|
final outcome = await _runner.run(
|
||||||
|
settings: settings,
|
||||||
|
appSettings: widget.appSettings.value,
|
||||||
|
live: () => mounted,
|
||||||
|
);
|
||||||
|
if (outcome.ok) _adoptReconciledSettings(outcome.reconciled);
|
||||||
|
_logEvent(
|
||||||
|
'sync_result',
|
||||||
|
params: {
|
||||||
|
'ok': outcome.ok,
|
||||||
|
'auto': true,
|
||||||
|
if (outcome.ok) 'detail': outcome.detail,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
_autoSyncing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies a settings snapshot reconciled during a sync pass, when it is
|
||||||
|
/// newer than what this screen already holds (the toggle in Settings may
|
||||||
|
/// have written a newer value locally in between, which must win).
|
||||||
|
void _adoptReconciledSettings(AppSettings? reconciled) {
|
||||||
|
if (!mounted) return;
|
||||||
|
widget.appSettings.value = widget.appSettings.value.adopt(reconciled);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _openList() {
|
||||||
|
_logEvent('screen_view', params: {'screen': 'notes_list'});
|
||||||
|
unawaited(
|
||||||
|
Navigator.of(context).push<void>(
|
||||||
|
MaterialPageRoute(
|
||||||
|
builder: (_) => NotesListScreen(repository: widget.repository),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _showSnack(String message) {
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text(message), duration: const Duration(seconds: 2)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reloads the persisted last-sync outcome so the status line survives a
|
||||||
|
/// restart. Skipped when the screen went away while the read was in
|
||||||
|
/// flight -- the notifier must not be written after dispose.
|
||||||
|
Future<void> _restoreSyncStatus() async {
|
||||||
|
await _syncStatus.restore(stillLive: () => mounted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restores notes from the local backup file, but only into an empty DB so a
|
||||||
|
/// stale backup never clobbers existing notes (merge-by-id stays safe too).
|
||||||
|
Future<void> _recoverFromBackup() async {
|
||||||
|
final existing = await widget.repository.listNotes();
|
||||||
|
if (existing.isNotEmpty) return;
|
||||||
|
final recovered = await _localBackup.recover();
|
||||||
|
if (recovered.isNotEmpty) await widget.repository.importNotes(recovered);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The composer column: metadata row, editor, and status footer.
|
||||||
|
Widget _captureBody({required bool advanced}) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
// Hidden together with the editor's own chrome while the
|
||||||
|
// bare guided stepper or its entry wizard is up, so the top
|
||||||
|
// of the screen stays free of noise. Also hidden outright
|
||||||
|
// when advanced mode is off.
|
||||||
|
if (advanced && _chromeVisible) ...[
|
||||||
|
CaptureMetaRow(
|
||||||
|
priority: _draft.priority,
|
||||||
|
status: _draft.status,
|
||||||
|
onPriorityChanged: _setPriority,
|
||||||
|
onStatusChanged: _setStatus,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
],
|
||||||
|
Expanded(
|
||||||
|
// The key lives on this Expanded, not on NoteEditor itself:
|
||||||
|
// the Row above is conditionally present, which shifts
|
||||||
|
// this Expanded's position in the Column whenever
|
||||||
|
// advancedMode changes at runtime. A key one level too
|
||||||
|
// deep (previously on NoteEditor) doesn't survive that
|
||||||
|
// reposition — Flutter can't match it at the new index,
|
||||||
|
// so it tears down and remounts NoteEditor with an empty
|
||||||
|
// draft, discarding whatever the user was typing.
|
||||||
|
key: ValueKey(_editorGeneration),
|
||||||
|
child: NoteEditor(
|
||||||
|
initialTemplate: NoteTemplate.defaultTemplate,
|
||||||
|
initialMode: NoteEditorMode.raw,
|
||||||
|
advancedMode: advanced,
|
||||||
|
priority: _draft.priority,
|
||||||
|
onPriorityChanged: _setPriority,
|
||||||
|
onChromeVisibleChanged: _setChromeVisible,
|
||||||
|
autofocus: true,
|
||||||
|
onChanged: _onChanged,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
CaptureStatusFooter(
|
||||||
|
syncStatus: _syncStatus.latest,
|
||||||
|
lastSavedAt: _draft.lastSavedAt,
|
||||||
|
showSavedAt: advanced,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Persists the current text on every change. The note row is created on
|
||||||
|
/// the first non-empty keystroke, which is the one worth logging.
|
||||||
|
Future<void> _onChanged(String text) async {
|
||||||
|
final created = await _draft.write(text, live: () => mounted);
|
||||||
|
if (created) _logEvent('note_created');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies a new priority to the draft, persisting immediately if a note
|
||||||
|
/// row already exists (otherwise it is applied on the first keystroke).
|
||||||
|
Future<void> _setPriority(Priority priority) async {
|
||||||
|
_logEvent(
|
||||||
|
'priority_changed',
|
||||||
|
params: {'from': _draft.priority.name, 'to': priority.name},
|
||||||
|
);
|
||||||
|
_rebuild(() => _draft.priority = priority);
|
||||||
|
await _draft.persistMetadata(live: () => mounted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies a new status to the draft, persisting immediately if a note
|
||||||
|
/// row already exists.
|
||||||
|
Future<void> _setStatus(Status status) async {
|
||||||
|
_logEvent(
|
||||||
|
'status_changed',
|
||||||
|
params: {'from': _draft.status.name, 'to': status.name},
|
||||||
|
);
|
||||||
|
_rebuild(() => _draft.status = status);
|
||||||
|
await _draft.persistMetadata(live: () => mounted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finalises the current idea and resets the field to a fresh template.
|
||||||
|
/// The field going blank is the only feedback needed — autosave already
|
||||||
|
/// persisted every keystroke, so there is nothing left to confirm.
|
||||||
|
void _saveAndReset() {
|
||||||
|
_logEvent('new_note_reset');
|
||||||
|
_rebuild(() {
|
||||||
|
_editorGeneration++; // recreate the editor with a fresh template
|
||||||
|
_draft.reset();
|
||||||
|
_chromeVisible = true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs an interaction event without blocking the caller on the prefs
|
||||||
|
/// round-trip `AnalyticsService.logEvent` does. A no-op when
|
||||||
|
/// [CaptureScreen.analytics] is null (tests that don't exercise it).
|
||||||
|
void _logEvent(String name, {Map<String, Object?> params = const {}}) {
|
||||||
|
final analytics = widget.analytics;
|
||||||
|
if (analytics == null) return;
|
||||||
|
unawaited(
|
||||||
|
analytics.logEvent(
|
||||||
|
AnalyticsEvent(name: name, timestamp: DateTime.now(), params: params),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
64
lib/ui/capture_screen_widget.dart
Normal file
64
lib/ui/capture_screen_widget.dart
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
/// The [CaptureScreen] widget's public surface: its parameters and their
|
||||||
|
/// contracts. The state that drives them lives in `capture_screen.dart`.
|
||||||
|
///
|
||||||
|
/// A `part` rather than a separate library because `createState` returns a
|
||||||
|
/// private class, so the widget and its State cannot be split across
|
||||||
|
/// libraries.
|
||||||
|
part of 'capture_screen.dart';
|
||||||
|
|
||||||
|
/// The landing screen: an always-focused text box for jotting an idea.
|
||||||
|
///
|
||||||
|
/// Per the product goal "no interruptions, immediate", text is persisted
|
||||||
|
/// to local storage on *every* keystroke. A note row is created lazily on
|
||||||
|
/// the first character typed, then updated in place. The "new note" action
|
||||||
|
/// finalises the current idea and clears the field for the next one.
|
||||||
|
class CaptureScreen extends StatefulWidget {
|
||||||
|
/// Creates a [CaptureScreen] backed by [repository].
|
||||||
|
const CaptureScreen({
|
||||||
|
required this.repository,
|
||||||
|
required this.appSettings,
|
||||||
|
this.analytics,
|
||||||
|
this.httpClient,
|
||||||
|
this.localBackup,
|
||||||
|
this.firebaseFactory,
|
||||||
|
this.stateStore,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The store the captured note is persisted to on every keystroke.
|
||||||
|
final NoteRepository repository;
|
||||||
|
|
||||||
|
/// App-wide preferences, currently just `advancedMode`: whether the
|
||||||
|
/// priority/status row and the routine save/sync status line are shown.
|
||||||
|
/// A sync failure is always surfaced regardless of this flag.
|
||||||
|
final ValueNotifier<AppSettings> appSettings;
|
||||||
|
|
||||||
|
/// Interaction-only usage analytics (taps, navigation, sync outcomes —
|
||||||
|
/// never note text). Null in tests that don't exercise it, so the prefs
|
||||||
|
/// round-trip `logEvent` does on every call never has to be awaited by a
|
||||||
|
/// test that didn't ask for it.
|
||||||
|
final AnalyticsService? analytics;
|
||||||
|
|
||||||
|
/// Builds the Firebase backend. Injected so tests can supply a fake, or
|
||||||
|
/// null to assert the pre-migration GitHub-only path still works.
|
||||||
|
final Future<FirebaseRestClient?> Function()? firebaseFactory;
|
||||||
|
|
||||||
|
/// Revision cache. Injected so tests need no application-support directory.
|
||||||
|
final SyncStateStore? stateStore;
|
||||||
|
|
||||||
|
/// Injectable HTTP client for the sync path. Production leaves this null
|
||||||
|
/// (the GitHubClient creates its own); tests pass a mock so the configured
|
||||||
|
/// sync flow can be exercised without real network access.
|
||||||
|
final http.Client? httpClient;
|
||||||
|
|
||||||
|
/// Injectable local-disk backup. Production leaves this null (a platform
|
||||||
|
/// file-backed instance is created); tests pass a fake with in-memory IO.
|
||||||
|
final LocalBackup? localBackup;
|
||||||
|
|
||||||
|
/// How long focus must stay lost before a background sync fires. Public so
|
||||||
|
/// tests can pump exactly past it.
|
||||||
|
static const autoSyncDebounce = Duration(seconds: 5);
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<CaptureScreen> createState() => _CaptureScreenState();
|
||||||
|
}
|
||||||
108
lib/ui/capture_status.dart
Normal file
108
lib/ui/capture_status.dart
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
/// The capture screen's small shared pieces: its sync-status record and the
|
||||||
|
/// metadata dropdown used for priority and status.
|
||||||
|
///
|
||||||
|
/// Split out of `capture_screen.dart` for file size. [SyncStatus] was already
|
||||||
|
/// public; [MetaDropdown] is public only because Dart privacy is
|
||||||
|
/// library-scoped.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
import 'package:todo/sync/sync_service.dart';
|
||||||
|
|
||||||
|
/// Formats [t] as HH:MM:SS for the status line.
|
||||||
|
String formatSyncTime(DateTime t) {
|
||||||
|
String two(int n) => n.toString().padLeft(2, '0');
|
||||||
|
return '${two(t.hour)}:${two(t.minute)}:${two(t.second)}';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Outcome of a sync attempt, shown in the capture screen's status line.
|
||||||
|
class SyncStatus {
|
||||||
|
/// Creates a [SyncStatus] from a completed sync attempt's outcome.
|
||||||
|
const SyncStatus({
|
||||||
|
required this.time,
|
||||||
|
required this.ok,
|
||||||
|
required this.detail,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// When the attempt finished.
|
||||||
|
final DateTime time;
|
||||||
|
|
||||||
|
/// Whether the sync succeeded.
|
||||||
|
final bool ok;
|
||||||
|
|
||||||
|
/// One-line summary: merged/skipped counts on success, the error otherwise.
|
||||||
|
final String detail;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last sync outcome, in a notifier and in shared preferences.
|
||||||
|
///
|
||||||
|
/// Persisted because the status line has to survive a restart: a failure
|
||||||
|
/// recorded just before the app closed must still be visible next launch,
|
||||||
|
/// which is the whole point of showing it.
|
||||||
|
class SyncStatusStore {
|
||||||
|
static const _kTime = 'sync.lastTime';
|
||||||
|
static const _kOk = 'sync.lastOk';
|
||||||
|
static const _kDetail = 'sync.lastDetail';
|
||||||
|
|
||||||
|
/// The latest outcome, or null before the first sync on this install.
|
||||||
|
final ValueNotifier<SyncStatus?> latest = ValueNotifier<SyncStatus?>(null);
|
||||||
|
|
||||||
|
/// Reloads the persisted outcome into [latest].
|
||||||
|
///
|
||||||
|
/// Does nothing when [latest] already holds something: a sync that
|
||||||
|
/// completed while this was in flight is newer than what is on disk.
|
||||||
|
Future<void> restore({bool Function()? stillLive}) async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final time = DateTime.tryParse(prefs.getString(_kTime) ?? '');
|
||||||
|
// Checked after the await, not before: the screen can go away while the
|
||||||
|
// read is in flight, and writing the notifier then is a use-after-dispose.
|
||||||
|
if (stillLive != null && !stillLive()) return;
|
||||||
|
if (time == null || latest.value != null) return;
|
||||||
|
latest.value = SyncStatus(
|
||||||
|
time: time,
|
||||||
|
ok: prefs.getBool(_kOk) ?? true,
|
||||||
|
detail: prefs.getString(_kDetail) ?? '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records an outcome in [latest] and persists it.
|
||||||
|
///
|
||||||
|
/// [live] is false once the screen is gone: the notifier must not be
|
||||||
|
/// written after dispose, but the outcome is still worth persisting.
|
||||||
|
Future<void> record({
|
||||||
|
required bool ok,
|
||||||
|
required String detail,
|
||||||
|
bool live = true,
|
||||||
|
}) async {
|
||||||
|
final status = SyncStatus(time: DateTime.now(), ok: ok, detail: detail);
|
||||||
|
if (live) latest.value = status;
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setString(_kTime, status.time.toIso8601String());
|
||||||
|
await prefs.setBool(_kOk, ok);
|
||||||
|
await prefs.setString(_kDetail, detail);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Releases the notifier.
|
||||||
|
void dispose() => latest.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Human-readable one-liner for a sync outcome, shared by the snackbar and
|
||||||
|
/// the status line. Skipped files are called out so a peer device silently
|
||||||
|
/// dropping out of the merge is visible.
|
||||||
|
///
|
||||||
|
/// Firebase-vs-GitHub-only is called out too, and first, because it used
|
||||||
|
/// to read identically either way: "Synced ... merged N device(s))" while
|
||||||
|
/// disconnected from Firebase looked exactly like success, which is
|
||||||
|
/// precisely how a desktop stuck syncing over the GitHub mirror alone
|
||||||
|
/// went unnoticed for days.
|
||||||
|
String describeSyncResult(SyncResult result) {
|
||||||
|
final skipped = result.skippedFiles.length;
|
||||||
|
final backend = result.firebaseConnected
|
||||||
|
? ''
|
||||||
|
: 'GitHub-only (Firebase not connected) — ';
|
||||||
|
return '$backend'
|
||||||
|
'merged ${result.mergedDevices} device(s)'
|
||||||
|
'${skipped == 0 ? '' : ', skipped $skipped unreadable file(s)'}';
|
||||||
|
}
|
||||||
77
lib/ui/capture_status_footer.dart
Normal file
77
lib/ui/capture_status_footer.dart
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
/// The two status lines under the capture screen's editor.
|
||||||
|
///
|
||||||
|
/// Split out of `capture_screen.dart` for file size. Both are listeners over
|
||||||
|
/// notifiers the screen owns, so this rebuilds without the screen having to.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/ui/capture_status.dart';
|
||||||
|
|
||||||
|
/// A sync-failure line and a local-save line, each rebuilt independently.
|
||||||
|
class CaptureStatusFooter extends StatelessWidget {
|
||||||
|
/// Creates the footer over the screen's two status notifiers.
|
||||||
|
const CaptureStatusFooter({
|
||||||
|
required this.syncStatus,
|
||||||
|
required this.lastSavedAt,
|
||||||
|
required this.showSavedAt,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The latest sync outcome; only failures are rendered.
|
||||||
|
final ValueListenable<SyncStatus?> syncStatus;
|
||||||
|
|
||||||
|
/// When the draft was last written locally, or null before the first save.
|
||||||
|
final ValueListenable<DateTime?> lastSavedAt;
|
||||||
|
|
||||||
|
/// Whether to show the local-save line at all (advanced mode only).
|
||||||
|
final bool showSavedAt;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
// Sync is automatic; routine "saved"/"synced" chatter is not worth
|
||||||
|
// showing. Only a sync failure is surfaced, since that is the one
|
||||||
|
// state the user might need to act on.
|
||||||
|
ValueListenableBuilder<SyncStatus?>(
|
||||||
|
valueListenable: syncStatus,
|
||||||
|
builder: (context, status, _) {
|
||||||
|
if (status == null || status.ok) {
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 8),
|
||||||
|
child: Text(
|
||||||
|
'Sync failed at ${formatSyncTime(status.time)} · '
|
||||||
|
'${status.detail}',
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: theme.colorScheme.error,
|
||||||
|
),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
if (showSavedAt)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 4),
|
||||||
|
child: ValueListenableBuilder<DateTime?>(
|
||||||
|
valueListenable: lastSavedAt,
|
||||||
|
builder: (context, savedAt, _) => Text(
|
||||||
|
savedAt == null
|
||||||
|
? 'Autosaves as you type'
|
||||||
|
: 'Saved locally at ${formatSyncTime(savedAt)}',
|
||||||
|
style: theme.textTheme.bodySmall,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
103
lib/ui/capture_sync_runner.dart
Normal file
103
lib/ui/capture_sync_runner.dart
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
/// Runs a sync pass for the capture screen and reports its outcome.
|
||||||
|
///
|
||||||
|
/// Split out of `capture_screen.dart` for file size, and it de-duplicates the
|
||||||
|
/// two callers at the same time: the manual button and the background tick
|
||||||
|
/// ran byte-identical `runSync` blocks that differed only in whether they
|
||||||
|
/// show a snackbar and what they log.
|
||||||
|
///
|
||||||
|
/// Deliberately has no `BuildContext` and no `setState`: the screen decides
|
||||||
|
/// what to show, this decides what to do.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/sync/run_sync.dart';
|
||||||
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
|
import 'package:todo/ui/capture_status.dart';
|
||||||
|
|
||||||
|
/// What a sync attempt did, in the terms the capture screen cares about.
|
||||||
|
class CaptureSyncOutcome {
|
||||||
|
/// Creates an outcome.
|
||||||
|
const CaptureSyncOutcome({
|
||||||
|
required this.ok,
|
||||||
|
required this.detail,
|
||||||
|
this.reconciled,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Whether the pass completed without throwing.
|
||||||
|
final bool ok;
|
||||||
|
|
||||||
|
/// One-line summary: merged/skipped counts on success, the error otherwise.
|
||||||
|
final String detail;
|
||||||
|
|
||||||
|
/// Settings reconciled during the pass, when the pass succeeded.
|
||||||
|
final AppSettings? reconciled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs sync passes against one repository and settings pair.
|
||||||
|
class CaptureSyncRunner {
|
||||||
|
/// Creates a runner over the screen's injected dependencies.
|
||||||
|
const CaptureSyncRunner({
|
||||||
|
required this.repository,
|
||||||
|
required this.status,
|
||||||
|
this.analytics,
|
||||||
|
this.httpClient,
|
||||||
|
this.firebaseFactory,
|
||||||
|
this.stateStore,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The store being synced.
|
||||||
|
final NoteRepository repository;
|
||||||
|
|
||||||
|
/// Where the outcome is recorded and persisted.
|
||||||
|
final SyncStatusStore status;
|
||||||
|
|
||||||
|
/// Optional analytics sink, passed straight through to [runSync].
|
||||||
|
final AnalyticsService? analytics;
|
||||||
|
|
||||||
|
/// Injected HTTP client, so tests run the real path without network.
|
||||||
|
final http.Client? httpClient;
|
||||||
|
|
||||||
|
/// Injected Firebase client factory, for the same reason.
|
||||||
|
final Future<FirebaseRestClient?> Function()? firebaseFactory;
|
||||||
|
|
||||||
|
/// Injected sync-state store.
|
||||||
|
final SyncStateStore? stateStore;
|
||||||
|
|
||||||
|
/// Runs one pass and records the outcome.
|
||||||
|
///
|
||||||
|
/// [live] is the screen's `mounted` at the moment of recording -- the pass
|
||||||
|
/// still finishes and still persists its outcome after the screen is gone,
|
||||||
|
/// it just must not write the notifier.
|
||||||
|
Future<CaptureSyncOutcome> run({
|
||||||
|
required SyncSettings settings,
|
||||||
|
required AppSettings appSettings,
|
||||||
|
required bool Function() live,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
final result = await runSync(
|
||||||
|
repository,
|
||||||
|
settings,
|
||||||
|
appSettings: appSettings,
|
||||||
|
analytics: analytics,
|
||||||
|
httpClient: httpClient,
|
||||||
|
firebaseFactory: firebaseFactory,
|
||||||
|
stateStore: stateStore,
|
||||||
|
);
|
||||||
|
final detail = describeSyncResult(result.syncResult);
|
||||||
|
await status.record(ok: true, detail: detail, live: live());
|
||||||
|
return CaptureSyncOutcome(
|
||||||
|
ok: true,
|
||||||
|
detail: detail,
|
||||||
|
reconciled: result.appSettings,
|
||||||
|
);
|
||||||
|
} on Exception catch (e) {
|
||||||
|
await status.record(ok: false, detail: '$e', live: live());
|
||||||
|
return CaptureSyncOutcome(ok: false, detail: '$e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
110
lib/ui/device_code_dialog.dart
Normal file
110
lib/ui/device_code_dialog.dart
Normal file
@ -0,0 +1,110 @@
|
|||||||
|
/// The GitHub device-flow dialog: shows the user code, opens the page, and
|
||||||
|
/// polls until the grant is approved.
|
||||||
|
///
|
||||||
|
/// Split out of `github_mirror_screen.dart` for file size; public only
|
||||||
|
/// because Dart privacy is library-scoped.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
|
import 'package:todo/sync/github_device_auth.dart';
|
||||||
|
import 'package:url_launcher/url_launcher.dart';
|
||||||
|
|
||||||
|
/// Dialog shown during the device flow: displays the user code, opens the
|
||||||
|
/// verification page, and polls until authorized — popping the token (or
|
||||||
|
/// null if cancelled / failed).
|
||||||
|
class DeviceCodeDialog extends StatefulWidget {
|
||||||
|
/// Creates the dialog for a pending device-flow grant.
|
||||||
|
const DeviceCodeDialog({
|
||||||
|
required this.device,
|
||||||
|
required this.auth,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The pending grant: user code, verification URL, poll interval.
|
||||||
|
final DeviceCodeResponse device;
|
||||||
|
|
||||||
|
/// Auth client used to poll for the approved token.
|
||||||
|
final GitHubDeviceAuth auth;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<DeviceCodeDialog> createState() => _DeviceCodeDialogState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DeviceCodeDialogState extends State<DeviceCodeDialog> {
|
||||||
|
String? _error;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
unawaited(_poll());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _poll() async {
|
||||||
|
try {
|
||||||
|
final token = await widget.auth.pollForToken(widget.device);
|
||||||
|
if (mounted) Navigator.of(context).pop(token);
|
||||||
|
} on Exception catch (e) {
|
||||||
|
if (mounted) setState(() => _error = '$e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _openPage() async {
|
||||||
|
await Clipboard.setData(ClipboardData(text: widget.device.userCode));
|
||||||
|
await launchUrl(
|
||||||
|
Uri.parse(widget.device.verificationUri),
|
||||||
|
mode: LaunchMode.externalApplication,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return AlertDialog(
|
||||||
|
title: const Text('Authorize on GitHub'),
|
||||||
|
content: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
const Text('Enter this code on GitHub:'),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
SelectableText(
|
||||||
|
widget.device.userCode,
|
||||||
|
style: Theme.of(context).textTheme.headlineSmall,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
if (_error == null)
|
||||||
|
const Row(
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: 16,
|
||||||
|
height: 16,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
SizedBox(width: 12),
|
||||||
|
Expanded(child: Text('Waiting for authorization…')),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
else
|
||||||
|
Text(
|
||||||
|
_error!,
|
||||||
|
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
child: const Text('Cancel'),
|
||||||
|
),
|
||||||
|
FilledButton.icon(
|
||||||
|
onPressed: _openPage,
|
||||||
|
icon: const Icon(Icons.open_in_new),
|
||||||
|
label: const Text('Open GitHub & copy code'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -2,7 +2,6 @@ import 'dart:async';
|
|||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
import 'package:todo/analytics/analytics_service.dart';
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
import 'package:todo/data/app_settings.dart';
|
import 'package:todo/data/app_settings.dart';
|
||||||
@ -10,56 +9,9 @@ import 'package:todo/data/note_repository.dart';
|
|||||||
import 'package:todo/sync/github_device_auth.dart';
|
import 'package:todo/sync/github_device_auth.dart';
|
||||||
import 'package:todo/sync/run_sync.dart';
|
import 'package:todo/sync/run_sync.dart';
|
||||||
import 'package:todo/sync/sync_settings.dart';
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
import 'package:url_launcher/url_launcher.dart';
|
import 'package:todo/ui/device_code_dialog.dart';
|
||||||
|
|
||||||
/// The GitHub mirror screen: cutover-only sync transport, not a peer of
|
part 'github_mirror_screen_widget.dart';
|
||||||
/// Firebase.
|
|
||||||
///
|
|
||||||
/// Kept app-local rather than folded into the shared `sync_settings_ui`
|
|
||||||
/// package because connecting here also triggers an actual note sync via
|
|
||||||
/// [runSync] -- unlike the shared package's Firebase/Backup sections, which
|
|
||||||
/// only save settings. See `lib/ui/settings_screen.dart` for the "Enable
|
|
||||||
/// advanced" toggle and the link to this screen and to the shared Sync
|
|
||||||
/// settings screen.
|
|
||||||
class GitHubMirrorScreen extends StatefulWidget {
|
|
||||||
/// Creates a [GitHubMirrorScreen] pre-filled with [initial] settings.
|
|
||||||
const GitHubMirrorScreen({
|
|
||||||
required this.initial,
|
|
||||||
required this.repository,
|
|
||||||
required this.appSettings,
|
|
||||||
this.analytics,
|
|
||||||
this.httpClient,
|
|
||||||
this.firebaseFactory,
|
|
||||||
this.stateStore,
|
|
||||||
super.key,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// The sync settings loaded when this screen was opened.
|
|
||||||
final SyncSettings initial;
|
|
||||||
|
|
||||||
/// The store a post-connect sync reads from and writes to.
|
|
||||||
final NoteRepository repository;
|
|
||||||
|
|
||||||
/// App-wide preferences, reconciled after a post-connect sync.
|
|
||||||
final ValueNotifier<AppSettings> appSettings;
|
|
||||||
|
|
||||||
/// Interaction-only usage analytics. Null in tests that don't exercise it.
|
|
||||||
final AnalyticsService? analytics;
|
|
||||||
|
|
||||||
/// Optional HTTP client for the GitHub calls (test-connection and device
|
|
||||||
/// flow). Injected by tests; production uses each client's default.
|
|
||||||
final http.Client? httpClient;
|
|
||||||
|
|
||||||
/// Builds the Firebase backend for the post-connect sync. Injected so
|
|
||||||
/// tests can supply a fake.
|
|
||||||
final Future<FirebaseRestClient?> Function()? firebaseFactory;
|
|
||||||
|
|
||||||
/// Revision cache. Injected so tests need no application-support directory.
|
|
||||||
final SyncStateStore? stateStore;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<GitHubMirrorScreen> createState() => _GitHubMirrorScreenState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
||||||
late final TextEditingController _owner = TextEditingController(
|
late final TextEditingController _owner = TextEditingController(
|
||||||
@ -111,7 +63,7 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
|||||||
final token = await showDialog<String>(
|
final token = await showDialog<String>(
|
||||||
context: context,
|
context: context,
|
||||||
barrierDismissible: false,
|
barrierDismissible: false,
|
||||||
builder: (_) => _DeviceCodeDialog(device: device, auth: auth),
|
builder: (_) => DeviceCodeDialog(device: device, auth: auth),
|
||||||
);
|
);
|
||||||
if (token != null && token.isNotEmpty) {
|
if (token != null && token.isNotEmpty) {
|
||||||
setState(() {
|
setState(() {
|
||||||
@ -278,91 +230,3 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Dialog shown during the device flow: displays the user code, opens the
|
|
||||||
/// verification page, and polls until authorized — popping the token (or
|
|
||||||
/// null if cancelled / failed).
|
|
||||||
class _DeviceCodeDialog extends StatefulWidget {
|
|
||||||
const _DeviceCodeDialog({required this.device, required this.auth});
|
|
||||||
|
|
||||||
final DeviceCodeResponse device;
|
|
||||||
final GitHubDeviceAuth auth;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<_DeviceCodeDialog> createState() => _DeviceCodeDialogState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
|
|
||||||
String? _error;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
unawaited(_poll());
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _poll() async {
|
|
||||||
try {
|
|
||||||
final token = await widget.auth.pollForToken(widget.device);
|
|
||||||
if (mounted) Navigator.of(context).pop(token);
|
|
||||||
} on Exception catch (e) {
|
|
||||||
if (mounted) setState(() => _error = '$e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _openPage() async {
|
|
||||||
await Clipboard.setData(ClipboardData(text: widget.device.userCode));
|
|
||||||
await launchUrl(
|
|
||||||
Uri.parse(widget.device.verificationUri),
|
|
||||||
mode: LaunchMode.externalApplication,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return AlertDialog(
|
|
||||||
title: const Text('Authorize on GitHub'),
|
|
||||||
content: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
const Text('Enter this code on GitHub:'),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
SelectableText(
|
|
||||||
widget.device.userCode,
|
|
||||||
style: Theme.of(context).textTheme.headlineSmall,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
if (_error == null)
|
|
||||||
const Row(
|
|
||||||
children: [
|
|
||||||
SizedBox(
|
|
||||||
width: 16,
|
|
||||||
height: 16,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
),
|
|
||||||
SizedBox(width: 12),
|
|
||||||
Expanded(child: Text('Waiting for authorization…')),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
else
|
|
||||||
Text(
|
|
||||||
_error!,
|
|
||||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
actions: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
|
||||||
child: const Text('Cancel'),
|
|
||||||
),
|
|
||||||
FilledButton.icon(
|
|
||||||
onPressed: _openPage,
|
|
||||||
icon: const Icon(Icons.open_in_new),
|
|
||||||
label: const Text('Open GitHub & copy code'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
54
lib/ui/github_mirror_screen_widget.dart
Normal file
54
lib/ui/github_mirror_screen_widget.dart
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
/// The [GitHubMirrorScreen] widget's public surface.
|
||||||
|
///
|
||||||
|
/// A `part` rather than a separate library because `createState` returns a
|
||||||
|
/// private class, so the widget and its State cannot be split apart.
|
||||||
|
part of 'github_mirror_screen.dart';
|
||||||
|
|
||||||
|
/// The GitHub mirror screen: cutover-only sync transport, not a peer of
|
||||||
|
/// Firebase.
|
||||||
|
///
|
||||||
|
/// Kept app-local rather than folded into the shared `sync_settings_ui`
|
||||||
|
/// package because connecting here also triggers an actual note sync via
|
||||||
|
/// [runSync] -- unlike the shared package's Firebase/Backup sections, which
|
||||||
|
/// only save settings. See `lib/ui/settings_screen.dart` for the "Enable
|
||||||
|
/// advanced" toggle and the link to this screen and to the shared Sync
|
||||||
|
/// settings screen.
|
||||||
|
class GitHubMirrorScreen extends StatefulWidget {
|
||||||
|
/// Creates a [GitHubMirrorScreen] pre-filled with [initial] settings.
|
||||||
|
const GitHubMirrorScreen({
|
||||||
|
required this.initial,
|
||||||
|
required this.repository,
|
||||||
|
required this.appSettings,
|
||||||
|
this.analytics,
|
||||||
|
this.httpClient,
|
||||||
|
this.firebaseFactory,
|
||||||
|
this.stateStore,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The sync settings loaded when this screen was opened.
|
||||||
|
final SyncSettings initial;
|
||||||
|
|
||||||
|
/// The store a post-connect sync reads from and writes to.
|
||||||
|
final NoteRepository repository;
|
||||||
|
|
||||||
|
/// App-wide preferences, reconciled after a post-connect sync.
|
||||||
|
final ValueNotifier<AppSettings> appSettings;
|
||||||
|
|
||||||
|
/// Interaction-only usage analytics. Null in tests that don't exercise it.
|
||||||
|
final AnalyticsService? analytics;
|
||||||
|
|
||||||
|
/// Optional HTTP client for the GitHub calls (test-connection and device
|
||||||
|
/// flow). Injected by tests; production uses each client's default.
|
||||||
|
final http.Client? httpClient;
|
||||||
|
|
||||||
|
/// Builds the Firebase backend for the post-connect sync. Injected so
|
||||||
|
/// tests can supply a fake.
|
||||||
|
final Future<FirebaseRestClient?> Function()? firebaseFactory;
|
||||||
|
|
||||||
|
/// Revision cache. Injected so tests need no application-support directory.
|
||||||
|
final SyncStateStore? stateStore;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<GitHubMirrorScreen> createState() => _GitHubMirrorScreenState();
|
||||||
|
}
|
||||||
152
lib/ui/note_actions_sheet.dart
Normal file
152
lib/ui/note_actions_sheet.dart
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
/// The per-note actions sheet shown from the notes list.
|
||||||
|
///
|
||||||
|
/// Split out of `notes_list_screen.dart` for file size; public only because
|
||||||
|
/// Dart privacy is library-scoped.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
import 'package:todo/ui/confirm.dart';
|
||||||
|
|
||||||
|
/// The per-note bottom sheet: status/priority chips, and delete.
|
||||||
|
class NoteActionsSheet extends StatefulWidget {
|
||||||
|
/// Creates the per-note actions sheet for [note].
|
||||||
|
const NoteActionsSheet({
|
||||||
|
required this.note,
|
||||||
|
required this.onChanged,
|
||||||
|
required this.onDelete,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The note being acted on.
|
||||||
|
final Note note;
|
||||||
|
|
||||||
|
/// Called with the edited note whenever a chip changes it.
|
||||||
|
final Future<void> Function(Note) onChanged;
|
||||||
|
|
||||||
|
/// Called once the user confirms deletion.
|
||||||
|
final Future<void> Function() onDelete;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<NoteActionsSheet> createState() => _NoteActionsSheetState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _NoteActionsSheetState extends State<NoteActionsSheet> {
|
||||||
|
late Priority _priority = widget.note.priority;
|
||||||
|
late Status _status = widget.note.status;
|
||||||
|
|
||||||
|
Future<void> _persist() async {
|
||||||
|
await widget.onChanged(
|
||||||
|
widget.note.copyWith(
|
||||||
|
priority: _priority,
|
||||||
|
status: _status,
|
||||||
|
updatedAt: DateTime.now(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final firstLine = noteTitle(widget.note.text);
|
||||||
|
return SafeArea(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
firstLine.isEmpty ? '(empty)' : firstLine,
|
||||||
|
style: Theme.of(context).textTheme.titleMedium,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
_EnumChips<Status>(
|
||||||
|
label: 'Status',
|
||||||
|
values: Status.values,
|
||||||
|
selected: {_status},
|
||||||
|
labelOf: (s) => s.label,
|
||||||
|
onSelected: (s) {
|
||||||
|
setState(() => _status = s);
|
||||||
|
unawaited(_persist());
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
_EnumChips<Priority>(
|
||||||
|
label: 'Priority',
|
||||||
|
values: Priority.values,
|
||||||
|
selected: {_priority},
|
||||||
|
labelOf: (p) => p.label,
|
||||||
|
onSelected: (p) {
|
||||||
|
setState(() => _priority = p);
|
||||||
|
unawaited(_persist());
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
OutlinedButton.icon(
|
||||||
|
icon: const Icon(Icons.delete_outline),
|
||||||
|
label: const Text('Delete note'),
|
||||||
|
style: OutlinedButton.styleFrom(
|
||||||
|
foregroundColor: Theme.of(context).colorScheme.error,
|
||||||
|
),
|
||||||
|
onPressed: () async {
|
||||||
|
final confirmed = await confirmDestructive(
|
||||||
|
context,
|
||||||
|
title: 'Delete note?',
|
||||||
|
message: 'This cannot be undone.',
|
||||||
|
);
|
||||||
|
if (!confirmed) return;
|
||||||
|
await widget.onDelete();
|
||||||
|
if (context.mounted) Navigator.of(context).pop();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Single-select chip row for an enum (used for per-note priority/status).
|
||||||
|
class _EnumChips<T> extends StatelessWidget {
|
||||||
|
const _EnumChips({
|
||||||
|
required this.label,
|
||||||
|
required this.values,
|
||||||
|
required this.selected,
|
||||||
|
required this.labelOf,
|
||||||
|
required this.onSelected,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
final List<T> values;
|
||||||
|
final Set<T> selected;
|
||||||
|
final String Function(T) labelOf;
|
||||||
|
final ValueChanged<T> onSelected;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(label, style: Theme.of(context).textTheme.labelLarge),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
children: [
|
||||||
|
for (final v in values)
|
||||||
|
ChoiceChip(
|
||||||
|
label: Text(labelOf(v)),
|
||||||
|
selected: selected.contains(v),
|
||||||
|
onSelected: (_) => onSelected(v),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
109
lib/ui/note_date_range_field.dart
Normal file
109
lib/ui/note_date_range_field.dart
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
/// The Created / Last-updated date-range control used by the filter sheet.
|
||||||
|
///
|
||||||
|
/// Split out of `notes_list_screen.dart` for file size. Public only because
|
||||||
|
/// Dart privacy is library-scoped and the filter sheet now lives in a
|
||||||
|
/// different file.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
/// A labelled date range shown as presets plus a custom-range picker.
|
||||||
|
class DateRangeField extends StatelessWidget {
|
||||||
|
/// Creates a labelled date-range control.
|
||||||
|
const DateRangeField({
|
||||||
|
required this.label,
|
||||||
|
required this.from,
|
||||||
|
required this.to,
|
||||||
|
required this.onChanged,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Heading shown above the control (e.g. 'Created').
|
||||||
|
final String label;
|
||||||
|
|
||||||
|
/// Start of the selected range, or null when unbounded.
|
||||||
|
final DateTime? from;
|
||||||
|
|
||||||
|
/// End of the selected range, or null when unbounded.
|
||||||
|
final DateTime? to;
|
||||||
|
|
||||||
|
/// Called with the new (from, to); either may be null to clear.
|
||||||
|
final void Function(DateTime? from, DateTime? to) onChanged;
|
||||||
|
|
||||||
|
bool get _hasRange => from != null || to != null;
|
||||||
|
|
||||||
|
/// Sets a preset range of the last [days] days ending today.
|
||||||
|
void _applyDays(int days) {
|
||||||
|
final now = DateTime.now();
|
||||||
|
final today = DateTime(now.year, now.month, now.day);
|
||||||
|
onChanged(today.subtract(Duration(days: days - 1)), today);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickCustom(BuildContext context) async {
|
||||||
|
final now = DateTime.now();
|
||||||
|
final picked = await showDateRangePicker(
|
||||||
|
context: context,
|
||||||
|
firstDate: DateTime(2020),
|
||||||
|
lastDate: DateTime(now.year + 1, 12, 31),
|
||||||
|
initialDateRange: (from != null && to != null)
|
||||||
|
? DateTimeRange(start: from!, end: to!)
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
if (picked != null) onChanged(picked.start, picked.end);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Text(label, style: theme.textTheme.labelLarge),
|
||||||
|
const Spacer(),
|
||||||
|
if (_hasRange)
|
||||||
|
Text(_rangeLabel(), style: theme.textTheme.bodySmall),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
children: [
|
||||||
|
ActionChip(
|
||||||
|
label: const Text('Today'),
|
||||||
|
onPressed: () => _applyDays(1),
|
||||||
|
),
|
||||||
|
ActionChip(
|
||||||
|
label: const Text('7 days'),
|
||||||
|
onPressed: () => _applyDays(7),
|
||||||
|
),
|
||||||
|
ActionChip(
|
||||||
|
label: const Text('30 days'),
|
||||||
|
onPressed: () => _applyDays(30),
|
||||||
|
),
|
||||||
|
ActionChip(
|
||||||
|
label: const Text('Custom…'),
|
||||||
|
onPressed: () => _pickCustom(context),
|
||||||
|
),
|
||||||
|
if (_hasRange)
|
||||||
|
ActionChip(
|
||||||
|
avatar: const Icon(Icons.clear, size: 16),
|
||||||
|
label: const Text('Any'),
|
||||||
|
onPressed: () => onChanged(null, null),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compact "YYYY-MM-DD → YYYY-MM-DD" (or one-sided) summary of the range.
|
||||||
|
String _rangeLabel() {
|
||||||
|
String d(DateTime? t) =>
|
||||||
|
t == null ? '…' : '${t.year}-${_two(t.month)}-${_two(t.day)}';
|
||||||
|
return '${d(from)} → ${d(to)}';
|
||||||
|
}
|
||||||
|
|
||||||
|
String _two(int n) => n.toString().padLeft(2, '0');
|
||||||
|
}
|
||||||
@ -3,112 +3,22 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:todo/data/note.dart';
|
import 'package:todo/data/note.dart';
|
||||||
import 'package:todo/data/note_template.dart';
|
import 'package:todo/data/note_template.dart';
|
||||||
import 'package:todo/ui/markdown_view.dart';
|
import 'package:todo/ui/markdown_view.dart';
|
||||||
import 'package:todo/ui/theme.dart';
|
import 'package:todo/ui/note_editor_chrome.dart';
|
||||||
|
import 'package:todo/ui/note_editor_document.dart';
|
||||||
|
import 'package:todo/ui/note_editor_mode.dart';
|
||||||
|
import 'package:todo/ui/note_editor_raw_field.dart';
|
||||||
|
import 'package:todo/ui/note_editor_step_page.dart';
|
||||||
|
import 'package:todo/ui/note_editor_wizard.dart';
|
||||||
|
|
||||||
/// Which view of the note the editor is currently showing.
|
export 'package:todo/ui/note_editor_mode.dart';
|
||||||
enum NoteEditorMode {
|
|
||||||
/// Read-only rendered Markdown (headings, guidance, bullets).
|
|
||||||
preview,
|
|
||||||
|
|
||||||
/// Full-screen per-step view, one step per template section.
|
part 'note_editor_views.dart';
|
||||||
guided,
|
part 'note_editor_widget.dart';
|
||||||
|
|
||||||
/// A single text field showing the assembled Markdown verbatim.
|
|
||||||
raw,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A guided editor for a note's text, shared by the capture and detail
|
|
||||||
/// screens.
|
|
||||||
///
|
|
||||||
/// It is a *view* over plain text: it parses [initialText] into template
|
|
||||||
/// sections and reports the re-assembled text through [onChanged] on every
|
|
||||||
/// edit. Storage stays plain text, so sync and markdown export are unaffected.
|
|
||||||
///
|
|
||||||
/// Modes (see [NoteEditorMode]):
|
|
||||||
/// * **Preview** — the note rendered as Markdown, read-only.
|
|
||||||
/// * **Guided** — a full-screen per-step view, one step per template
|
|
||||||
/// section, with guidance on what to write and why the LLM needs it.
|
|
||||||
/// * **Raw** — a single text field showing the assembled text verbatim.
|
|
||||||
///
|
|
||||||
/// Non-conforming or freeform text never enters the guided stepper (we never
|
|
||||||
/// force it into the template), so for such text Guided is unavailable and the
|
|
||||||
/// editable source stays the raw body, preserving the user's content.
|
|
||||||
///
|
|
||||||
/// Entering Guided on an empty draft first runs a two-step wizard (priority,
|
|
||||||
/// then template) via [onPriorityChanged], since those choices only make
|
|
||||||
/// sense once, before there's anything to guide. Guided itself — wizard or
|
|
||||||
/// bare step page — hides the template/mode chrome entirely (just a back arrow
|
|
||||||
/// to return to Raw); [onChromeVisibleChanged] tells the parent screen to
|
|
||||||
/// hide its own priority/status row in sync.
|
|
||||||
class NoteEditor extends StatefulWidget {
|
|
||||||
/// Creates a [NoteEditor] with the given callbacks and initial state.
|
|
||||||
const NoteEditor({
|
|
||||||
required this.onChanged,
|
|
||||||
required this.priority,
|
|
||||||
required this.onPriorityChanged,
|
|
||||||
required this.onChromeVisibleChanged,
|
|
||||||
this.initialText = '',
|
|
||||||
this.initialTemplate,
|
|
||||||
this.initialMode = NoteEditorMode.guided,
|
|
||||||
this.autofocus = false,
|
|
||||||
this.advancedMode = true,
|
|
||||||
super.key,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Called with the freshly assembled note text on every edit.
|
|
||||||
final ValueChanged<String> onChanged;
|
|
||||||
|
|
||||||
/// The note's current priority, shown as the wizard's starting selection.
|
|
||||||
final Priority priority;
|
|
||||||
|
|
||||||
/// Called when the priority wizard step is confirmed (Guided "Start").
|
|
||||||
final ValueChanged<Priority> onPriorityChanged;
|
|
||||||
|
|
||||||
/// Called whenever the editor's own chrome (template dropdown, mode
|
|
||||||
/// selector) is shown/hidden, so the parent screen can hide its
|
|
||||||
/// priority/status row in sync while Guided (wizard or bare stepper) is
|
|
||||||
/// active.
|
|
||||||
final ValueChanged<bool> onChromeVisibleChanged;
|
|
||||||
|
|
||||||
/// Existing note text to load. Empty for a fresh draft.
|
|
||||||
final String initialText;
|
|
||||||
|
|
||||||
/// Template to author with. When null the template is detected from
|
|
||||||
/// [initialText] (used when opening an existing note).
|
|
||||||
final NoteTemplate? initialTemplate;
|
|
||||||
|
|
||||||
/// Preferred mode to open in. Falls back to [NoteEditorMode.raw] when
|
|
||||||
/// [NoteEditorMode.guided] is requested for text that can't be guided
|
|
||||||
/// (freeform template or non-conforming content).
|
|
||||||
final NoteEditorMode initialMode;
|
|
||||||
|
|
||||||
/// Autofocus the first field, so a fresh capture needs zero taps before
|
|
||||||
/// typing — preserving the app's instant-capture invariant.
|
|
||||||
final bool autofocus;
|
|
||||||
|
|
||||||
/// Whether the template picker and View/Guided/Raw mode toggle are shown.
|
|
||||||
/// For a freshly-mounted editor, false pins the mode to
|
|
||||||
/// [NoteEditorMode.raw] regardless of [initialMode], and Guided/Preview
|
|
||||||
/// are unreachable — casual capture needs neither. Toggling this off
|
|
||||||
/// while already mid-Guided does not itself force an immediate mode
|
|
||||||
/// change (the open mode stays until the next mode transition, which
|
|
||||||
/// then resolves to raw) — a transient, self-healing state, not a hole
|
|
||||||
/// in the gating.
|
|
||||||
final bool advancedMode;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<NoteEditor> createState() => _NoteEditorState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _NoteEditorState extends State<NoteEditor> {
|
class _NoteEditorState extends State<NoteEditor> {
|
||||||
late NoteTemplate _template;
|
late final NoteEditorDocument _doc;
|
||||||
late NoteEditorMode _mode;
|
late NoteEditorMode _mode;
|
||||||
|
|
||||||
/// Whether the editable content currently lives in [_body] (raw source)
|
|
||||||
/// rather than the per-section controllers (guided source). Preview keeps
|
|
||||||
/// whichever source was last active so [_currentText] stays correct.
|
|
||||||
late bool _rawSource;
|
|
||||||
|
|
||||||
int _currentStep = 0;
|
int _currentStep = 0;
|
||||||
|
|
||||||
/// Whether the priority+template entry wizard is showing in place of the
|
/// Whether the priority+template entry wizard is showing in place of the
|
||||||
@ -116,70 +26,24 @@ class _NoteEditorState extends State<NoteEditor> {
|
|||||||
/// either "Start" (which flips to bare Guided) or "Cancel" (back to Raw).
|
/// either "Start" (which flips to bare Guided) or "Cancel" (back to Raw).
|
||||||
bool _enteringGuided = false;
|
bool _enteringGuided = false;
|
||||||
|
|
||||||
/// Which wizard step (0: priority, 1: template) is showing.
|
|
||||||
int _wizardStep = 0;
|
|
||||||
|
|
||||||
/// Working copies of the wizard's two choices, committed on "Start".
|
|
||||||
Priority _wizardPriority = Priority.defaultValue;
|
|
||||||
NoteTemplate _wizardTemplate = NoteTemplate.defaultTemplate;
|
|
||||||
|
|
||||||
/// One controller per structured section (keyed by section key).
|
|
||||||
final Map<String, TextEditingController> _section = {};
|
|
||||||
|
|
||||||
/// Set once the user picks a template themselves, which stops
|
/// Set once the user picks a template themselves, which stops
|
||||||
/// [_retemplateDraft] from overriding that choice as they keep typing.
|
/// [_retemplateDraft] from overriding that choice as they keep typing.
|
||||||
bool _templatePickedByUser = false;
|
bool _templatePickedByUser = false;
|
||||||
|
|
||||||
/// Single field used for the freeform [NoteTemplate.blank] body and for raw
|
|
||||||
/// mode of a structured template.
|
|
||||||
final TextEditingController _body = TextEditingController();
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
final initial = widget.initialTemplate;
|
_doc = NoteEditorDocument.forInitialText(
|
||||||
if (initial != null) {
|
widget.initialText,
|
||||||
_template = initial;
|
template: widget.initialTemplate,
|
||||||
// Only prefer the guided (sections) source for an empty draft when the
|
openingRaw: widget.initialMode == NoteEditorMode.raw,
|
||||||
// caller actually wants to open in Guided — an empty Raw draft (the new
|
);
|
||||||
// default) must keep the raw body as its source, or typing into the Raw
|
|
||||||
// field would silently update the (hidden, unused) section controllers
|
|
||||||
// instead of what's emitted via onChanged.
|
|
||||||
_loadSource(
|
|
||||||
initial,
|
|
||||||
widget.initialText,
|
|
||||||
preferGuided: widget.initialMode != NoteEditorMode.raw,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
// Detect: does the text cleanly fit the design-spec template?
|
|
||||||
final parsed = parse(NoteTemplate.llmDesignSpec, widget.initialText);
|
|
||||||
if (parsed.conforms) {
|
|
||||||
_template = NoteTemplate.llmDesignSpec;
|
|
||||||
// Same Raw/source consistency rule as above: an explicit Raw request
|
|
||||||
// must keep the raw body as the source even for conforming text.
|
|
||||||
if (widget.initialMode == NoteEditorMode.raw) {
|
|
||||||
_rawSource = true;
|
|
||||||
_body.text = widget.initialText;
|
|
||||||
} else {
|
|
||||||
_rawSource = false;
|
|
||||||
_fillSections(parsed.values);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Freeform / legacy / hand-mangled — keep it as a raw body, untouched.
|
|
||||||
_template = NoteTemplate.blank;
|
|
||||||
_rawSource = true;
|
|
||||||
_body.text = widget.initialText;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_mode = _resolveMode(widget.initialMode);
|
_mode = _resolveMode(widget.initialMode);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
for (final c in _section.values) {
|
_doc.dispose();
|
||||||
c.dispose();
|
|
||||||
}
|
|
||||||
_body.dispose();
|
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -187,7 +51,7 @@ class _NoteEditorState extends State<NoteEditor> {
|
|||||||
/// template whose current source still fits the template. Used to decide the
|
/// template whose current source still fits the template. Used to decide the
|
||||||
/// initial mode; the Guided segment itself is offered for any structured
|
/// initial mode; the Guided segment itself is offered for any structured
|
||||||
/// template (a switch that no longer conforms is blocked at switch time).
|
/// template (a switch that no longer conforms is blocked at switch time).
|
||||||
bool get _canOpenGuided => !_template.isFreeform && !_rawSource;
|
bool get _canOpenGuided => !_doc.template.isFreeform && !_doc.rawSource;
|
||||||
|
|
||||||
/// Picks the mode to actually display: honours [desired] unless Guided was
|
/// Picks the mode to actually display: honours [desired] unless Guided was
|
||||||
/// asked for when it can't be opened (falls back to Raw), or
|
/// asked for when it can't be opened (falls back to Raw), or
|
||||||
@ -201,58 +65,13 @@ class _NoteEditorState extends State<NoteEditor> {
|
|||||||
return desired;
|
return desired;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ensures a controller exists for every section of [template].
|
|
||||||
void _ensureControllers(NoteTemplate template) {
|
|
||||||
for (final s in template.sections) {
|
|
||||||
_section.putIfAbsent(s.key, TextEditingController.new);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _goToStep(int index) {
|
void _goToStep(int index) {
|
||||||
setState(() {
|
setState(() {
|
||||||
_currentStep = index.clamp(0, _template.sections.length - 1);
|
_currentStep = index.clamp(0, _doc.template.sections.length - 1);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void _fillSections(Map<String, String> values) {
|
void _emit() => widget.onChanged(_doc.currentText());
|
||||||
_ensureControllers(_template);
|
|
||||||
for (final s in _template.sections) {
|
|
||||||
_section[s.key]!.text = values[s.key] ?? '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads [text] into [template], choosing the guided source when it conforms
|
|
||||||
/// (or when [preferGuided] and the text is empty) and the raw body otherwise.
|
|
||||||
void _loadSource(
|
|
||||||
NoteTemplate template,
|
|
||||||
String text, {
|
|
||||||
required bool preferGuided,
|
|
||||||
}) {
|
|
||||||
if (template.isFreeform) {
|
|
||||||
_rawSource = true;
|
|
||||||
_body.text = text;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final parsed = parse(template, text);
|
|
||||||
if (parsed.conforms || (preferGuided && text.trim().isEmpty)) {
|
|
||||||
_rawSource = false;
|
|
||||||
_fillSections(parsed.values);
|
|
||||||
} else {
|
|
||||||
_rawSource = true;
|
|
||||||
_body.text = text;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The current note text, assembled from whichever source is active.
|
|
||||||
String _currentText() {
|
|
||||||
if (_rawSource) return _body.text;
|
|
||||||
final values = {
|
|
||||||
for (final s in _template.sections) s.key: _section[s.key]?.text ?? '',
|
|
||||||
};
|
|
||||||
return assemble(_template, values);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _emit() => widget.onChanged(_currentText());
|
|
||||||
|
|
||||||
/// Re-picks the draft's template from what has been typed so far, unless the
|
/// Re-picks the draft's template from what has been typed so far, unless the
|
||||||
/// user has chosen one explicitly.
|
/// user has chosen one explicitly.
|
||||||
@ -262,23 +81,23 @@ class _NoteEditorState extends State<NoteEditor> {
|
|||||||
/// link and Guided drops away, write a sentence under it and the spec
|
/// link and Guided drops away, write a sentence under it and the spec
|
||||||
/// template comes back.
|
/// template comes back.
|
||||||
void _retemplateDraft() {
|
void _retemplateDraft() {
|
||||||
if (_templatePickedByUser || !_rawSource) return;
|
if (_templatePickedByUser || !_doc.rawSource) return;
|
||||||
final next = NoteTemplate.forDraft(_body.text);
|
final next = NoteTemplate.forDraft(_doc.body.text);
|
||||||
if (next.id == _template.id) return;
|
if (next.id == _doc.template.id) return;
|
||||||
setState(() {
|
setState(() {
|
||||||
_template = next;
|
_doc.template = next;
|
||||||
_currentStep = 0;
|
_currentStep = 0;
|
||||||
_mode = _resolveMode(_mode);
|
_mode = _resolveMode(_mode);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void _switchTemplate(NoteTemplate next) {
|
void _switchTemplate(NoteTemplate next) {
|
||||||
if (next.id == _template.id) return;
|
if (next.id == _doc.template.id) return;
|
||||||
final text = _currentText();
|
final text = _doc.currentText();
|
||||||
setState(() {
|
setState(() {
|
||||||
_template = next;
|
_doc.template = next;
|
||||||
_currentStep = 0;
|
_currentStep = 0;
|
||||||
_loadSource(next, text, preferGuided: true);
|
_doc.load(next, text, preferGuided: true);
|
||||||
_mode = _resolveMode(_mode);
|
_mode = _resolveMode(_mode);
|
||||||
});
|
});
|
||||||
_emit();
|
_emit();
|
||||||
@ -290,42 +109,31 @@ class _NoteEditorState extends State<NoteEditor> {
|
|||||||
setState(() {
|
setState(() {
|
||||||
switch (next) {
|
switch (next) {
|
||||||
case NoteEditorMode.guided:
|
case NoteEditorMode.guided:
|
||||||
if (_rawSource) {
|
// raw -> guided: only if the edited text still fits the template.
|
||||||
// raw -> guided: only if the edited text still fits the template.
|
if (!_doc.tryAdoptGuided()) {
|
||||||
final parsed = parse(_template, _body.text);
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
if (!parsed.conforms && _body.text.trim().isNotEmpty) {
|
const SnackBar(
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
content: Text(
|
||||||
const SnackBar(
|
"Text doesn't match the template — staying in raw",
|
||||||
content: Text(
|
|
||||||
"Text doesn't match the template — staying in raw",
|
|
||||||
),
|
|
||||||
duration: Duration(seconds: 2),
|
|
||||||
),
|
),
|
||||||
);
|
duration: Duration(seconds: 2),
|
||||||
return;
|
),
|
||||||
}
|
);
|
||||||
_fillSections(parsed.values);
|
return;
|
||||||
_rawSource = false;
|
|
||||||
}
|
}
|
||||||
_currentStep = 0;
|
_currentStep = 0;
|
||||||
if (_currentText().trim().isEmpty) {
|
if (_doc.currentText().trim().isEmpty) {
|
||||||
// Fresh, empty draft: priority and template are meaningful
|
// Fresh, empty draft: priority and template are meaningful
|
||||||
// choices only once, so ask for them before showing the stepper.
|
// choices only once, so ask for them before showing the stepper.
|
||||||
_enteringGuided = true;
|
_enteringGuided = true;
|
||||||
_wizardStep = 0;
|
|
||||||
_wizardPriority = widget.priority;
|
|
||||||
_wizardTemplate = NoteTemplate.defaultTemplate;
|
|
||||||
} else {
|
} else {
|
||||||
// Existing content: priority/template are already settled, so
|
// Existing content: priority/template are already settled, so
|
||||||
// skip straight to the bare stepper rather than re-asking.
|
// skip straight to the bare stepper rather than re-asking.
|
||||||
_mode = NoteEditorMode.guided;
|
_mode = NoteEditorMode.guided;
|
||||||
}
|
}
|
||||||
case NoteEditorMode.raw:
|
case NoteEditorMode.raw:
|
||||||
if (!_rawSource) {
|
// guided -> raw: materialise the assembled text into the body.
|
||||||
// guided -> raw: materialise the assembled text into the body.
|
_doc.materialiseToRaw();
|
||||||
_body.text = _currentText();
|
|
||||||
_rawSource = true;
|
|
||||||
}
|
|
||||||
_mode = NoteEditorMode.raw;
|
_mode = NoteEditorMode.raw;
|
||||||
case NoteEditorMode.preview:
|
case NoteEditorMode.preview:
|
||||||
// Read-only render of the current source; nothing to convert.
|
// Read-only render of the current source; nothing to convert.
|
||||||
@ -341,13 +149,13 @@ class _NoteEditorState extends State<NoteEditor> {
|
|||||||
/// Distinct from [_switchTemplate]: that short-circuits when the template
|
/// Distinct from [_switchTemplate]: that short-circuits when the template
|
||||||
/// is unchanged, which would skip flipping out of the wizard here.
|
/// is unchanged, which would skip flipping out of the wizard here.
|
||||||
void _enterGuidedWithTemplate(NoteTemplate template) {
|
void _enterGuidedWithTemplate(NoteTemplate template) {
|
||||||
final text = _currentText();
|
final text = _doc.currentText();
|
||||||
// Choosing a template in the wizard is as explicit as using the dropdown.
|
// Choosing a template in the wizard is as explicit as using the dropdown.
|
||||||
_templatePickedByUser = true;
|
_templatePickedByUser = true;
|
||||||
setState(() {
|
setState(() {
|
||||||
_template = template;
|
_doc.template = template;
|
||||||
_currentStep = 0;
|
_currentStep = 0;
|
||||||
_loadSource(template, text, preferGuided: true);
|
_doc.load(template, text, preferGuided: true);
|
||||||
_mode = NoteEditorMode.guided;
|
_mode = NoteEditorMode.guided;
|
||||||
_enteringGuided = false;
|
_enteringGuided = false;
|
||||||
});
|
});
|
||||||
@ -361,342 +169,53 @@ class _NoteEditorState extends State<NoteEditor> {
|
|||||||
widget.onChromeVisibleChanged(true);
|
widget.onChromeVisibleChanged(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Exits the bare stepper back to Raw, restoring the chrome.
|
|
||||||
void _exitGuided() {
|
|
||||||
setState(() {
|
|
||||||
if (!_rawSource) {
|
|
||||||
_body.text = _currentText();
|
|
||||||
_rawSource = true;
|
|
||||||
}
|
|
||||||
_mode = NoteEditorMode.raw;
|
|
||||||
});
|
|
||||||
widget.onChromeVisibleChanged(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
if (_enteringGuided) return _guidedEntryWizard();
|
||||||
if (_enteringGuided) return _buildGuidedEntryWizard(theme);
|
|
||||||
|
|
||||||
// Guided hides the template/mode chrome entirely. Return the flat step
|
// Guided hides the template/mode chrome entirely. Return the flat step
|
||||||
// page directly so the TextField sits in THIS column's Expanded — same
|
// page directly so the TextField sits in THIS column's Expanded — same
|
||||||
// depth as _buildRaw, avoiding the nested-Column/Expanded layout issue
|
// depth as the raw field, avoiding the nested-Column/Expanded layout issue
|
||||||
// that silently collapses the inner flex space in release builds.
|
// that silently collapses the inner flex space in release builds.
|
||||||
if (_mode == NoteEditorMode.guided) return _buildStepPage(theme);
|
if (_mode == NoteEditorMode.guided) return _buildStepPage();
|
||||||
|
|
||||||
// Advanced mode off: the template picker and mode toggle are hidden and
|
// Advanced mode off: the template picker and mode toggle are hidden and
|
||||||
// _resolveMode() has already pinned _mode to raw, so skip straight to
|
// _resolveMode() has already pinned _mode to raw, so skip straight to
|
||||||
// the body directly (not wrapped in another Expanded — the parent
|
// the body directly (not wrapped in another Expanded — the parent
|
||||||
// screen already wraps this whole widget in one, same as the guided
|
// screen already wraps this whole widget in one, same as the guided
|
||||||
// branch above).
|
// branch above).
|
||||||
if (!widget.advancedMode) return _buildBody(theme);
|
if (!widget.advancedMode) return _buildBody();
|
||||||
|
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
DropdownButtonFormField<String>(
|
NoteEditorChrome(
|
||||||
initialValue: _template.id,
|
template: _doc.template,
|
||||||
decoration: const InputDecoration(
|
mode: _mode,
|
||||||
labelText: 'Template',
|
onTemplateSelected: (next) {
|
||||||
isDense: true,
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
|
||||||
),
|
|
||||||
items: [
|
|
||||||
for (final t in NoteTemplate.all)
|
|
||||||
DropdownMenuItem(value: t.id, child: Text(t.label)),
|
|
||||||
],
|
|
||||||
onChanged: (id) {
|
|
||||||
if (id == null) return;
|
|
||||||
_templatePickedByUser = true;
|
_templatePickedByUser = true;
|
||||||
_switchTemplate(NoteTemplate.all.firstWhere((t) => t.id == id));
|
_switchTemplate(next);
|
||||||
},
|
},
|
||||||
),
|
onModeSelected: _setMode,
|
||||||
const SizedBox(height: 8),
|
|
||||||
Align(
|
|
||||||
alignment: Alignment.centerLeft,
|
|
||||||
child: SegmentedButton<NoteEditorMode>(
|
|
||||||
showSelectedIcon: false,
|
|
||||||
segments: [
|
|
||||||
const ButtonSegment(
|
|
||||||
value: NoteEditorMode.preview,
|
|
||||||
icon: Icon(Icons.visibility_outlined),
|
|
||||||
label: Text('View'),
|
|
||||||
),
|
|
||||||
// Guided is offered for any structured template; tapping it
|
|
||||||
// on an empty draft opens the wizard (see _setMode), and is
|
|
||||||
// blocked at switch time if the raw text no longer conforms.
|
|
||||||
if (!_template.isFreeform)
|
|
||||||
const ButtonSegment(
|
|
||||||
value: NoteEditorMode.guided,
|
|
||||||
icon: Icon(Icons.checklist),
|
|
||||||
label: Text('Guided'),
|
|
||||||
),
|
|
||||||
const ButtonSegment(
|
|
||||||
value: NoteEditorMode.raw,
|
|
||||||
icon: Icon(Icons.notes),
|
|
||||||
label: Text('Raw'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
selected: {_mode},
|
|
||||||
onSelectionChanged: (s) => _setMode(s.first),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
Expanded(child: _buildBody(theme)),
|
Expanded(child: _buildBody()),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The two-step priority -> template wizard shown before a fresh draft
|
/// Exits the bare stepper back to Raw, restoring the chrome.
|
||||||
/// enters Guided. Replaces the normal chrome entirely (see [build]).
|
void _exitGuided() {
|
||||||
Widget _buildGuidedEntryWizard(ThemeData theme) {
|
setState(() {
|
||||||
return Column(
|
_doc.materialiseToRaw();
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
_mode = NoteEditorMode.raw;
|
||||||
mainAxisSize: MainAxisSize.min,
|
});
|
||||||
children: [
|
widget.onChromeVisibleChanged(true);
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
IconButton(
|
|
||||||
icon: const Icon(Icons.close),
|
|
||||||
tooltip: 'Cancel',
|
|
||||||
onPressed: _cancelWizard,
|
|
||||||
),
|
|
||||||
Text(
|
|
||||||
'Step ${_wizardStep + 1} of 2',
|
|
||||||
style: theme.textTheme.labelLarge,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
if (_wizardStep == 0)
|
|
||||||
..._buildWizardPriorityStep()
|
|
||||||
else
|
|
||||||
..._buildWizardTemplateStep(),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Widget> _buildWizardPriorityStep() {
|
/// Rebuilds after a guided step edit, then re-emits the assembled text.
|
||||||
return [
|
void _onStepFieldChanged() {
|
||||||
DropdownButtonFormField<Priority>(
|
setState(() {});
|
||||||
initialValue: _wizardPriority,
|
_emit();
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Priority',
|
|
||||||
isDense: true,
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
|
||||||
),
|
|
||||||
items: [
|
|
||||||
for (final p in Priority.values)
|
|
||||||
DropdownMenuItem(value: p, child: Text(p.label)),
|
|
||||||
],
|
|
||||||
onChanged: (p) {
|
|
||||||
if (p != null) setState(() => _wizardPriority = p);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Align(
|
|
||||||
alignment: Alignment.centerRight,
|
|
||||||
child: FilledButton(
|
|
||||||
onPressed: () => setState(() => _wizardStep = 1),
|
|
||||||
child: const Text('Next'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
List<Widget> _buildWizardTemplateStep() {
|
|
||||||
final templates = NoteTemplate.all.where((t) => !t.isFreeform).toList();
|
|
||||||
return [
|
|
||||||
DropdownButtonFormField<String>(
|
|
||||||
initialValue: _wizardTemplate.id,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Template',
|
|
||||||
isDense: true,
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
|
||||||
),
|
|
||||||
items: [
|
|
||||||
for (final t in templates)
|
|
||||||
DropdownMenuItem(value: t.id, child: Text(t.label)),
|
|
||||||
],
|
|
||||||
onChanged: (id) {
|
|
||||||
if (id == null) return;
|
|
||||||
setState(
|
|
||||||
() => _wizardTemplate = templates.firstWhere((t) => t.id == id),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Row(
|
|
||||||
mainAxisAlignment: MainAxisAlignment.end,
|
|
||||||
children: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => setState(() => _wizardStep = 0),
|
|
||||||
child: const Text('Back'),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
FilledButton(
|
|
||||||
onPressed: () {
|
|
||||||
widget.onPriorityChanged(_wizardPriority);
|
|
||||||
_enterGuidedWithTemplate(_wizardTemplate);
|
|
||||||
},
|
|
||||||
child: const Text('Start'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildBody(ThemeData theme) {
|
|
||||||
switch (_mode) {
|
|
||||||
case NoteEditorMode.preview:
|
|
||||||
return MarkdownView(text: _currentText());
|
|
||||||
case NoteEditorMode.raw:
|
|
||||||
return _buildRaw(theme);
|
|
||||||
// coverage:ignore-start
|
|
||||||
// Unreachable: build() short-circuits to _buildStepPage before reaching
|
|
||||||
// here, so this arm only exists to make the switch exhaustive.
|
|
||||||
case NoteEditorMode.guided:
|
|
||||||
return _buildRaw(theme);
|
|
||||||
// coverage:ignore-end
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildRaw(ThemeData theme) {
|
|
||||||
// Caps the editing column at ~70 chars (rule 21) on the desktop's
|
|
||||||
// arbitrarily wide Chrome `--app` window. Center/ConstrainedBox only,
|
|
||||||
// no extra Column — nesting a second Column here previously broke the
|
|
||||||
// expands:true constraint chain in release builds (see _buildStepPage).
|
|
||||||
return Center(
|
|
||||||
child: ConstrainedBox(
|
|
||||||
constraints: const BoxConstraints(maxWidth: kProseMaxWidth),
|
|
||||||
child: TextField(
|
|
||||||
controller: _body,
|
|
||||||
autofocus: widget.autofocus,
|
|
||||||
maxLines: null,
|
|
||||||
expands: true,
|
|
||||||
textAlignVertical: TextAlignVertical.top,
|
|
||||||
keyboardType: TextInputType.multiline,
|
|
||||||
style: theme.textTheme.bodyLarge,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
border: InputBorder.none,
|
|
||||||
hintText: 'Write your idea…',
|
|
||||||
),
|
|
||||||
onChanged: (_) {
|
|
||||||
_retemplateDraft();
|
|
||||||
_emit();
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Full-screen per-step view returned directly from [build] so the
|
|
||||||
/// [TextField] is a first-level [Expanded] child of THIS column — the same
|
|
||||||
/// depth as [_buildRaw]. Nesting it inside a second Column broke the
|
|
||||||
/// flutter constraint chain in release builds (inner Expanded got 0 height).
|
|
||||||
Widget _buildStepPage(ThemeData theme) {
|
|
||||||
_ensureControllers(_template);
|
|
||||||
final sections = _template.sections;
|
|
||||||
final idx = _currentStep.clamp(0, sections.length - 1);
|
|
||||||
final section = sections[idx];
|
|
||||||
final total = sections.length;
|
|
||||||
final controller = _section[section.key]!;
|
|
||||||
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
// Back arrow — only exit from guided mode.
|
|
||||||
Align(
|
|
||||||
alignment: Alignment.centerLeft,
|
|
||||||
child: IconButton(
|
|
||||||
icon: const Icon(Icons.arrow_back),
|
|
||||||
tooltip: 'Exit guided',
|
|
||||||
onPressed: _exitGuided,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
// Progress bar + step counter.
|
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Text('${idx + 1} / $total', style: theme.textTheme.labelMedium),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
child: LinearProgressIndicator(value: (idx + 1) / total),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
// Section label + helper text.
|
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
section.isTitle ? 'title' : section.label,
|
|
||||||
style: theme.textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
section.helper,
|
|
||||||
style: theme.textTheme.bodySmall?.copyWith(
|
|
||||||
color: theme.colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
// TextField fills all remaining space — directly in this Column's
|
|
||||||
// Expanded, same as _buildRaw, so expands:true works correctly.
|
|
||||||
Expanded(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 0),
|
|
||||||
child: TextField(
|
|
||||||
controller: controller,
|
|
||||||
autofocus: widget.autofocus && idx == 0,
|
|
||||||
expands: true,
|
|
||||||
maxLines: null,
|
|
||||||
keyboardType: TextInputType.multiline,
|
|
||||||
textAlignVertical: TextAlignVertical.top,
|
|
||||||
decoration: InputDecoration(
|
|
||||||
hintText: section.hint,
|
|
||||||
border: const OutlineInputBorder(),
|
|
||||||
isDense: true,
|
|
||||||
),
|
|
||||||
onChanged: (_) {
|
|
||||||
setState(() {});
|
|
||||||
_emit();
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
// Navigation buttons — sibling of Expanded so keyboard pushes them up.
|
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
if (idx > 0)
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => _goToStep(idx - 1),
|
|
||||||
child: const Text('Back'),
|
|
||||||
),
|
|
||||||
const Spacer(),
|
|
||||||
if (idx < total - 1)
|
|
||||||
FilledButton(
|
|
||||||
onPressed: () => _goToStep(idx + 1),
|
|
||||||
child: const Text('Next'),
|
|
||||||
)
|
|
||||||
else
|
|
||||||
FilledButton(onPressed: _exitGuided, child: const Text('Done')),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
95
lib/ui/note_editor_chrome.dart
Normal file
95
lib/ui/note_editor_chrome.dart
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
/// The editor's chrome: the template picker and the View/Guided/Raw toggle.
|
||||||
|
///
|
||||||
|
/// Split out of `note_editor.dart` for file size. Stateless and callback-only
|
||||||
|
/// — every choice it offers is applied by `_NoteEditorState`, which owns the
|
||||||
|
/// template and mode. Guided hides this chrome entirely, so it is only ever
|
||||||
|
/// built in Preview and Raw.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
import 'package:todo/ui/note_editor_mode.dart';
|
||||||
|
|
||||||
|
/// Template dropdown above a segmented View / Guided / Raw selector.
|
||||||
|
class NoteEditorChrome extends StatelessWidget {
|
||||||
|
/// Creates the chrome for [template] in [mode].
|
||||||
|
const NoteEditorChrome({
|
||||||
|
required this.template,
|
||||||
|
required this.mode,
|
||||||
|
required this.onTemplateSelected,
|
||||||
|
required this.onModeSelected,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The template currently selected in the dropdown.
|
||||||
|
final NoteTemplate template;
|
||||||
|
|
||||||
|
/// The mode the segmented button shows as selected.
|
||||||
|
final NoteEditorMode mode;
|
||||||
|
|
||||||
|
/// Called with the template the user picked.
|
||||||
|
final ValueChanged<NoteTemplate> onTemplateSelected;
|
||||||
|
|
||||||
|
/// Called with the mode the user picked.
|
||||||
|
final ValueChanged<NoteEditorMode> onModeSelected;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
DropdownButtonFormField<String>(
|
||||||
|
initialValue: template.id,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Template',
|
||||||
|
isDense: true,
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||||
|
),
|
||||||
|
items: [
|
||||||
|
for (final t in NoteTemplate.all)
|
||||||
|
DropdownMenuItem(value: t.id, child: Text(t.label)),
|
||||||
|
],
|
||||||
|
onChanged: (id) {
|
||||||
|
if (id == null) return;
|
||||||
|
onTemplateSelected(
|
||||||
|
NoteTemplate.all.firstWhere((t) => t.id == id),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: SegmentedButton<NoteEditorMode>(
|
||||||
|
showSelectedIcon: false,
|
||||||
|
segments: [
|
||||||
|
const ButtonSegment(
|
||||||
|
value: NoteEditorMode.preview,
|
||||||
|
icon: Icon(Icons.visibility_outlined),
|
||||||
|
label: Text('View'),
|
||||||
|
),
|
||||||
|
// Guided is offered for any structured template; tapping it
|
||||||
|
// on an empty draft opens the wizard, and is blocked at
|
||||||
|
// switch time if the raw text no longer conforms.
|
||||||
|
if (!template.isFreeform)
|
||||||
|
const ButtonSegment(
|
||||||
|
value: NoteEditorMode.guided,
|
||||||
|
icon: Icon(Icons.checklist),
|
||||||
|
label: Text('Guided'),
|
||||||
|
),
|
||||||
|
const ButtonSegment(
|
||||||
|
value: NoteEditorMode.raw,
|
||||||
|
icon: Icon(Icons.notes),
|
||||||
|
label: Text('Raw'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
selected: {mode},
|
||||||
|
onSelectionChanged: (s) => onModeSelected(s.first),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
163
lib/ui/note_editor_document.dart
Normal file
163
lib/ui/note_editor_document.dart
Normal file
@ -0,0 +1,163 @@
|
|||||||
|
/// The editor's text state: the template, the controllers, and which of the
|
||||||
|
/// two sources (raw body vs. per-section fields) is currently authoritative.
|
||||||
|
///
|
||||||
|
/// Split out of `note_editor.dart` for file size, and it is the honest seam:
|
||||||
|
/// none of this needs a `BuildContext` or a `setState` — it is the model the
|
||||||
|
/// widget renders. `_NoteEditorState` still drives every transition and still
|
||||||
|
/// owns when to rebuild; this class just holds the text and converts between
|
||||||
|
/// the two sources.
|
||||||
|
///
|
||||||
|
/// The two-source design is what keeps non-conforming text safe: text that
|
||||||
|
/// does not fit the template is never forced through it, it stays verbatim in
|
||||||
|
/// [body] and the editor shows the raw field instead.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
|
||||||
|
/// Holds a note's editable text for one [NoteTemplate].
|
||||||
|
class NoteEditorDocument {
|
||||||
|
/// Creates a document for [template]; call [load] to put text in it.
|
||||||
|
NoteEditorDocument(this.template);
|
||||||
|
|
||||||
|
/// Builds the document a freshly-mounted editor should start from.
|
||||||
|
///
|
||||||
|
/// With an explicit [template] the text is simply loaded into it. Without
|
||||||
|
/// one the template is *detected*: text that cleanly fits the design-spec
|
||||||
|
/// template adopts it, and anything else (freeform, legacy, hand-mangled)
|
||||||
|
/// stays a raw body under [NoteTemplate.blank], untouched.
|
||||||
|
///
|
||||||
|
/// [openingRaw] keeps the raw body authoritative even for conforming text.
|
||||||
|
/// Without it, typing into a Raw field would silently update the hidden,
|
||||||
|
/// unused section controllers instead of what `onChanged` emits.
|
||||||
|
factory NoteEditorDocument.forInitialText(
|
||||||
|
String text, {
|
||||||
|
required NoteTemplate? template,
|
||||||
|
required bool openingRaw,
|
||||||
|
}) {
|
||||||
|
if (template != null) {
|
||||||
|
return NoteEditorDocument(template)
|
||||||
|
..load(template, text, preferGuided: !openingRaw);
|
||||||
|
}
|
||||||
|
final parsed = parse(NoteTemplate.llmDesignSpec, text);
|
||||||
|
if (!parsed.conforms) {
|
||||||
|
return NoteEditorDocument(NoteTemplate.blank)
|
||||||
|
..rawSource = true
|
||||||
|
..body.text = text;
|
||||||
|
}
|
||||||
|
final doc = NoteEditorDocument(NoteTemplate.llmDesignSpec);
|
||||||
|
if (openingRaw) {
|
||||||
|
doc
|
||||||
|
..rawSource = true
|
||||||
|
..body.text = text;
|
||||||
|
} else {
|
||||||
|
doc.adoptSections(parsed.values);
|
||||||
|
}
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The template the text is authored against.
|
||||||
|
NoteTemplate template;
|
||||||
|
|
||||||
|
/// Whether the editable content currently lives in [body] (raw source)
|
||||||
|
/// rather than the per-section controllers (guided source). Preview keeps
|
||||||
|
/// whichever source was last active so [currentText] stays correct.
|
||||||
|
bool rawSource = true;
|
||||||
|
|
||||||
|
/// Single field used for the freeform [NoteTemplate.blank] body and for raw
|
||||||
|
/// mode of a structured template.
|
||||||
|
final TextEditingController body = TextEditingController();
|
||||||
|
|
||||||
|
/// One controller per structured section (keyed by section key).
|
||||||
|
final Map<String, TextEditingController> section = {};
|
||||||
|
|
||||||
|
/// Ensures a controller exists for every section of [forTemplate].
|
||||||
|
void ensureControllers(NoteTemplate forTemplate) {
|
||||||
|
for (final s in forTemplate.sections) {
|
||||||
|
section.putIfAbsent(s.key, TextEditingController.new);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes [values] into the per-section controllers.
|
||||||
|
void fillSections(Map<String, String> values) {
|
||||||
|
ensureControllers(template);
|
||||||
|
for (final s in template.sections) {
|
||||||
|
section[s.key]!.text = values[s.key] ?? '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loads [text] into [forTemplate], choosing the guided source when it
|
||||||
|
/// conforms (or when [preferGuided] and the text is empty) and the raw body
|
||||||
|
/// otherwise.
|
||||||
|
void load(
|
||||||
|
NoteTemplate forTemplate,
|
||||||
|
String text, {
|
||||||
|
required bool preferGuided,
|
||||||
|
}) {
|
||||||
|
template = forTemplate;
|
||||||
|
if (forTemplate.isFreeform) {
|
||||||
|
rawSource = true;
|
||||||
|
body.text = text;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final parsed = parse(forTemplate, text);
|
||||||
|
if (parsed.conforms || (preferGuided && text.trim().isEmpty)) {
|
||||||
|
rawSource = false;
|
||||||
|
fillSections(parsed.values);
|
||||||
|
} else {
|
||||||
|
rawSource = true;
|
||||||
|
body.text = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adopts [values] as the guided source, making the section fields
|
||||||
|
/// authoritative.
|
||||||
|
///
|
||||||
|
/// The raw -> guided direction, once the caller has confirmed the text
|
||||||
|
/// still conforms to the template.
|
||||||
|
void adoptSections(Map<String, String> values) {
|
||||||
|
fillSections(values);
|
||||||
|
rawSource = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tries to make the section fields authoritative, for raw -> guided.
|
||||||
|
///
|
||||||
|
/// Returns false and changes nothing when the edited raw text no longer
|
||||||
|
/// fits the template — the caller keeps the editor in raw and says so,
|
||||||
|
/// rather than forcing text through a template it does not match.
|
||||||
|
/// Empty text always succeeds: there is nothing to lose.
|
||||||
|
bool tryAdoptGuided() {
|
||||||
|
if (!rawSource) return true;
|
||||||
|
final parsed = parse(template, body.text);
|
||||||
|
if (!parsed.conforms && body.text.trim().isNotEmpty) return false;
|
||||||
|
adoptSections(parsed.values);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the editable content into the raw body, leaving it authoritative.
|
||||||
|
///
|
||||||
|
/// Used on guided -> raw so the assembled text is what the user then edits.
|
||||||
|
void materialiseToRaw() {
|
||||||
|
if (rawSource) return;
|
||||||
|
body.text = currentText();
|
||||||
|
rawSource = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current note text, assembled from whichever source is active.
|
||||||
|
String currentText() {
|
||||||
|
if (rawSource) return body.text;
|
||||||
|
final values = {
|
||||||
|
for (final s in template.sections) s.key: section[s.key]?.text ?? '',
|
||||||
|
};
|
||||||
|
return assemble(template, values);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Disposes every controller this document owns.
|
||||||
|
void dispose() {
|
||||||
|
for (final c in section.values) {
|
||||||
|
c.dispose();
|
||||||
|
}
|
||||||
|
body.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
18
lib/ui/note_editor_mode.dart
Normal file
18
lib/ui/note_editor_mode.dart
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
/// Which view of the note the editor is currently showing.
|
||||||
|
///
|
||||||
|
/// Its own file so the chrome and the editor can both name it without either
|
||||||
|
/// importing the other. `note_editor.dart` re-exports it, so existing callers
|
||||||
|
/// (the detail screen, the tests) are unaffected.
|
||||||
|
library;
|
||||||
|
|
||||||
|
/// Which view of the note the editor is currently showing.
|
||||||
|
enum NoteEditorMode {
|
||||||
|
/// Read-only rendered Markdown (headings, guidance, bullets).
|
||||||
|
preview,
|
||||||
|
|
||||||
|
/// Full-screen per-step view, one step per template section.
|
||||||
|
guided,
|
||||||
|
|
||||||
|
/// A single text field showing the assembled Markdown verbatim.
|
||||||
|
raw,
|
||||||
|
}
|
||||||
57
lib/ui/note_editor_raw_field.dart
Normal file
57
lib/ui/note_editor_raw_field.dart
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
/// The raw-mode editing field: the assembled note text, verbatim.
|
||||||
|
///
|
||||||
|
/// Split out of `note_editor.dart` for file size. Stateless; the controller
|
||||||
|
/// stays owned by `_NoteEditorState`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/ui/theme.dart';
|
||||||
|
|
||||||
|
/// A full-height plain-text field for the note's assembled Markdown.
|
||||||
|
class NoteEditorRawField extends StatelessWidget {
|
||||||
|
/// Creates the raw field over [controller].
|
||||||
|
const NoteEditorRawField({
|
||||||
|
required this.controller,
|
||||||
|
required this.autofocus,
|
||||||
|
required this.onChanged,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Controller holding the raw body text.
|
||||||
|
final TextEditingController controller;
|
||||||
|
|
||||||
|
/// Whether the field takes focus on first build.
|
||||||
|
final bool autofocus;
|
||||||
|
|
||||||
|
/// Called on every keystroke.
|
||||||
|
final VoidCallback onChanged;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
// Caps the editing column at ~70 chars (rule 21) on the desktop's
|
||||||
|
// arbitrarily wide Chrome `--app` window. Center/ConstrainedBox only,
|
||||||
|
// no extra Column — nesting a second Column here previously broke the
|
||||||
|
// expands:true constraint chain in release builds (see
|
||||||
|
// NoteEditorStepPage, which documents the same hazard).
|
||||||
|
return Center(
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: kProseMaxWidth),
|
||||||
|
child: TextField(
|
||||||
|
controller: controller,
|
||||||
|
autofocus: autofocus,
|
||||||
|
maxLines: null,
|
||||||
|
expands: true,
|
||||||
|
textAlignVertical: TextAlignVertical.top,
|
||||||
|
keyboardType: TextInputType.multiline,
|
||||||
|
style: Theme.of(context).textTheme.bodyLarge,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
border: InputBorder.none,
|
||||||
|
hintText: 'Write your idea…',
|
||||||
|
),
|
||||||
|
onChanged: (_) => onChanged(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
151
lib/ui/note_editor_step_page.dart
Normal file
151
lib/ui/note_editor_step_page.dart
Normal file
@ -0,0 +1,151 @@
|
|||||||
|
/// The guided stepper's full-screen per-step view.
|
||||||
|
///
|
||||||
|
/// Split out of `note_editor.dart` for file size. Stateless on purpose: the
|
||||||
|
/// controllers, the current step and the template all stay owned by
|
||||||
|
/// `_NoteEditorState`, and are passed in — this widget only lays them out.
|
||||||
|
///
|
||||||
|
/// Returned directly from the editor's `build` so the [TextField] is a
|
||||||
|
/// first-level [Expanded] child of THIS column, the same depth as the raw
|
||||||
|
/// editor's. Nesting it inside a second Column broke the flutter constraint
|
||||||
|
/// chain in release builds (the inner Expanded got 0 height), so the flat
|
||||||
|
/// structure here is load-bearing rather than incidental.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
|
||||||
|
/// One step of the guided editor: label, guidance, input, and navigation.
|
||||||
|
class NoteEditorStepPage extends StatelessWidget {
|
||||||
|
/// Creates the step view for [section], step [index] of [total].
|
||||||
|
const NoteEditorStepPage({
|
||||||
|
required this.section,
|
||||||
|
required this.controller,
|
||||||
|
required this.index,
|
||||||
|
required this.total,
|
||||||
|
required this.autofocus,
|
||||||
|
required this.onChanged,
|
||||||
|
required this.onGoToStep,
|
||||||
|
required this.onExit,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The template section this step edits.
|
||||||
|
final TemplateSection section;
|
||||||
|
|
||||||
|
/// Controller for this section's text, owned by the editor.
|
||||||
|
final TextEditingController controller;
|
||||||
|
|
||||||
|
/// Zero-based index of this step, already clamped to the section range.
|
||||||
|
final int index;
|
||||||
|
|
||||||
|
/// How many steps the template has in total.
|
||||||
|
final int total;
|
||||||
|
|
||||||
|
/// Whether the input should take focus on first build.
|
||||||
|
final bool autofocus;
|
||||||
|
|
||||||
|
/// Called on every keystroke so the editor can re-emit the assembled text.
|
||||||
|
final VoidCallback onChanged;
|
||||||
|
|
||||||
|
/// Called with the step index to move to.
|
||||||
|
final ValueChanged<int> onGoToStep;
|
||||||
|
|
||||||
|
/// Called by the back arrow and by "Done" on the last step.
|
||||||
|
final VoidCallback onExit;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
// Back arrow — only exit from guided mode.
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: IconButton(
|
||||||
|
icon: const Icon(Icons.arrow_back),
|
||||||
|
tooltip: 'Exit guided',
|
||||||
|
onPressed: onExit,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// Progress bar + step counter.
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Text('${index + 1} / $total', style: theme.textTheme.labelMedium),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: LinearProgressIndicator(value: (index + 1) / total),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// Section label + helper text.
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
section.isTitle ? 'title' : section.label,
|
||||||
|
style: theme.textTheme.titleMedium,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(
|
||||||
|
section.helper,
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// TextField fills all remaining space — directly in this Column's
|
||||||
|
// Expanded, same as the raw editor, so expands:true works correctly.
|
||||||
|
Expanded(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 0, 16, 0),
|
||||||
|
child: TextField(
|
||||||
|
controller: controller,
|
||||||
|
autofocus: autofocus && index == 0,
|
||||||
|
expands: true,
|
||||||
|
maxLines: null,
|
||||||
|
keyboardType: TextInputType.multiline,
|
||||||
|
textAlignVertical: TextAlignVertical.top,
|
||||||
|
decoration: InputDecoration(
|
||||||
|
hintText: section.hint,
|
||||||
|
border: const OutlineInputBorder(),
|
||||||
|
isDense: true,
|
||||||
|
),
|
||||||
|
onChanged: (_) => onChanged(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// Navigation buttons — sibling of Expanded so keyboard pushes them up.
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
if (index > 0)
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => onGoToStep(index - 1),
|
||||||
|
child: const Text('Back'),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
if (index < total - 1)
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => onGoToStep(index + 1),
|
||||||
|
child: const Text('Next'),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
FilledButton(onPressed: onExit, child: const Text('Done')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
65
lib/ui/note_editor_views.dart
Normal file
65
lib/ui/note_editor_views.dart
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
/// The [NoteEditor]'s view wiring: the small methods that hand this editor's
|
||||||
|
/// state to the extracted presentation widgets.
|
||||||
|
///
|
||||||
|
/// A `part` of `note_editor.dart` because every method here reads private
|
||||||
|
/// state (`_doc`, `_mode`, `_currentStep`) that Dart scopes to the library.
|
||||||
|
part of 'note_editor.dart';
|
||||||
|
|
||||||
|
extension _NoteEditorViews on _NoteEditorState {
|
||||||
|
/// The pre-guided wizard. Its step state lives in the widget itself; only
|
||||||
|
/// the two committed choices come back here.
|
||||||
|
Widget _guidedEntryWizard() => NoteEditorWizard(
|
||||||
|
initialPriority: widget.priority,
|
||||||
|
initialTemplate: NoteTemplate.defaultTemplate,
|
||||||
|
onCancel: _cancelWizard,
|
||||||
|
onStart: (priority, template) {
|
||||||
|
widget.onPriorityChanged(priority);
|
||||||
|
_enterGuidedWithTemplate(template);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
/// The raw field, wired to this editor's body controller.
|
||||||
|
Widget _rawField() => NoteEditorRawField(
|
||||||
|
controller: _doc.body,
|
||||||
|
autofocus: widget.autofocus,
|
||||||
|
onChanged: () {
|
||||||
|
_retemplateDraft();
|
||||||
|
_emit();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
Widget _buildBody() {
|
||||||
|
switch (_mode) {
|
||||||
|
case NoteEditorMode.preview:
|
||||||
|
return MarkdownView(text: _doc.currentText());
|
||||||
|
case NoteEditorMode.raw:
|
||||||
|
return _rawField();
|
||||||
|
// coverage:ignore-start
|
||||||
|
// Unreachable: build() short-circuits to _buildStepPage before reaching
|
||||||
|
// here, so this arm only exists to make the switch exhaustive.
|
||||||
|
case NoteEditorMode.guided:
|
||||||
|
return _rawField();
|
||||||
|
// coverage:ignore-end
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full-screen per-step view returned directly from [build] so the
|
||||||
|
/// TextField is a first-level Expanded child of that column -- see
|
||||||
|
/// [NoteEditorStepPage], which documents why the flat structure matters.
|
||||||
|
Widget _buildStepPage() {
|
||||||
|
_doc.ensureControllers(_doc.template);
|
||||||
|
final sections = _doc.template.sections;
|
||||||
|
final idx = _currentStep.clamp(0, sections.length - 1);
|
||||||
|
final section = sections[idx];
|
||||||
|
return NoteEditorStepPage(
|
||||||
|
section: section,
|
||||||
|
controller: _doc.section[section.key]!,
|
||||||
|
index: idx,
|
||||||
|
total: sections.length,
|
||||||
|
autofocus: widget.autofocus,
|
||||||
|
onGoToStep: _goToStep,
|
||||||
|
onExit: _exitGuided,
|
||||||
|
onChanged: _onStepFieldChanged,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
90
lib/ui/note_editor_widget.dart
Normal file
90
lib/ui/note_editor_widget.dart
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
/// The [NoteEditor] widget's public surface: its parameters and their
|
||||||
|
/// contracts. The state that drives them lives in `note_editor.dart`.
|
||||||
|
///
|
||||||
|
/// A `part` rather than a separate library because the widget and its State
|
||||||
|
/// are genuinely one unit -- `createState` returns a private class, so they
|
||||||
|
/// cannot be split across libraries without making that class public.
|
||||||
|
part of 'note_editor.dart';
|
||||||
|
|
||||||
|
/// A guided editor for a note's text, shared by the capture and detail
|
||||||
|
/// screens.
|
||||||
|
///
|
||||||
|
/// It is a *view* over plain text: it parses [initialText] into template
|
||||||
|
/// sections and reports the re-assembled text through [onChanged] on every
|
||||||
|
/// edit. Storage stays plain text, so sync and markdown export are unaffected.
|
||||||
|
///
|
||||||
|
/// Modes (see [NoteEditorMode]):
|
||||||
|
/// * **Preview** — the note rendered as Markdown, read-only.
|
||||||
|
/// * **Guided** — a full-screen per-step view, one step per template
|
||||||
|
/// section, with guidance on what to write and why the LLM needs it.
|
||||||
|
/// * **Raw** — a single text field showing the assembled text verbatim.
|
||||||
|
///
|
||||||
|
/// Non-conforming or freeform text never enters the guided stepper (we never
|
||||||
|
/// force it into the template), so for such text Guided is unavailable and the
|
||||||
|
/// editable source stays the raw body, preserving the user's content.
|
||||||
|
///
|
||||||
|
/// Entering Guided on an empty draft first runs a two-step wizard (priority,
|
||||||
|
/// then template) via [onPriorityChanged], since those choices only make
|
||||||
|
/// sense once, before there's anything to guide. Guided itself — wizard or
|
||||||
|
/// bare step page — hides the template/mode chrome entirely (just a back arrow
|
||||||
|
/// to return to Raw); [onChromeVisibleChanged] tells the parent screen to
|
||||||
|
/// hide its own priority/status row in sync.
|
||||||
|
class NoteEditor extends StatefulWidget {
|
||||||
|
/// Creates a [NoteEditor] with the given callbacks and initial state.
|
||||||
|
const NoteEditor({
|
||||||
|
required this.onChanged,
|
||||||
|
required this.priority,
|
||||||
|
required this.onPriorityChanged,
|
||||||
|
required this.onChromeVisibleChanged,
|
||||||
|
this.initialText = '',
|
||||||
|
this.initialTemplate,
|
||||||
|
this.initialMode = NoteEditorMode.guided,
|
||||||
|
this.autofocus = false,
|
||||||
|
this.advancedMode = true,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Called with the freshly assembled note text on every edit.
|
||||||
|
final ValueChanged<String> onChanged;
|
||||||
|
|
||||||
|
/// The note's current priority, shown as the wizard's starting selection.
|
||||||
|
final Priority priority;
|
||||||
|
|
||||||
|
/// Called when the priority wizard step is confirmed (Guided "Start").
|
||||||
|
final ValueChanged<Priority> onPriorityChanged;
|
||||||
|
|
||||||
|
/// Called whenever the editor's own chrome (template dropdown, mode
|
||||||
|
/// selector) is shown/hidden, so the parent screen can hide its
|
||||||
|
/// priority/status row in sync while Guided (wizard or bare stepper) is
|
||||||
|
/// active.
|
||||||
|
final ValueChanged<bool> onChromeVisibleChanged;
|
||||||
|
|
||||||
|
/// Existing note text to load. Empty for a fresh draft.
|
||||||
|
final String initialText;
|
||||||
|
|
||||||
|
/// Template to author with. When null the template is detected from
|
||||||
|
/// [initialText] (used when opening an existing note).
|
||||||
|
final NoteTemplate? initialTemplate;
|
||||||
|
|
||||||
|
/// Preferred mode to open in. Falls back to [NoteEditorMode.raw] when
|
||||||
|
/// [NoteEditorMode.guided] is requested for text that can't be guided
|
||||||
|
/// (freeform template or non-conforming content).
|
||||||
|
final NoteEditorMode initialMode;
|
||||||
|
|
||||||
|
/// Autofocus the first field, so a fresh capture needs zero taps before
|
||||||
|
/// typing — preserving the app's instant-capture invariant.
|
||||||
|
final bool autofocus;
|
||||||
|
|
||||||
|
/// Whether the template picker and View/Guided/Raw mode toggle are shown.
|
||||||
|
/// For a freshly-mounted editor, false pins the mode to
|
||||||
|
/// [NoteEditorMode.raw] regardless of [initialMode], and Guided/Preview
|
||||||
|
/// are unreachable — casual capture needs neither. Toggling this off
|
||||||
|
/// while already mid-Guided does not itself force an immediate mode
|
||||||
|
/// change (the open mode stays until the next mode transition, which
|
||||||
|
/// then resolves to raw) — a transient, self-healing state, not a hole
|
||||||
|
/// in the gating.
|
||||||
|
final bool advancedMode;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<NoteEditor> createState() => _NoteEditorState();
|
||||||
|
}
|
||||||
138
lib/ui/note_editor_wizard.dart
Normal file
138
lib/ui/note_editor_wizard.dart
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
/// The two-step wizard shown before the guided stepper on an empty draft.
|
||||||
|
///
|
||||||
|
/// Split out of `note_editor.dart` for file size. It owns its own step index
|
||||||
|
/// and pending choices — the editor only cares about the two values that come
|
||||||
|
/// back out, so keeping that state here rather than in `_NoteEditorState` is
|
||||||
|
/// both smaller and better scoped.
|
||||||
|
///
|
||||||
|
/// Priority and template are asked once, up front, because those choices only
|
||||||
|
/// make sense before there is anything to guide.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
|
||||||
|
/// Asks for a priority, then a template, then hands both back via [onStart].
|
||||||
|
class NoteEditorWizard extends StatefulWidget {
|
||||||
|
/// Creates the wizard seeded with [initialPriority] and [initialTemplate].
|
||||||
|
const NoteEditorWizard({
|
||||||
|
required this.initialPriority,
|
||||||
|
required this.initialTemplate,
|
||||||
|
required this.onStart,
|
||||||
|
required this.onCancel,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Priority the first step opens on.
|
||||||
|
final Priority initialPriority;
|
||||||
|
|
||||||
|
/// Template the second step opens on.
|
||||||
|
final NoteTemplate initialTemplate;
|
||||||
|
|
||||||
|
/// Called with both choices when the user presses "Start".
|
||||||
|
final void Function(Priority priority, NoteTemplate template) onStart;
|
||||||
|
|
||||||
|
/// Called when the user dismisses the wizard.
|
||||||
|
final VoidCallback onCancel;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<NoteEditorWizard> createState() => _NoteEditorWizardState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _NoteEditorWizardState extends State<NoteEditorWizard> {
|
||||||
|
late int _step = 0;
|
||||||
|
late Priority _priority = widget.initialPriority;
|
||||||
|
late NoteTemplate _template = widget.initialTemplate;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.close),
|
||||||
|
tooltip: 'Cancel',
|
||||||
|
onPressed: widget.onCancel,
|
||||||
|
),
|
||||||
|
Text('Step ${_step + 1} of 2', style: theme.textTheme.labelLarge),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
if (_step == 0) ..._priorityStep() else ..._templateStep(),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Widget> _priorityStep() {
|
||||||
|
return [
|
||||||
|
DropdownButtonFormField<Priority>(
|
||||||
|
initialValue: _priority,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Priority',
|
||||||
|
isDense: true,
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||||
|
),
|
||||||
|
items: [
|
||||||
|
for (final p in Priority.values)
|
||||||
|
DropdownMenuItem(value: p, child: Text(p.label)),
|
||||||
|
],
|
||||||
|
onChanged: (p) {
|
||||||
|
if (p != null) setState(() => _priority = p);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerRight,
|
||||||
|
child: FilledButton(
|
||||||
|
onPressed: () => setState(() => _step = 1),
|
||||||
|
child: const Text('Next'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Widget> _templateStep() {
|
||||||
|
final templates = NoteTemplate.all.where((t) => !t.isFreeform).toList();
|
||||||
|
return [
|
||||||
|
DropdownButtonFormField<String>(
|
||||||
|
initialValue: _template.id,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Template',
|
||||||
|
isDense: true,
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||||
|
),
|
||||||
|
items: [
|
||||||
|
for (final t in templates)
|
||||||
|
DropdownMenuItem(value: t.id, child: Text(t.label)),
|
||||||
|
],
|
||||||
|
onChanged: (id) {
|
||||||
|
if (id == null) return;
|
||||||
|
setState(() => _template = templates.firstWhere((t) => t.id == id));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.end,
|
||||||
|
children: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => setState(() => _step = 0),
|
||||||
|
child: const Text('Back'),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => widget.onStart(_priority, _template),
|
||||||
|
child: const Text('Start'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
69
lib/ui/note_tile.dart
Normal file
69
lib/ui/note_tile.dart
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
/// One row of the notes list.
|
||||||
|
///
|
||||||
|
/// Split out of `notes_list_screen.dart` for file size; public only because
|
||||||
|
/// Dart privacy is library-scoped.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
|
||||||
|
/// One row in the notes list: title, metadata line, and an actions button.
|
||||||
|
class NoteTile extends StatelessWidget {
|
||||||
|
/// Creates a tile for [note].
|
||||||
|
const NoteTile({
|
||||||
|
required this.note,
|
||||||
|
required this.onTap,
|
||||||
|
required this.onActions,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The note this row displays.
|
||||||
|
final Note note;
|
||||||
|
|
||||||
|
/// Open the full note for reading/editing.
|
||||||
|
/// Called when the row body is tapped (opens the note).
|
||||||
|
final VoidCallback onTap;
|
||||||
|
|
||||||
|
/// Open the quick-actions sheet (priority/status/delete).
|
||||||
|
/// Called when the trailing actions button is tapped.
|
||||||
|
final VoidCallback onActions;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final firstLine = noteTitle(note.text);
|
||||||
|
// Every note has a status and a priority now, so both are always shown.
|
||||||
|
final meta = <String>[
|
||||||
|
note.status.label,
|
||||||
|
note.priority.label,
|
||||||
|
'edited ${_relative(note.updatedAt)}',
|
||||||
|
].join(' · ');
|
||||||
|
return ListTile(
|
||||||
|
title: Text(
|
||||||
|
firstLine.isEmpty ? '(empty)' : firstLine,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
subtitle: Text(meta),
|
||||||
|
trailing: IconButton(
|
||||||
|
icon: const Icon(Icons.more_vert),
|
||||||
|
tooltip: 'Quick actions',
|
||||||
|
onPressed: onActions,
|
||||||
|
),
|
||||||
|
onTap: onTap,
|
||||||
|
onLongPress: onActions,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compact relative time like "2m ago" for the list subtitle.
|
||||||
|
String _relative(DateTime t) {
|
||||||
|
final d = DateTime.now().difference(t);
|
||||||
|
if (d.inMinutes < 1) return 'just now';
|
||||||
|
if (d.inHours < 1) return '${d.inMinutes}m ago';
|
||||||
|
if (d.inDays < 1) return '${d.inHours}h ago';
|
||||||
|
return '${d.inDays}d ago';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bottom sheet for editing one note's priority/status or deleting it.
|
||||||
184
lib/ui/notes_filter_sheet.dart
Normal file
184
lib/ui/notes_filter_sheet.dart
Normal file
@ -0,0 +1,184 @@
|
|||||||
|
/// The notes-list filter sheet and its multi-select chip row.
|
||||||
|
///
|
||||||
|
/// Split out of `notes_list_screen.dart` for file size. [FilterSheet] is
|
||||||
|
/// public only because Dart privacy is library-scoped; it is still an
|
||||||
|
/// implementation detail of the notes list, pushed by
|
||||||
|
/// `_NotesListScreenState._openFilters`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/ui/note_date_range_field.dart';
|
||||||
|
import 'package:todo/ui/notes_list_screen.dart' show kDefaultStatuses;
|
||||||
|
|
||||||
|
/// The filter editing sheet: priority + status multi-select and Created /
|
||||||
|
/// Last-updated date ranges (presets + a custom range picker). Edits a
|
||||||
|
/// working copy and returns it via [Navigator.pop] on "Apply".
|
||||||
|
class FilterSheet extends StatefulWidget {
|
||||||
|
/// Creates the sheet seeded with the currently applied [initial] filter.
|
||||||
|
const FilterSheet({required this.initial, super.key});
|
||||||
|
|
||||||
|
/// The filter the sheet opens with; edits are made to a working copy.
|
||||||
|
final NoteFilter initial;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<FilterSheet> createState() => _FilterSheetState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _FilterSheetState extends State<FilterSheet> {
|
||||||
|
late Set<Priority> _priorities = {...widget.initial.priorities};
|
||||||
|
late Set<Status> _statuses = {...widget.initial.statuses};
|
||||||
|
late DateTime? _createdFrom = widget.initial.createdFrom;
|
||||||
|
late DateTime? _createdTo = widget.initial.createdTo;
|
||||||
|
late DateTime? _updatedFrom = widget.initial.updatedFrom;
|
||||||
|
late DateTime? _updatedTo = widget.initial.updatedTo;
|
||||||
|
|
||||||
|
void _toggle<T>(Set<T> set, T value) {
|
||||||
|
setState(() => set.contains(value) ? set.remove(value) : set.add(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
void _clearAll() {
|
||||||
|
setState(() {
|
||||||
|
_priorities = {};
|
||||||
|
// Reset to the default view (hide Done/Abandoned), not an empty set,
|
||||||
|
// so "Clear all" matches the app's unfiltered baseline.
|
||||||
|
_statuses = {...kDefaultStatuses};
|
||||||
|
_createdFrom = null;
|
||||||
|
_createdTo = null;
|
||||||
|
_updatedFrom = null;
|
||||||
|
_updatedTo = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
NoteFilter _build() {
|
||||||
|
// query is owned by the search box and re-applied by the caller.
|
||||||
|
return NoteFilter(
|
||||||
|
priorities: _priorities,
|
||||||
|
statuses: _statuses,
|
||||||
|
createdFrom: _createdFrom,
|
||||||
|
createdTo: _createdTo,
|
||||||
|
updatedFrom: _updatedFrom,
|
||||||
|
updatedTo: _updatedTo,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return SafeArea(
|
||||||
|
child: Padding(
|
||||||
|
padding: EdgeInsets.fromLTRB(
|
||||||
|
16,
|
||||||
|
0,
|
||||||
|
16,
|
||||||
|
16 + MediaQuery.of(context).viewInsets.bottom,
|
||||||
|
),
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Text('Filters', style: theme.textTheme.titleLarge),
|
||||||
|
const Spacer(),
|
||||||
|
TextButton(
|
||||||
|
onPressed: _clearAll,
|
||||||
|
child: const Text('Clear all'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
_MultiChips<Status>(
|
||||||
|
label: 'Status',
|
||||||
|
values: Status.values,
|
||||||
|
selected: _statuses,
|
||||||
|
labelOf: (s) => s.label,
|
||||||
|
onToggle: (s) => _toggle(_statuses, s),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
_MultiChips<Priority>(
|
||||||
|
label: 'Priority',
|
||||||
|
values: Priority.values,
|
||||||
|
selected: _priorities,
|
||||||
|
labelOf: (p) => p.label,
|
||||||
|
onToggle: (p) => _toggle(_priorities, p),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
DateRangeField(
|
||||||
|
label: 'Created',
|
||||||
|
from: _createdFrom,
|
||||||
|
to: _createdTo,
|
||||||
|
onChanged: (from, to) => setState(() {
|
||||||
|
_createdFrom = from;
|
||||||
|
_createdTo = to;
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
DateRangeField(
|
||||||
|
label: 'Last updated',
|
||||||
|
from: _updatedFrom,
|
||||||
|
to: _updatedTo,
|
||||||
|
onChanged: (from, to) => setState(() {
|
||||||
|
_updatedFrom = from;
|
||||||
|
_updatedTo = to;
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 20),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(_build()),
|
||||||
|
child: const Text('Apply'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Multi-select chip group for an enum (used by the filter sheet).
|
||||||
|
class _MultiChips<T> extends StatelessWidget {
|
||||||
|
const _MultiChips({
|
||||||
|
required this.label,
|
||||||
|
required this.values,
|
||||||
|
required this.selected,
|
||||||
|
required this.labelOf,
|
||||||
|
required this.onToggle,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
final List<T> values;
|
||||||
|
final Set<T> selected;
|
||||||
|
final String Function(T) labelOf;
|
||||||
|
final ValueChanged<T> onToggle;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(label, style: Theme.of(context).textTheme.labelLarge),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
children: [
|
||||||
|
for (final v in values)
|
||||||
|
FilterChip(
|
||||||
|
label: Text(labelOf(v)),
|
||||||
|
selected: selected.contains(v),
|
||||||
|
onSelected: (_) => onToggle(v),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A date-range control offering quick presets plus a custom range picker.
|
||||||
|
///
|
||||||
|
/// Reports the chosen [from]/[to] (day granularity, both inclusive) back to
|
||||||
|
/// the parent; `null`/`null` means "any date" for this field.
|
||||||
52
lib/ui/notes_list_navigation.dart
Normal file
52
lib/ui/notes_list_navigation.dart
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
/// Navigation out of the notes list: the detail screen and the actions sheet.
|
||||||
|
///
|
||||||
|
/// Split out of `notes_list_screen.dart` for file size. Plain functions rather
|
||||||
|
/// than methods because neither needs the screen's state -- they only need a
|
||||||
|
/// context, the note, and the store.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/ui/note_actions_sheet.dart';
|
||||||
|
import 'package:todo/ui/note_detail_screen.dart';
|
||||||
|
|
||||||
|
/// Opens the full note: read it, edit the body, change priority/status.
|
||||||
|
Future<void> openNote(
|
||||||
|
BuildContext context,
|
||||||
|
Note note,
|
||||||
|
NoteRepository repository,
|
||||||
|
) async {
|
||||||
|
await Navigator.of(context).push<void>(
|
||||||
|
MaterialPageRoute(
|
||||||
|
builder: (_) => NoteDetailScreen(note: note, repository: repository),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the per-note quick-actions sheet (priority, status, delete).
|
||||||
|
Future<void> openNoteActions(
|
||||||
|
BuildContext context,
|
||||||
|
Note note,
|
||||||
|
NoteRepository repository,
|
||||||
|
) async {
|
||||||
|
await showModalBottomSheet<void>(
|
||||||
|
context: context,
|
||||||
|
showDragHandle: true,
|
||||||
|
// Scroll-controlled so the sheet can exceed the default 9/16 of the
|
||||||
|
// viewport. On a 768px-tall screen that default is only ~432px, and this
|
||||||
|
// sheet's content grows with the note title and its chip rows -- an
|
||||||
|
// unscrollable sheet would clip the Delete action out of reach.
|
||||||
|
isScrollControlled: true,
|
||||||
|
builder: (_) => NoteActionsSheet(
|
||||||
|
note: note,
|
||||||
|
onChanged: (updated) async {
|
||||||
|
await repository.upsert(updated);
|
||||||
|
},
|
||||||
|
onDelete: () async {
|
||||||
|
await repository.delete(note.id);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -4,9 +4,9 @@ import 'package:flutter/material.dart';
|
|||||||
|
|
||||||
import 'package:todo/data/note.dart';
|
import 'package:todo/data/note.dart';
|
||||||
import 'package:todo/data/note_repository.dart';
|
import 'package:todo/data/note_repository.dart';
|
||||||
import 'package:todo/data/note_template.dart';
|
import 'package:todo/ui/note_tile.dart';
|
||||||
import 'package:todo/ui/confirm.dart';
|
import 'package:todo/ui/notes_filter_sheet.dart';
|
||||||
import 'package:todo/ui/note_detail_screen.dart';
|
import 'package:todo/ui/notes_list_navigation.dart';
|
||||||
|
|
||||||
/// The default status selection: hide completed/dropped work. This is the
|
/// The default status selection: hide completed/dropped work. This is the
|
||||||
/// app's notion of "unfiltered", so it does not count towards the filter
|
/// app's notion of "unfiltered", so it does not count towards the filter
|
||||||
@ -103,7 +103,7 @@ class _NotesListScreenState extends State<NotesListScreen> {
|
|||||||
context: context,
|
context: context,
|
||||||
isScrollControlled: true,
|
isScrollControlled: true,
|
||||||
showDragHandle: true,
|
showDragHandle: true,
|
||||||
builder: (_) => _FilterSheet(initial: _filter),
|
builder: (_) => FilterSheet(initial: _filter),
|
||||||
);
|
);
|
||||||
if (edited != null) {
|
if (edited != null) {
|
||||||
_filter = edited.copyWith(query: _searchController.text);
|
_filter = edited.copyWith(query: _searchController.text);
|
||||||
@ -111,38 +111,6 @@ class _NotesListScreenState extends State<NotesListScreen> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Opens the full note: read it, edit the body, change priority/status.
|
|
||||||
Future<void> _openNote(Note note) async {
|
|
||||||
await Navigator.of(context).push<void>(
|
|
||||||
MaterialPageRoute(
|
|
||||||
builder: (_) =>
|
|
||||||
NoteDetailScreen(note: note, repository: widget.repository),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Opens the per-note quick-actions sheet (priority, status, delete).
|
|
||||||
Future<void> _openNoteActions(Note note) async {
|
|
||||||
await showModalBottomSheet<void>(
|
|
||||||
context: context,
|
|
||||||
showDragHandle: true,
|
|
||||||
// Scroll-controlled so the sheet can exceed the default 9/16 of the
|
|
||||||
// viewport. On a 768px-tall screen that default is only ~432px, and this
|
|
||||||
// sheet's content grows with the note title and its chip rows -- an
|
|
||||||
// unscrollable sheet would clip the Delete action out of reach.
|
|
||||||
isScrollControlled: true,
|
|
||||||
builder: (_) => _NoteActionsSheet(
|
|
||||||
note: note,
|
|
||||||
onChanged: (updated) async {
|
|
||||||
await widget.repository.upsert(updated);
|
|
||||||
},
|
|
||||||
onDelete: () async {
|
|
||||||
await widget.repository.delete(note.id);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final badgeCount = _badgeCount;
|
final badgeCount = _badgeCount;
|
||||||
@ -236,11 +204,13 @@ class _NotesListScreenState extends State<NotesListScreen> {
|
|||||||
return ListView.separated(
|
return ListView.separated(
|
||||||
itemCount: notes.length,
|
itemCount: notes.length,
|
||||||
separatorBuilder: (_, _) => const Divider(height: 1),
|
separatorBuilder: (_, _) => const Divider(height: 1),
|
||||||
itemBuilder: (context, i) => _NoteTile(
|
itemBuilder: (context, i) => NoteTile(
|
||||||
key: ValueKey(notes[i].id),
|
key: ValueKey(notes[i].id),
|
||||||
note: notes[i],
|
note: notes[i],
|
||||||
onTap: () => _openNote(notes[i]),
|
onTap: () =>
|
||||||
onActions: () => _openNoteActions(notes[i]),
|
openNote(context, notes[i], widget.repository),
|
||||||
|
onActions: () =>
|
||||||
|
openNoteActions(context, notes[i], widget.repository),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@ -253,446 +223,3 @@ class _NotesListScreenState extends State<NotesListScreen> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// One row in the notes list: first line, then a metadata subtitle.
|
/// One row in the notes list: first line, then a metadata subtitle.
|
||||||
class _NoteTile extends StatelessWidget {
|
|
||||||
const _NoteTile({
|
|
||||||
required this.note,
|
|
||||||
required this.onTap,
|
|
||||||
required this.onActions,
|
|
||||||
super.key,
|
|
||||||
});
|
|
||||||
|
|
||||||
final Note note;
|
|
||||||
|
|
||||||
/// Open the full note for reading/editing.
|
|
||||||
final VoidCallback onTap;
|
|
||||||
|
|
||||||
/// Open the quick-actions sheet (priority/status/delete).
|
|
||||||
final VoidCallback onActions;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final firstLine = noteTitle(note.text);
|
|
||||||
// Every note has a status and a priority now, so both are always shown.
|
|
||||||
final meta = <String>[
|
|
||||||
note.status.label,
|
|
||||||
note.priority.label,
|
|
||||||
'edited ${_relative(note.updatedAt)}',
|
|
||||||
].join(' · ');
|
|
||||||
return ListTile(
|
|
||||||
title: Text(
|
|
||||||
firstLine.isEmpty ? '(empty)' : firstLine,
|
|
||||||
maxLines: 2,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
),
|
|
||||||
subtitle: Text(meta),
|
|
||||||
trailing: IconButton(
|
|
||||||
icon: const Icon(Icons.more_vert),
|
|
||||||
tooltip: 'Quick actions',
|
|
||||||
onPressed: onActions,
|
|
||||||
),
|
|
||||||
onTap: onTap,
|
|
||||||
onLongPress: onActions,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Compact relative time like "2m ago" for the list subtitle.
|
|
||||||
String _relative(DateTime t) {
|
|
||||||
final d = DateTime.now().difference(t);
|
|
||||||
if (d.inMinutes < 1) return 'just now';
|
|
||||||
if (d.inHours < 1) return '${d.inMinutes}m ago';
|
|
||||||
if (d.inDays < 1) return '${d.inHours}h ago';
|
|
||||||
return '${d.inDays}d ago';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bottom sheet for editing one note's priority/status or deleting it.
|
|
||||||
class _NoteActionsSheet extends StatefulWidget {
|
|
||||||
const _NoteActionsSheet({
|
|
||||||
required this.note,
|
|
||||||
required this.onChanged,
|
|
||||||
required this.onDelete,
|
|
||||||
});
|
|
||||||
|
|
||||||
final Note note;
|
|
||||||
final Future<void> Function(Note) onChanged;
|
|
||||||
final Future<void> Function() onDelete;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<_NoteActionsSheet> createState() => _NoteActionsSheetState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _NoteActionsSheetState extends State<_NoteActionsSheet> {
|
|
||||||
late Priority _priority = widget.note.priority;
|
|
||||||
late Status _status = widget.note.status;
|
|
||||||
|
|
||||||
Future<void> _persist() async {
|
|
||||||
await widget.onChanged(
|
|
||||||
widget.note.copyWith(
|
|
||||||
priority: _priority,
|
|
||||||
status: _status,
|
|
||||||
updatedAt: DateTime.now(),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final firstLine = noteTitle(widget.note.text);
|
|
||||||
return SafeArea(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
firstLine.isEmpty ? '(empty)' : firstLine,
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
maxLines: 2,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
_EnumChips<Status>(
|
|
||||||
label: 'Status',
|
|
||||||
values: Status.values,
|
|
||||||
selected: {_status},
|
|
||||||
labelOf: (s) => s.label,
|
|
||||||
onSelected: (s) {
|
|
||||||
setState(() => _status = s);
|
|
||||||
unawaited(_persist());
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
_EnumChips<Priority>(
|
|
||||||
label: 'Priority',
|
|
||||||
values: Priority.values,
|
|
||||||
selected: {_priority},
|
|
||||||
labelOf: (p) => p.label,
|
|
||||||
onSelected: (p) {
|
|
||||||
setState(() => _priority = p);
|
|
||||||
unawaited(_persist());
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
OutlinedButton.icon(
|
|
||||||
icon: const Icon(Icons.delete_outline),
|
|
||||||
label: const Text('Delete note'),
|
|
||||||
style: OutlinedButton.styleFrom(
|
|
||||||
foregroundColor: Theme.of(context).colorScheme.error,
|
|
||||||
),
|
|
||||||
onPressed: () async {
|
|
||||||
final confirmed = await confirmDestructive(
|
|
||||||
context,
|
|
||||||
title: 'Delete note?',
|
|
||||||
message: 'This cannot be undone.',
|
|
||||||
);
|
|
||||||
if (!confirmed) return;
|
|
||||||
await widget.onDelete();
|
|
||||||
if (context.mounted) Navigator.of(context).pop();
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Single-select chip row for an enum (used for per-note priority/status).
|
|
||||||
class _EnumChips<T> extends StatelessWidget {
|
|
||||||
const _EnumChips({
|
|
||||||
required this.label,
|
|
||||||
required this.values,
|
|
||||||
required this.selected,
|
|
||||||
required this.labelOf,
|
|
||||||
required this.onSelected,
|
|
||||||
});
|
|
||||||
|
|
||||||
final String label;
|
|
||||||
final List<T> values;
|
|
||||||
final Set<T> selected;
|
|
||||||
final String Function(T) labelOf;
|
|
||||||
final ValueChanged<T> onSelected;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(label, style: Theme.of(context).textTheme.labelLarge),
|
|
||||||
const SizedBox(height: 6),
|
|
||||||
Wrap(
|
|
||||||
spacing: 8,
|
|
||||||
children: [
|
|
||||||
for (final v in values)
|
|
||||||
ChoiceChip(
|
|
||||||
label: Text(labelOf(v)),
|
|
||||||
selected: selected.contains(v),
|
|
||||||
onSelected: (_) => onSelected(v),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The filter editing sheet: priority + status multi-select and Created /
|
|
||||||
/// Last-updated date ranges (presets + a custom range picker). Edits a
|
|
||||||
/// working copy and returns it via [Navigator.pop] on "Apply".
|
|
||||||
class _FilterSheet extends StatefulWidget {
|
|
||||||
const _FilterSheet({required this.initial});
|
|
||||||
|
|
||||||
final NoteFilter initial;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<_FilterSheet> createState() => _FilterSheetState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _FilterSheetState extends State<_FilterSheet> {
|
|
||||||
late Set<Priority> _priorities = {...widget.initial.priorities};
|
|
||||||
late Set<Status> _statuses = {...widget.initial.statuses};
|
|
||||||
late DateTime? _createdFrom = widget.initial.createdFrom;
|
|
||||||
late DateTime? _createdTo = widget.initial.createdTo;
|
|
||||||
late DateTime? _updatedFrom = widget.initial.updatedFrom;
|
|
||||||
late DateTime? _updatedTo = widget.initial.updatedTo;
|
|
||||||
|
|
||||||
void _toggle<T>(Set<T> set, T value) {
|
|
||||||
setState(() => set.contains(value) ? set.remove(value) : set.add(value));
|
|
||||||
}
|
|
||||||
|
|
||||||
void _clearAll() {
|
|
||||||
setState(() {
|
|
||||||
_priorities = {};
|
|
||||||
// Reset to the default view (hide Done/Abandoned), not an empty set,
|
|
||||||
// so "Clear all" matches the app's unfiltered baseline.
|
|
||||||
_statuses = {...kDefaultStatuses};
|
|
||||||
_createdFrom = null;
|
|
||||||
_createdTo = null;
|
|
||||||
_updatedFrom = null;
|
|
||||||
_updatedTo = null;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
NoteFilter _build() {
|
|
||||||
// query is owned by the search box and re-applied by the caller.
|
|
||||||
return NoteFilter(
|
|
||||||
priorities: _priorities,
|
|
||||||
statuses: _statuses,
|
|
||||||
createdFrom: _createdFrom,
|
|
||||||
createdTo: _createdTo,
|
|
||||||
updatedFrom: _updatedFrom,
|
|
||||||
updatedTo: _updatedTo,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final theme = Theme.of(context);
|
|
||||||
return SafeArea(
|
|
||||||
child: Padding(
|
|
||||||
padding: EdgeInsets.fromLTRB(
|
|
||||||
16,
|
|
||||||
0,
|
|
||||||
16,
|
|
||||||
16 + MediaQuery.of(context).viewInsets.bottom,
|
|
||||||
),
|
|
||||||
child: SingleChildScrollView(
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Text('Filters', style: theme.textTheme.titleLarge),
|
|
||||||
const Spacer(),
|
|
||||||
TextButton(
|
|
||||||
onPressed: _clearAll,
|
|
||||||
child: const Text('Clear all'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
_MultiChips<Status>(
|
|
||||||
label: 'Status',
|
|
||||||
values: Status.values,
|
|
||||||
selected: _statuses,
|
|
||||||
labelOf: (s) => s.label,
|
|
||||||
onToggle: (s) => _toggle(_statuses, s),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
_MultiChips<Priority>(
|
|
||||||
label: 'Priority',
|
|
||||||
values: Priority.values,
|
|
||||||
selected: _priorities,
|
|
||||||
labelOf: (p) => p.label,
|
|
||||||
onToggle: (p) => _toggle(_priorities, p),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
_DateRangeField(
|
|
||||||
label: 'Created',
|
|
||||||
from: _createdFrom,
|
|
||||||
to: _createdTo,
|
|
||||||
onChanged: (from, to) => setState(() {
|
|
||||||
_createdFrom = from;
|
|
||||||
_createdTo = to;
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
_DateRangeField(
|
|
||||||
label: 'Last updated',
|
|
||||||
from: _updatedFrom,
|
|
||||||
to: _updatedTo,
|
|
||||||
onChanged: (from, to) => setState(() {
|
|
||||||
_updatedFrom = from;
|
|
||||||
_updatedTo = to;
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 20),
|
|
||||||
FilledButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop(_build()),
|
|
||||||
child: const Text('Apply'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Multi-select chip group for an enum (used by the filter sheet).
|
|
||||||
class _MultiChips<T> extends StatelessWidget {
|
|
||||||
const _MultiChips({
|
|
||||||
required this.label,
|
|
||||||
required this.values,
|
|
||||||
required this.selected,
|
|
||||||
required this.labelOf,
|
|
||||||
required this.onToggle,
|
|
||||||
});
|
|
||||||
|
|
||||||
final String label;
|
|
||||||
final List<T> values;
|
|
||||||
final Set<T> selected;
|
|
||||||
final String Function(T) labelOf;
|
|
||||||
final ValueChanged<T> onToggle;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(label, style: Theme.of(context).textTheme.labelLarge),
|
|
||||||
const SizedBox(height: 6),
|
|
||||||
Wrap(
|
|
||||||
spacing: 8,
|
|
||||||
children: [
|
|
||||||
for (final v in values)
|
|
||||||
FilterChip(
|
|
||||||
label: Text(labelOf(v)),
|
|
||||||
selected: selected.contains(v),
|
|
||||||
onSelected: (_) => onToggle(v),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A date-range control offering quick presets plus a custom range picker.
|
|
||||||
///
|
|
||||||
/// Reports the chosen [from]/[to] (day granularity, both inclusive) back to
|
|
||||||
/// the parent; `null`/`null` means "any date" for this field.
|
|
||||||
class _DateRangeField extends StatelessWidget {
|
|
||||||
const _DateRangeField({
|
|
||||||
required this.label,
|
|
||||||
required this.from,
|
|
||||||
required this.to,
|
|
||||||
required this.onChanged,
|
|
||||||
});
|
|
||||||
|
|
||||||
final String label;
|
|
||||||
final DateTime? from;
|
|
||||||
final DateTime? to;
|
|
||||||
|
|
||||||
/// Called with the new (from, to); either may be null to clear.
|
|
||||||
final void Function(DateTime? from, DateTime? to) onChanged;
|
|
||||||
|
|
||||||
bool get _hasRange => from != null || to != null;
|
|
||||||
|
|
||||||
/// Sets a preset range of the last [days] days ending today.
|
|
||||||
void _applyDays(int days) {
|
|
||||||
final now = DateTime.now();
|
|
||||||
final today = DateTime(now.year, now.month, now.day);
|
|
||||||
onChanged(today.subtract(Duration(days: days - 1)), today);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _pickCustom(BuildContext context) async {
|
|
||||||
final now = DateTime.now();
|
|
||||||
final picked = await showDateRangePicker(
|
|
||||||
context: context,
|
|
||||||
firstDate: DateTime(2020),
|
|
||||||
lastDate: DateTime(now.year + 1, 12, 31),
|
|
||||||
initialDateRange: (from != null && to != null)
|
|
||||||
? DateTimeRange(start: from!, end: to!)
|
|
||||||
: null,
|
|
||||||
);
|
|
||||||
if (picked != null) onChanged(picked.start, picked.end);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final theme = Theme.of(context);
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Text(label, style: theme.textTheme.labelLarge),
|
|
||||||
const Spacer(),
|
|
||||||
if (_hasRange)
|
|
||||||
Text(_rangeLabel(), style: theme.textTheme.bodySmall),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 6),
|
|
||||||
Wrap(
|
|
||||||
spacing: 8,
|
|
||||||
children: [
|
|
||||||
ActionChip(
|
|
||||||
label: const Text('Today'),
|
|
||||||
onPressed: () => _applyDays(1),
|
|
||||||
),
|
|
||||||
ActionChip(
|
|
||||||
label: const Text('7 days'),
|
|
||||||
onPressed: () => _applyDays(7),
|
|
||||||
),
|
|
||||||
ActionChip(
|
|
||||||
label: const Text('30 days'),
|
|
||||||
onPressed: () => _applyDays(30),
|
|
||||||
),
|
|
||||||
ActionChip(
|
|
||||||
label: const Text('Custom…'),
|
|
||||||
onPressed: () => _pickCustom(context),
|
|
||||||
),
|
|
||||||
if (_hasRange)
|
|
||||||
ActionChip(
|
|
||||||
avatar: const Icon(Icons.clear, size: 16),
|
|
||||||
label: const Text('Any'),
|
|
||||||
onPressed: () => onChanged(null, null),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Compact "YYYY-MM-DD → YYYY-MM-DD" (or one-sided) summary of the range.
|
|
||||||
String _rangeLabel() {
|
|
||||||
String d(DateTime? t) =>
|
|
||||||
t == null ? '…' : '${t.year}-${_two(t.month)}-${_two(t.day)}';
|
|
||||||
return '${d(from)} → ${d(to)}';
|
|
||||||
}
|
|
||||||
|
|
||||||
String _two(int n) => n.toString().padLeft(2, '0');
|
|
||||||
}
|
|
||||||
|
|||||||
16
pubspec.lock
16
pubspec.lock
@ -469,10 +469,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: matcher
|
name: matcher
|
||||||
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
|
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.12.19"
|
version: "0.12.20"
|
||||||
material_color_utilities:
|
material_color_utilities:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -485,10 +485,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: meta
|
name: meta
|
||||||
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"
|
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.18.0"
|
version: "1.19.0"
|
||||||
mime:
|
mime:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -843,10 +843,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: test_api
|
name: test_api
|
||||||
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"
|
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.7.11"
|
version: "0.7.12"
|
||||||
typed_data:
|
typed_data:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -931,10 +931,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: vector_math
|
name: vector_math
|
||||||
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
|
sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.2.0"
|
version: "2.4.2"
|
||||||
very_good_analysis:
|
very_good_analysis:
|
||||||
dependency: "direct dev"
|
dependency: "direct dev"
|
||||||
description:
|
description:
|
||||||
|
|||||||
@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
|||||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
# In Windows, build-name is used as the major, minor, and patch parts
|
# In Windows, build-name is used as the major, minor, and patch parts
|
||||||
# of the product and file versions while build-number is used as the build suffix.
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
version: 1.0.10+1
|
version: 1.0.21+1
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.12.2
|
sdk: ^3.12.2
|
||||||
|
|||||||
@ -1,5 +1,14 @@
|
|||||||
# Refactor TODO — enforce the 250-line file cap
|
# Refactor TODO — enforce the 250-line file cap
|
||||||
|
|
||||||
|
> **DONE for this repo (2026-08-14).** Every file is at most 250 lines and
|
||||||
|
> `bash ~/utils/scripts/check_file_length.sh --all` exits 0. The gate is wired
|
||||||
|
> into `.pre-commit-config.yaml` and `.github/workflows/file-length.yml`, and
|
||||||
|
> was verified from a fresh checkout: `scripts/install_hooks.sh` installs it,
|
||||||
|
> and a staged 260-line file then makes `git commit` fail. 313 tests pass at
|
||||||
|
> 100% coverage (up from 99.9%). The counts below are the pre-refactor survey,
|
||||||
|
> kept as the record of what was done — re-run the survey before reusing this
|
||||||
|
> file here. It is still a valid prompt for **other** repos.
|
||||||
|
|
||||||
> **This file is a ready-to-use prompt.** Paste it to Claude, or open this repo
|
> **This file is a ready-to-use prompt.** Paste it to Claude, or open this repo
|
||||||
> and say "do refactor_claude_todo". It is self-contained: everything needed to
|
> and say "do refactor_claude_todo". It is self-contained: everything needed to
|
||||||
> execute is below. Generated 2026-08-14 from a measured survey of every repo.
|
> execute is below. Generated 2026-08-14 from a measured survey of every repo.
|
||||||
|
|||||||
31
scripts/check_file_length.sh
Executable file
31
scripts/check_file_length.sh
Executable file
@ -0,0 +1,31 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Fail if any file in the commit exceeds the shared 250-line cap.
|
||||||
|
#
|
||||||
|
# Thin delegate to the shared gate in ~/utils, which owns the cap and the
|
||||||
|
# exemption list (generated / vendored / data files). Copying that logic here
|
||||||
|
# is what lets one repo's idea of "too long" drift from every other repo's --
|
||||||
|
# so this script only locates the shared checker and forwards its arguments.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# scripts/check_file_length.sh <file> [<file> ...] # pre-commit passes these
|
||||||
|
# scripts/check_file_length.sh --all # whole tree, from cwd
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
readonly SHARED_GATE="${UTILS_ROOT:-$HOME/utils}/scripts/check_file_length.sh"
|
||||||
|
|
||||||
|
main() {
|
||||||
|
if [[ ! -x "$SHARED_GATE" ]]; then
|
||||||
|
echo "Error: shared file-length gate not found at $SHARED_GATE" >&2
|
||||||
|
echo " Clone github.com/kuhyx/utils to ~/utils, or set" >&2
|
||||||
|
echo " UTILS_ROOT to where it lives." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
exec bash "$SHARED_GATE" "$@"
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
@ -4,8 +4,24 @@
|
|||||||
# Install this repo's git hooks.
|
# Install this repo's git hooks.
|
||||||
#
|
#
|
||||||
# .git/hooks/ is not tracked, so a fresh clone has no hooks. Run this once
|
# .git/hooks/ is not tracked, so a fresh clone has no hooks. Run this once
|
||||||
# after cloning. Unlike habit_stack and diet-guard, this repo does not use the
|
# after cloning.
|
||||||
# pre-commit framework (its quality gate is CI), so the hook is a plain script.
|
#
|
||||||
|
# Two layers, deliberately:
|
||||||
|
#
|
||||||
|
# 1. pre-commit (the framework) runs the read-only gates in
|
||||||
|
# .pre-commit-config.yaml -- the crdt_sync override check and the
|
||||||
|
# 250-line file-length cap.
|
||||||
|
# 2. A thin wrapper hook installed here runs pre-commit first and, only if
|
||||||
|
# it passed, runs scripts/bump_patch_version.sh.
|
||||||
|
#
|
||||||
|
# The bump cannot live in .pre-commit-config.yaml. pre-commit stashes
|
||||||
|
# unstaged changes for the duration of its run and restores them with
|
||||||
|
# `git apply`; the bump rewrites pubspec.yaml inside that window, so an
|
||||||
|
# uncommitted edit anywhere near the `version:` line makes the restore
|
||||||
|
# conflict -- which aborts the commit and DROPS the developer's edit from the
|
||||||
|
# working tree. Running it after pre-commit has exited keeps the mutation
|
||||||
|
# outside the stash cycle, and gating it on pre-commit's exit status stops a
|
||||||
|
# rejected commit from leaving a stray bump staged for the next one.
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@ -13,27 +29,59 @@ set -euo pipefail
|
|||||||
REPO_ROOT="$(git rev-parse --show-toplevel)"
|
REPO_ROOT="$(git rev-parse --show-toplevel)"
|
||||||
readonly REPO_ROOT
|
readonly REPO_ROOT
|
||||||
readonly HOOK="$REPO_ROOT/.git/hooks/pre-commit"
|
readonly HOOK="$REPO_ROOT/.git/hooks/pre-commit"
|
||||||
|
readonly LEGACY_MARKER='bump_patch_version.sh'
|
||||||
|
|
||||||
main() {
|
# The old hand-written hook has to go before pre-commit will install over it;
|
||||||
if [[ -e "$HOOK" ]] && ! grep -q 'bump_patch_version.sh' "$HOOK"; then
|
# pre-commit refuses to clobber a foreign hook.
|
||||||
echo "Error: $HOOK exists and is not ours; refusing to clobber it." >&2
|
remove_legacy_hook() {
|
||||||
exit 1
|
if [[ -e "$HOOK" ]] && grep -q "$LEGACY_MARKER" "$HOOK" \
|
||||||
|
&& ! grep -q 'pre-commit' "$HOOK"; then
|
||||||
|
rm -f "$HOOK"
|
||||||
|
echo "Removed the legacy hand-written pre-commit hook."
|
||||||
fi
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_pre_commit() {
|
||||||
|
if command -v pre-commit >/dev/null 2>&1; then
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
echo "Installing pre-commit..."
|
||||||
|
if command -v pipx >/dev/null 2>&1; then
|
||||||
|
pipx install pre-commit
|
||||||
|
else
|
||||||
|
python3 -m pip install --user pre-commit
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Wraps pre-commit's own generated hook so the version bump runs after it,
|
||||||
|
# and only on success. pre-commit install --hook-type pre-commit writes the
|
||||||
|
# generated script; we move it aside and call it from ours.
|
||||||
|
install_wrapper() {
|
||||||
|
local generated="$REPO_ROOT/.git/hooks/pre-commit.pre-commit-generated"
|
||||||
|
mv "$HOOK" "$generated"
|
||||||
cat > "$HOOK" <<'HOOK_BODY'
|
cat > "$HOOK" <<'HOOK_BODY'
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# Installed by scripts/install_hooks.sh — see that file.
|
# Installed by scripts/install_hooks.sh — see that file for why the version
|
||||||
|
# bump runs here rather than as a pre-commit hook.
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
readonly ROOT="$(git rev-parse --show-toplevel)"
|
ROOT="$(git rev-parse --show-toplevel)"
|
||||||
# Gate first: a local crdt_sync override left in place makes CI build a
|
readonly ROOT
|
||||||
# library this checkout has never tested against, silently and in both
|
|
||||||
# directions. Blocking the commit is the only thing that actually prevents it.
|
# The read-only gates. A non-zero exit here rejects the commit, and the bump
|
||||||
bash "$ROOT/scripts/check_no_crdt_sync_override.sh" "$ROOT/pubspec.yaml"
|
# below never runs, so a rejected attempt leaves no stray version change.
|
||||||
|
"$ROOT/.git/hooks/pre-commit.pre-commit-generated" "$@"
|
||||||
|
|
||||||
exec bash "$ROOT/scripts/bump_patch_version.sh"
|
exec bash "$ROOT/scripts/bump_patch_version.sh"
|
||||||
HOOK_BODY
|
HOOK_BODY
|
||||||
|
|
||||||
chmod 755 "$HOOK"
|
chmod 755 "$HOOK"
|
||||||
echo "Installed pre-commit hook: $HOOK"
|
}
|
||||||
|
|
||||||
|
main() {
|
||||||
|
ensure_pre_commit
|
||||||
|
remove_legacy_hook
|
||||||
|
pre-commit install
|
||||||
|
install_wrapper
|
||||||
|
echo "Installed pre-commit hooks: $HOOK"
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
139
test/analytics_event_test.dart
Normal file
139
test/analytics_event_test.dart
Normal file
@ -0,0 +1,139 @@
|
|||||||
|
/// Tests for the interaction-only analytics buffer and Firebase flush.
|
||||||
|
@TestOn('vm')
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:todo/analytics/analytics_event.dart';
|
||||||
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
|
||||||
|
import 'analytics_helpers.dart';
|
||||||
|
|
||||||
|
FirebaseRestClient _fakeClient(
|
||||||
|
Future<http.Response> Function(http.Request request) handler,
|
||||||
|
) => FirebaseRestClient(
|
||||||
|
databaseUrl: 'https://x-rtdb.europe-west1.firebasedatabase.app',
|
||||||
|
auth: FirebaseTokenProvider(
|
||||||
|
apiKey: 'AIzaKey',
|
||||||
|
store: InMemoryCredentialStore(
|
||||||
|
FirebaseCredentials(
|
||||||
|
idToken: 'id',
|
||||||
|
refreshToken: 'refresh',
|
||||||
|
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
httpClient: http_testing.MockClient(handler),
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(() => SharedPreferences.setMockInitialValues({}));
|
||||||
|
|
||||||
|
group('AnalyticsEvent', () {
|
||||||
|
test('round-trips through toJson/tryFromJson', () {
|
||||||
|
final event = AnalyticsEvent(
|
||||||
|
name: 'screen_view',
|
||||||
|
timestamp: DateTime(2026, 1, 1, 12),
|
||||||
|
params: {'screen': 'capture'},
|
||||||
|
);
|
||||||
|
final decoded = AnalyticsEvent.tryFromJson(event.toJson());
|
||||||
|
|
||||||
|
expect(decoded, isNotNull);
|
||||||
|
expect(decoded!.name, 'screen_view');
|
||||||
|
expect(decoded.timestamp, event.timestamp);
|
||||||
|
expect(decoded.params, {'screen': 'capture'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tryFromJson returns null for a non-map value', () {
|
||||||
|
expect(AnalyticsEvent.tryFromJson('not a map'), isNull);
|
||||||
|
expect(AnalyticsEvent.tryFromJson(null), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tryFromJson returns null for a missing/invalid name', () {
|
||||||
|
expect(
|
||||||
|
AnalyticsEvent.tryFromJson({'timestamp': '2026-01-01T00:00:00.000'}),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tryFromJson returns null for an unparsable timestamp', () {
|
||||||
|
expect(
|
||||||
|
AnalyticsEvent.tryFromJson({'name': 'x', 'timestamp': 'not a date'}),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tryFromJson defaults params to empty when missing/non-map', () {
|
||||||
|
final decoded = AnalyticsEvent.tryFromJson({
|
||||||
|
'name': 'x',
|
||||||
|
'timestamp': DateTime(2026).toIso8601String(),
|
||||||
|
});
|
||||||
|
expect(decoded!.params, isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('AnalyticsService.logEvent', () {
|
||||||
|
test('appends to an initially empty buffer', () async {
|
||||||
|
const service = AnalyticsService(nodeId: 'device-a');
|
||||||
|
await service.logEvent(
|
||||||
|
AnalyticsEvent(name: 'app_open', timestamp: DateTime.now()),
|
||||||
|
);
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final raw = prefs.getString('analytics.buffer');
|
||||||
|
expect(raw, isNotNull);
|
||||||
|
final decoded = jsonDecode(raw!) as List;
|
||||||
|
expect(decoded, hasLength(1));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('drops the oldest event once past the cap', () async {
|
||||||
|
const service = AnalyticsService(nodeId: 'device-a');
|
||||||
|
for (var i = 0; i < AnalyticsService.maxBufferedEvents + 5; i++) {
|
||||||
|
await service.logEvent(
|
||||||
|
AnalyticsEvent(
|
||||||
|
name: 'event_$i',
|
||||||
|
timestamp: DateTime.now(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final decoded = jsonDecode(prefs.getString('analytics.buffer')!) as List;
|
||||||
|
expect(decoded, hasLength(AnalyticsService.maxBufferedEvents));
|
||||||
|
// The oldest 5 events were dropped, so event_0..event_4 are gone.
|
||||||
|
final names = decoded.map((e) => (e as Map)['name']).toList();
|
||||||
|
expect(names, isNot(contains('event_0')));
|
||||||
|
expect(
|
||||||
|
names,
|
||||||
|
contains('event_${AnalyticsService.maxBufferedEvents + 4}'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ignores a malformed pre-existing buffer entry on read', () async {
|
||||||
|
SharedPreferences.setMockInitialValues({
|
||||||
|
'analytics.buffer': jsonEncode([
|
||||||
|
{'not': 'an event'},
|
||||||
|
{
|
||||||
|
'name': 'ok_event',
|
||||||
|
'timestamp': DateTime(2026).toIso8601String(),
|
||||||
|
'params': <String, Object?>{},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
});
|
||||||
|
const service = AnalyticsService(nodeId: 'device-a');
|
||||||
|
await service.logEvent(
|
||||||
|
AnalyticsEvent(name: 'new_event', timestamp: DateTime.now()),
|
||||||
|
);
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final decoded = jsonDecode(prefs.getString('analytics.buffer')!) as List;
|
||||||
|
// The malformed entry was dropped; only the valid + new event remain.
|
||||||
|
expect(decoded, hasLength(2));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -12,6 +12,8 @@ import 'package:shared_preferences/shared_preferences.dart';
|
|||||||
import 'package:todo/analytics/analytics_event.dart';
|
import 'package:todo/analytics/analytics_event.dart';
|
||||||
import 'package:todo/analytics/analytics_service.dart';
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
|
||||||
|
import 'analytics_helpers.dart';
|
||||||
|
|
||||||
FirebaseRestClient _fakeClient(
|
FirebaseRestClient _fakeClient(
|
||||||
Future<http.Response> Function(http.Request request) handler,
|
Future<http.Response> Function(http.Request request) handler,
|
||||||
) => FirebaseRestClient(
|
) => FirebaseRestClient(
|
||||||
@ -32,109 +34,6 @@ FirebaseRestClient _fakeClient(
|
|||||||
void main() {
|
void main() {
|
||||||
setUp(() => SharedPreferences.setMockInitialValues({}));
|
setUp(() => SharedPreferences.setMockInitialValues({}));
|
||||||
|
|
||||||
group('AnalyticsEvent', () {
|
|
||||||
test('round-trips through toJson/tryFromJson', () {
|
|
||||||
final event = AnalyticsEvent(
|
|
||||||
name: 'screen_view',
|
|
||||||
timestamp: DateTime(2026, 1, 1, 12),
|
|
||||||
params: {'screen': 'capture'},
|
|
||||||
);
|
|
||||||
final decoded = AnalyticsEvent.tryFromJson(event.toJson());
|
|
||||||
|
|
||||||
expect(decoded, isNotNull);
|
|
||||||
expect(decoded!.name, 'screen_view');
|
|
||||||
expect(decoded.timestamp, event.timestamp);
|
|
||||||
expect(decoded.params, {'screen': 'capture'});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('tryFromJson returns null for a non-map value', () {
|
|
||||||
expect(AnalyticsEvent.tryFromJson('not a map'), isNull);
|
|
||||||
expect(AnalyticsEvent.tryFromJson(null), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('tryFromJson returns null for a missing/invalid name', () {
|
|
||||||
expect(
|
|
||||||
AnalyticsEvent.tryFromJson({'timestamp': '2026-01-01T00:00:00.000'}),
|
|
||||||
isNull,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('tryFromJson returns null for an unparsable timestamp', () {
|
|
||||||
expect(
|
|
||||||
AnalyticsEvent.tryFromJson({'name': 'x', 'timestamp': 'not a date'}),
|
|
||||||
isNull,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('tryFromJson defaults params to empty when missing/non-map', () {
|
|
||||||
final decoded = AnalyticsEvent.tryFromJson({
|
|
||||||
'name': 'x',
|
|
||||||
'timestamp': DateTime(2026).toIso8601String(),
|
|
||||||
});
|
|
||||||
expect(decoded!.params, isEmpty);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('AnalyticsService.logEvent', () {
|
|
||||||
test('appends to an initially empty buffer', () async {
|
|
||||||
const service = AnalyticsService(nodeId: 'device-a');
|
|
||||||
await service.logEvent(
|
|
||||||
AnalyticsEvent(name: 'app_open', timestamp: DateTime.now()),
|
|
||||||
);
|
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
|
||||||
final raw = prefs.getString('analytics.buffer');
|
|
||||||
expect(raw, isNotNull);
|
|
||||||
final decoded = jsonDecode(raw!) as List;
|
|
||||||
expect(decoded, hasLength(1));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('drops the oldest event once past the cap', () async {
|
|
||||||
const service = AnalyticsService(nodeId: 'device-a');
|
|
||||||
for (var i = 0; i < AnalyticsService.maxBufferedEvents + 5; i++) {
|
|
||||||
await service.logEvent(
|
|
||||||
AnalyticsEvent(
|
|
||||||
name: 'event_$i',
|
|
||||||
timestamp: DateTime.now(),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
|
||||||
final decoded = jsonDecode(prefs.getString('analytics.buffer')!) as List;
|
|
||||||
expect(decoded, hasLength(AnalyticsService.maxBufferedEvents));
|
|
||||||
// The oldest 5 events were dropped, so event_0..event_4 are gone.
|
|
||||||
final names = decoded.map((e) => (e as Map)['name']).toList();
|
|
||||||
expect(names, isNot(contains('event_0')));
|
|
||||||
expect(
|
|
||||||
names,
|
|
||||||
contains('event_${AnalyticsService.maxBufferedEvents + 4}'),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('ignores a malformed pre-existing buffer entry on read', () async {
|
|
||||||
SharedPreferences.setMockInitialValues({
|
|
||||||
'analytics.buffer': jsonEncode([
|
|
||||||
{'not': 'an event'},
|
|
||||||
{
|
|
||||||
'name': 'ok_event',
|
|
||||||
'timestamp': DateTime(2026).toIso8601String(),
|
|
||||||
'params': <String, Object?>{},
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
});
|
|
||||||
const service = AnalyticsService(nodeId: 'device-a');
|
|
||||||
await service.logEvent(
|
|
||||||
AnalyticsEvent(name: 'new_event', timestamp: DateTime.now()),
|
|
||||||
);
|
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
|
||||||
final decoded = jsonDecode(prefs.getString('analytics.buffer')!) as List;
|
|
||||||
// The malformed entry was dropped; only the valid + new event remain.
|
|
||||||
expect(decoded, hasLength(2));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('AnalyticsService.flush', () {
|
group('AnalyticsService.flush', () {
|
||||||
test('does nothing when client is null', () async {
|
test('does nothing when client is null', () async {
|
||||||
const service = AnalyticsService(nodeId: 'device-a');
|
const service = AnalyticsService(nodeId: 'device-a');
|
||||||
33
test/analytics_helpers.dart
Normal file
33
test/analytics_helpers.dart
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
/// The fake FirebaseRestClient used by the analytics tests.
|
||||||
|
///
|
||||||
|
/// Shared by the files `analytics_service_test.dart` was split into for the
|
||||||
|
/// 250-line cap. Deliberately NOT named `*_test.dart`: the runner would
|
||||||
|
/// collect it and fail on the missing `main()`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:todo/analytics/analytics_event.dart';
|
||||||
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
|
||||||
|
FirebaseRestClient _fakeClient(
|
||||||
|
Future<http.Response> Function(http.Request request) handler,
|
||||||
|
) => FirebaseRestClient(
|
||||||
|
databaseUrl: 'https://x-rtdb.europe-west1.firebasedatabase.app',
|
||||||
|
auth: FirebaseTokenProvider(
|
||||||
|
apiKey: 'AIzaKey',
|
||||||
|
store: InMemoryCredentialStore(
|
||||||
|
FirebaseCredentials(
|
||||||
|
idToken: 'id',
|
||||||
|
refreshToken: 'refresh',
|
||||||
|
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
httpClient: http_testing.MockClient(handler),
|
||||||
|
);
|
||||||
146
test/capture_screen_advanced_test.dart
Normal file
146
test/capture_screen_advanced_test.dart
Normal file
@ -0,0 +1,146 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
import 'package:todo/sync/local_backup.dart';
|
||||||
|
import 'package:todo/sync/notes_markdown.dart';
|
||||||
|
import 'package:todo/ui/capture_screen.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
|
import 'package:todo/ui/settings_screen.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
import 'capture_screen_harness.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets(
|
||||||
|
'auto-sync adopts a newer advancedMode value from Firebase',
|
||||||
|
(tester) async {
|
||||||
|
final remoteTime = DateTime(2026, 6);
|
||||||
|
final firebase = FirebaseRestClient(
|
||||||
|
databaseUrl: 'https://x-rtdb.europe-west1.firebasedatabase.app',
|
||||||
|
auth: FirebaseTokenProvider(
|
||||||
|
apiKey: 'AIzaKey',
|
||||||
|
store: InMemoryCredentialStore(
|
||||||
|
FirebaseCredentials(
|
||||||
|
idToken: 'id',
|
||||||
|
refreshToken: 'refresh',
|
||||||
|
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
httpClient: MockClient((request) async {
|
||||||
|
if (request.url.path == '/settings/advancedMode.json') {
|
||||||
|
return http.Response(
|
||||||
|
'{"value": "true", '
|
||||||
|
'"updatedAtMillis": "${remoteTime.millisecondsSinceEpoch}"}',
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (request.method == 'PUT') return http.Response(request.body, 200);
|
||||||
|
return http.Response('null', 200);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
final appSettings = ValueNotifier(
|
||||||
|
AppSettings(
|
||||||
|
advancedMode: false,
|
||||||
|
// Older than remoteTime, and non-null, so the reconciliation
|
||||||
|
// guard's `currentAt != null && !reconciledAt.isAfter(currentAt)`
|
||||||
|
// check actually evaluates both operands.
|
||||||
|
advancedModeUpdatedAt: remoteTime.subtract(
|
||||||
|
const Duration(days: 1),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await pumpCapture(
|
||||||
|
tester,
|
||||||
|
prefs: configuredPrefs,
|
||||||
|
firebaseFactory: () async => firebase,
|
||||||
|
appSettings: appSettings,
|
||||||
|
);
|
||||||
|
await tester.pump(); // settings load → auto-sync (pull) …
|
||||||
|
await tester.pump(); // … then push, then reconcile
|
||||||
|
|
||||||
|
expect(appSettings.value.advancedMode, isTrue);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('logs app_open when analytics is injected', (tester) async {
|
||||||
|
const analytics = AnalyticsService(nodeId: 'device-a');
|
||||||
|
await pumpCapture(tester, analytics: analytics);
|
||||||
|
await tester.pump(); // flush the unawaited logEvent's prefs write
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final buffer = prefs.getString('analytics.buffer');
|
||||||
|
expect(buffer, isNotNull);
|
||||||
|
expect(buffer, contains('app_open'));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('auto-syncs on launch when configured', (tester) async {
|
||||||
|
final methods = <String>[];
|
||||||
|
await pumpCapture(
|
||||||
|
tester,
|
||||||
|
prefs: configuredPrefs,
|
||||||
|
httpClient: recordingMock(methods),
|
||||||
|
);
|
||||||
|
await tester.pump(); // settings load → auto-sync (pull) …
|
||||||
|
await tester.pump(); // … then push
|
||||||
|
|
||||||
|
expect(methods, contains('PUT')); // this device pushed its changeset
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('does not auto-sync when unconfigured', (tester) async {
|
||||||
|
final methods = <String>[];
|
||||||
|
await pumpCapture(tester, httpClient: recordingMock(methods)); // no token
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(methods, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('auto-syncs again when the app is backgrounded', (tester) async {
|
||||||
|
final methods = <String>[];
|
||||||
|
await pumpCapture(
|
||||||
|
tester,
|
||||||
|
prefs: configuredPrefs,
|
||||||
|
httpClient: recordingMock(methods),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
methods.clear();
|
||||||
|
|
||||||
|
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// A sync ran. Not `contains('PUT')`: the launch sync above already pushed
|
||||||
|
// this log, so revision tracking correctly suppresses the second, unchanged
|
||||||
|
// push -- that suppression is the point of the revision cache.
|
||||||
|
expect(methods, isNotEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('auto-sync failure shows no snackbar but flags the status line', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final mock = MockClient((_) async => throw Exception('offline'));
|
||||||
|
await pumpCapture(tester, prefs: configuredPrefs, httpClient: mock);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// Capture must never be interrupted by a snackbar…
|
||||||
|
expect(find.byType(SnackBar), findsNothing);
|
||||||
|
// …but the failure is no longer swallowed: the status line shows it.
|
||||||
|
expect(find.textContaining('Sync failed at'), findsOneWidget);
|
||||||
|
expect(find.textContaining('offline'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
161
test/capture_screen_editing_test.dart
Normal file
161
test/capture_screen_editing_test.dart
Normal file
@ -0,0 +1,161 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
import 'package:todo/sync/local_backup.dart';
|
||||||
|
import 'package:todo/sync/notes_markdown.dart';
|
||||||
|
import 'package:todo/ui/capture_screen.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
|
import 'package:todo/ui/settings_screen.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
import 'capture_screen_harness.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('defaults to Raw, with Guided available via the entry wizard', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpCapture(tester);
|
||||||
|
|
||||||
|
// Defaults to Raw: a single text field, no note persisted yet.
|
||||||
|
expect(find.byType(TextField), findsOneWidget);
|
||||||
|
expect(find.text('Guided'), findsOneWidget);
|
||||||
|
expect(find.text('0'), findsOneWidget);
|
||||||
|
|
||||||
|
// Tapping Guided on the empty draft opens the priority+template wizard
|
||||||
|
// rather than jumping straight into the stepper.
|
||||||
|
await tester.tap(find.text('Guided'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('Step 1 of 2'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Next'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(find.text('Start'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// Now on step 1 of the full-screen step page.
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||||||
|
expect(
|
||||||
|
find.text('1 / ${NoteTemplate.llmDesignSpec.sections.length}'),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
expect(find.textContaining('imperative'), findsOneWidget); // title helper
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('saving the untouched template creates no note', (tester) async {
|
||||||
|
final repo = await pumpCapture(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('New note'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(await repo.listNotes(), isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('typing into the template persists a note with defaults', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final repo = await pumpCapture(tester);
|
||||||
|
|
||||||
|
// The first field in the guided stepper is the title section.
|
||||||
|
await tester.enterText(find.byType(TextField).first, 'My idea');
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
final notes = await repo.listNotes();
|
||||||
|
expect(notes, hasLength(1));
|
||||||
|
expect(notes.single.text, contains('My idea'));
|
||||||
|
expect(notes.single.priority, Priority.medium);
|
||||||
|
expect(notes.single.status, Status.todo);
|
||||||
|
expect(find.text('1'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the new-note action resets the template', (tester) async {
|
||||||
|
final repo = await pumpCapture(tester);
|
||||||
|
|
||||||
|
await tester.enterText(find.byType(TextField).first, 'A real idea');
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(find.byTooltip('New note'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(await repo.listNotes(), hasLength(1));
|
||||||
|
// The editor reset to a fresh, empty Raw draft.
|
||||||
|
expect(find.byType(TextField), findsOneWidget);
|
||||||
|
final raw = tester.widget<TextField>(find.byType(TextField));
|
||||||
|
expect(raw.controller!.text, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('tapping Sync while unconfigured prompts to connect a backend', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpCapture(tester); // empty prefs → no token → not configured
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Sync'));
|
||||||
|
await tester.pump(); // settings load + snackbar
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// The behaviour that matters is the routing, not the wording: an
|
||||||
|
// unconfigured device is sent to settings to connect a backend. Asserting
|
||||||
|
// on the snackbar text tied this to one phrasing, and the snackbar is
|
||||||
|
// gone by the time settings has pushed anyway.
|
||||||
|
expect(find.textContaining('Connect Firebase'), findsWidgets);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the notes-list button navigates to the list screen', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpCapture(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Notes'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300)); // route transition
|
||||||
|
|
||||||
|
expect(find.text('Notes'), findsOneWidget); // list screen app bar title
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('changing the priority dropdown updates the saved note', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final repo = await pumpCapture(tester);
|
||||||
|
|
||||||
|
await tester.enterText(find.byType(TextField).first, 'Prioritised idea');
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
await tester.tap(
|
||||||
|
find.byWidgetPredicate((w) => w is DropdownButton<Priority>),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 400)); // menu open
|
||||||
|
await tester.tap(find.text('High').last);
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect((await repo.listNotes()).single.priority, Priority.high);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('changing the status dropdown updates the saved note', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final repo = await pumpCapture(tester);
|
||||||
|
|
||||||
|
await tester.enterText(find.byType(TextField).first, 'Status idea');
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
await tester.tap(
|
||||||
|
find.byWidgetPredicate((w) => w is DropdownButton<Status>),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 400)); // menu open
|
||||||
|
await tester.tap(find.text('In progress').last);
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect((await repo.listNotes()).single.status, Status.inProgress);
|
||||||
|
});
|
||||||
|
}
|
||||||
106
test/capture_screen_harness.dart
Normal file
106
test/capture_screen_harness.dart
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
/// The shared harness for the capture-screen test files.
|
||||||
|
///
|
||||||
|
/// `capture_screen_test.dart` was split by concern for the 250-line cap.
|
||||||
|
/// [pumpCapture] closes over the `WidgetTester`'s view and addTearDown, so it
|
||||||
|
/// takes the tester as a parameter rather than being a closure inside main().
|
||||||
|
///
|
||||||
|
/// Deliberately NOT named `*_test.dart`: the runner would collect it and fail
|
||||||
|
/// on the missing `main()`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
import 'package:todo/sync/local_backup.dart';
|
||||||
|
import 'package:todo/sync/notes_markdown.dart';
|
||||||
|
import 'package:todo/ui/capture_screen.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
|
import 'package:todo/ui/settings_screen.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
// A real CRDT DB schedules sqflite timers that never drain under the
|
||||||
|
// widget tester's fake clock, so these tests inject a timer-free fake.
|
||||||
|
// (NOTE: avoid pumpAndSettle — the autofocused field's cursor blink never
|
||||||
|
// settles; pump explicit frames instead.)
|
||||||
|
Future<FakeNoteRepository> pumpCapture(
|
||||||
|
WidgetTester tester, {
|
||||||
|
Map<String, Object> prefs = const {},
|
||||||
|
http.Client? httpClient,
|
||||||
|
List<Note> seed = const [],
|
||||||
|
FakeNoteRepository? repository,
|
||||||
|
LocalBackup? localBackup,
|
||||||
|
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
||||||
|
// Defaults to true: these tests exercise today's full UI (priority/status
|
||||||
|
// dropdowns, sync status text, Guided). Tests for the new default-off
|
||||||
|
// behavior pass advancedMode: false explicitly.
|
||||||
|
ValueNotifier<AppSettings>? appSettings,
|
||||||
|
AnalyticsService? analytics,
|
||||||
|
}) async {
|
||||||
|
SharedPreferences.setMockInitialValues(prefs);
|
||||||
|
installFakeSecureStorage();
|
||||||
|
// Tall surface so a pushed settings screen builds its whole ListView.
|
||||||
|
tester.view.physicalSize = const Size(1200, 2800);
|
||||||
|
tester.view.devicePixelRatio = 1.0;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
|
||||||
|
final repo = repository ?? FakeNoteRepository(seed);
|
||||||
|
addTearDown(repo.close);
|
||||||
|
// Default to an in-memory, no-op backup so tests never touch real disk
|
||||||
|
// (the production backup writes ~/todo/BACKLOG.md on the Linux test host).
|
||||||
|
final backup =
|
||||||
|
localBackup ??
|
||||||
|
LocalBackup(
|
||||||
|
fetch: repo.listNotes,
|
||||||
|
reader: () async => null,
|
||||||
|
writer: (_) async {},
|
||||||
|
debounce: Duration.zero,
|
||||||
|
);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: CaptureScreen(
|
||||||
|
repository: repo,
|
||||||
|
appSettings:
|
||||||
|
appSettings ?? ValueNotifier(const AppSettings(advancedMode: true)),
|
||||||
|
analytics: analytics,
|
||||||
|
httpClient: httpClient,
|
||||||
|
// Both injected so the widget never reaches for the platform: the
|
||||||
|
// real factories want the OS keystore and an application-support
|
||||||
|
// directory, neither of which exists under `flutter test`.
|
||||||
|
firebaseFactory: firebaseFactory ?? () async => null,
|
||||||
|
stateStore: InMemorySyncStateStore(),
|
||||||
|
localBackup: backup,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump(); // flush initial stream + settings load
|
||||||
|
return repo;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seeds a fully configured GitHub sync so the configured `_sync` path runs.
|
||||||
|
const configuredPrefs = {
|
||||||
|
'sync.owner': 'o',
|
||||||
|
'sync.repo': 'r',
|
||||||
|
'sync.token': 'tok',
|
||||||
|
};
|
||||||
|
|
||||||
|
// A MockClient that records request methods and answers the sync flow:
|
||||||
|
// repo-exists GET (not /contents/) → 200, the (empty) log listing → 404,
|
||||||
|
// and the device's own PUT → 200.
|
||||||
|
MockClient recordingMock(List<String> methods) => MockClient((req) async {
|
||||||
|
methods.add(req.method);
|
||||||
|
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||||
|
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
||||||
|
return http.Response('', 404);
|
||||||
|
});
|
||||||
171
test/capture_screen_lifecycle_test.dart
Normal file
171
test/capture_screen_lifecycle_test.dart
Normal file
@ -0,0 +1,171 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
import 'package:todo/sync/local_backup.dart';
|
||||||
|
import 'package:todo/sync/notes_markdown.dart';
|
||||||
|
import 'package:todo/ui/capture_screen.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
|
import 'package:todo/ui/settings_screen.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
import 'capture_screen_harness.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets(
|
||||||
|
'auto-sync success shows no status text — sync is automatic and silent',
|
||||||
|
(tester) async {
|
||||||
|
final methods = <String>[];
|
||||||
|
await pumpCapture(
|
||||||
|
tester,
|
||||||
|
prefs: configuredPrefs,
|
||||||
|
httpClient: recordingMock(methods),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// Only a failure is worth surfacing; a routine success is silent.
|
||||||
|
expect(find.textContaining('Synced at'), findsNothing);
|
||||||
|
expect(find.textContaining('merged 0 device(s)'), findsNothing);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('restores the last sync outcome on launch', (tester) async {
|
||||||
|
// Unconfigured (no token) so no launch auto-sync overwrites the restored
|
||||||
|
// status. A failure recorded on a previous run must still be visible.
|
||||||
|
await pumpCapture(
|
||||||
|
tester,
|
||||||
|
prefs: {
|
||||||
|
'sync.lastTime': DateTime(2026, 7, 16, 12).toIso8601String(),
|
||||||
|
'sync.lastOk': false,
|
||||||
|
'sync.lastDetail': 'Exception: rate limited',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.textContaining('Sync failed at 12:00:00'), findsOneWidget);
|
||||||
|
expect(find.textContaining('rate limited'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('losing focus triggers a debounced auto-sync', (tester) async {
|
||||||
|
final methods = <String>[];
|
||||||
|
await pumpCapture(
|
||||||
|
tester,
|
||||||
|
prefs: configuredPrefs,
|
||||||
|
httpClient: recordingMock(methods),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
methods.clear();
|
||||||
|
|
||||||
|
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
|
||||||
|
// A second signal (hidden also counts as focus loss) resets the debounce
|
||||||
|
// instead of double-firing.
|
||||||
|
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);
|
||||||
|
await tester.pump(
|
||||||
|
CaptureScreen.autoSyncDebounce - const Duration(seconds: 1),
|
||||||
|
);
|
||||||
|
expect(methods, isEmpty); // still inside the debounce window
|
||||||
|
|
||||||
|
await tester.pump(const Duration(seconds: 1));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// A sync ran. Not `contains('PUT')`: the first sync above already pushed
|
||||||
|
// this log, so revision tracking correctly suppresses the second, unchanged
|
||||||
|
// push -- that suppression is the point of the revision cache.
|
||||||
|
expect(methods, isNotEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('recovers notes from the local backup into an empty DB', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final markdown = NotesMarkdown.export([
|
||||||
|
Note(
|
||||||
|
id: 'r1',
|
||||||
|
text: '# Recovered idea',
|
||||||
|
priority: Priority.medium,
|
||||||
|
status: Status.todo,
|
||||||
|
createdAt: DateTime(2026, 6, 15),
|
||||||
|
updatedAt: DateTime(2026, 6, 15),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
final backup = LocalBackup(
|
||||||
|
fetch: () async => const <Note>[],
|
||||||
|
reader: () async => markdown,
|
||||||
|
writer: (_) async {},
|
||||||
|
debounce: Duration.zero,
|
||||||
|
);
|
||||||
|
|
||||||
|
final repo = await pumpCapture(tester, localBackup: backup);
|
||||||
|
await tester.pump(); // recover → import
|
||||||
|
|
||||||
|
final notes = await repo.listNotes();
|
||||||
|
expect(notes, hasLength(1));
|
||||||
|
expect(notes.single.text, contains('Recovered idea'));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('does not recover when the DB already has notes', (tester) async {
|
||||||
|
final backup = LocalBackup(
|
||||||
|
fetch: () async => const <Note>[],
|
||||||
|
reader: () async => NotesMarkdown.export([
|
||||||
|
Note(
|
||||||
|
id: 'r1',
|
||||||
|
text: '# From backup',
|
||||||
|
priority: Priority.medium,
|
||||||
|
status: Status.todo,
|
||||||
|
createdAt: DateTime(2026, 6, 15),
|
||||||
|
updatedAt: DateTime(2026, 6, 15),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
writer: (_) async {},
|
||||||
|
debounce: Duration.zero,
|
||||||
|
);
|
||||||
|
final seeded = Note(
|
||||||
|
id: 'local',
|
||||||
|
text: '# Existing',
|
||||||
|
priority: Priority.medium,
|
||||||
|
status: Status.todo,
|
||||||
|
createdAt: DateTime(2026, 6, 15),
|
||||||
|
updatedAt: DateTime(2026, 6, 15),
|
||||||
|
);
|
||||||
|
|
||||||
|
final repo = await pumpCapture(tester, seed: [seeded], localBackup: backup);
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// The backup is ignored because the DB was not empty.
|
||||||
|
final notes = await repo.listNotes();
|
||||||
|
expect(notes, hasLength(1));
|
||||||
|
expect(notes.single.id, 'local');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('writes the local backup as notes change', (tester) async {
|
||||||
|
final writes = <String>[];
|
||||||
|
final repo = FakeNoteRepository();
|
||||||
|
// fetch pulls from the repo on write, mirroring production wiring.
|
||||||
|
final backup = LocalBackup(
|
||||||
|
fetch: repo.listNotes,
|
||||||
|
reader: () async => null,
|
||||||
|
writer: (md) async => writes.add(md),
|
||||||
|
debounce: Duration.zero,
|
||||||
|
);
|
||||||
|
|
||||||
|
await pumpCapture(tester, repository: repo, localBackup: backup);
|
||||||
|
await tester.enterText(find.byType(TextField).first, 'Backed up idea');
|
||||||
|
await tester
|
||||||
|
.pump(); // let the change tick → schedule → async fetch/write run
|
||||||
|
|
||||||
|
expect(writes, isNotEmpty);
|
||||||
|
expect(writes.last, contains('Backed up idea'));
|
||||||
|
});
|
||||||
|
}
|
||||||
189
test/capture_screen_sync_test.dart
Normal file
189
test/capture_screen_sync_test.dart
Normal file
@ -0,0 +1,189 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
import 'package:todo/sync/local_backup.dart';
|
||||||
|
import 'package:todo/sync/notes_markdown.dart';
|
||||||
|
import 'package:todo/ui/capture_screen.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
|
import 'package:todo/ui/settings_screen.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
import 'capture_screen_harness.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('Sync with a configured token runs the sync service', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
// Empty remote directory → the service has nothing to merge and pushes
|
||||||
|
// this device's own log (PUT). The bare repo GET (not /contents/) returns
|
||||||
|
// 200 so crdt_sync's client treats the 404 dir as "empty", not missing.
|
||||||
|
final mock = MockClient((req) async {
|
||||||
|
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||||
|
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
||||||
|
return http.Response('', 404);
|
||||||
|
});
|
||||||
|
await pumpCapture(tester, prefs: configuredPrefs, httpClient: mock);
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Sync'));
|
||||||
|
await tester.pump(); // setState(_syncing = true)
|
||||||
|
await tester.pump(); // service runs, snackbar scheduled
|
||||||
|
await tester.pump(); // snackbar builds
|
||||||
|
|
||||||
|
// No firebaseFactory was injected, so this runs over GitHub alone --
|
||||||
|
// the status line must say so rather than reading identically to a
|
||||||
|
// Firebase-connected sync.
|
||||||
|
expect(
|
||||||
|
find.textContaining(
|
||||||
|
'Synced: GitHub-only (Firebase not connected) — merged 0 device',
|
||||||
|
),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Sync surfaces a failure from the sync service', (tester) async {
|
||||||
|
final mock = MockClient((_) async => throw Exception('offline'));
|
||||||
|
await pumpCapture(tester, prefs: configuredPrefs, httpClient: mock);
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Sync'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// 'Sync failed:' is the snackbar; the status line says 'Sync failed at'.
|
||||||
|
expect(find.textContaining('Sync failed:'), findsOneWidget);
|
||||||
|
expect(find.textContaining('Sync failed at'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('manual sync reports peer files it could not decode', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
// One peer file exists but holds garbage → merged 0, skipped 1.
|
||||||
|
final mock = MockClient((req) async {
|
||||||
|
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||||
|
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
||||||
|
if (req.url.path.endsWith('/todo-sync/notes')) {
|
||||||
|
return http.Response('[{"name": "bad.json"}]', 200);
|
||||||
|
}
|
||||||
|
if (req.url.path.endsWith('/bad.json')) {
|
||||||
|
return http.Response(
|
||||||
|
'{"content": "${base64Encode(utf8.encode('{not a log'))}"}',
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return http.Response('', 404); // own-file sha probe → create fresh
|
||||||
|
});
|
||||||
|
await pumpCapture(tester, prefs: configuredPrefs, httpClient: mock);
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Sync'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
find.textContaining('skipped 1 unreadable file(s)'),
|
||||||
|
findsWidgets, // snackbar and status line both call it out
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('returning from settings adopts the saved configuration', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpCapture(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Settings'));
|
||||||
|
await tester.pumpAndSettle(); // route transition
|
||||||
|
expect(find.byType(SettingsScreen), findsOneWidget); // settings is up
|
||||||
|
|
||||||
|
// GitHub sync settings (owner/repo/token) now live on the standalone
|
||||||
|
// GitHubMirrorScreen, reached via a link from SettingsScreen. The pop
|
||||||
|
// value itself is discarded by SettingsScreen; _openSettings always
|
||||||
|
// reloads from storage instead (a device-flow "Connect" saves the token
|
||||||
|
// without popping a result at all, so a stale in-memory value would be
|
||||||
|
// wrong there too). This exercises that reload-after-return path, then
|
||||||
|
// Back returns to capture.
|
||||||
|
await tester.tap(find.text('Advanced sync (GitHub)'));
|
||||||
|
await tester.pumpAndSettle(); // route transition
|
||||||
|
expect(find.byType(GitHubMirrorScreen), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Save'));
|
||||||
|
await tester.pumpAndSettle(); // save + pop transition back to Settings
|
||||||
|
expect(find.byType(SettingsScreen), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.pageBack();
|
||||||
|
await tester.pumpAndSettle(); // pop transition back to capture
|
||||||
|
|
||||||
|
expect(find.byType(SettingsScreen), findsNothing); // back on capture
|
||||||
|
expect(find.byTooltip('Settings'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
// A MockClient that records request methods and answers the sync flow:
|
||||||
|
// repo-exists GET (not /contents/) → 200, the (empty) log listing → 404,
|
||||||
|
// and the device's own PUT → 200.
|
||||||
|
MockClient recordingMock(List<String> methods) => MockClient((req) async {
|
||||||
|
methods.add(req.method);
|
||||||
|
if (req.method == 'PUT') return http.Response('{}', 200);
|
||||||
|
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
||||||
|
return http.Response('', 404);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'advancedMode off shows just the text field, no chrome or status text',
|
||||||
|
(tester) async {
|
||||||
|
await pumpCapture(
|
||||||
|
tester,
|
||||||
|
appSettings: ValueNotifier(const AppSettings(advancedMode: false)),
|
||||||
|
);
|
||||||
|
await tester.enterText(find.byType(TextField), 'A plain idea');
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// The editor's own template/mode chrome is gone.
|
||||||
|
expect(find.text('Guided'), findsNothing);
|
||||||
|
expect(find.text('Template'), findsNothing);
|
||||||
|
// The capture screen's priority/status row is gone.
|
||||||
|
expect(find.text('Priority'), findsNothing);
|
||||||
|
expect(find.text('Status'), findsNothing);
|
||||||
|
// Routine status chatter is gone; only a badge count remains.
|
||||||
|
expect(find.textContaining('Autosaves as you type'), findsNothing);
|
||||||
|
expect(find.text('1'), findsOneWidget);
|
||||||
|
// The note still persisted normally underneath the simplified UI.
|
||||||
|
expect(find.text('A plain idea'), findsOneWidget);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'draft text survives an advancedMode toggle mid-typing',
|
||||||
|
(tester) async {
|
||||||
|
final appSettings = ValueNotifier(
|
||||||
|
const AppSettings(advancedMode: true),
|
||||||
|
);
|
||||||
|
await pumpCapture(tester, appSettings: appSettings);
|
||||||
|
|
||||||
|
await tester.enterText(
|
||||||
|
find.byType(TextField).first,
|
||||||
|
'my important idea',
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// The Row above the editor is conditionally present, which shifts the
|
||||||
|
// editor's position in the Column whenever advancedMode changes at
|
||||||
|
// runtime — a key one level too shallow doesn't survive that
|
||||||
|
// reposition and Flutter remounts the editor with an empty draft.
|
||||||
|
appSettings.value = const AppSettings(advancedMode: false);
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
final field = tester.widget<TextField>(find.byType(TextField).first);
|
||||||
|
expect(field.controller?.text, contains('my important idea'));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,660 +0,0 @@
|
|||||||
import 'dart:convert';
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
import 'package:http/testing.dart';
|
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
|
||||||
import 'package:todo/analytics/analytics_service.dart';
|
|
||||||
import 'package:todo/data/app_settings.dart';
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
import 'package:todo/data/note_template.dart';
|
|
||||||
import 'package:todo/sync/local_backup.dart';
|
|
||||||
import 'package:todo/sync/notes_markdown.dart';
|
|
||||||
import 'package:todo/ui/capture_screen.dart';
|
|
||||||
import 'package:todo/ui/github_mirror_screen.dart';
|
|
||||||
import 'package:todo/ui/settings_screen.dart';
|
|
||||||
|
|
||||||
import 'fake_note_repository.dart';
|
|
||||||
import 'fake_secure_storage.dart';
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
// A real CRDT DB schedules sqflite timers that never drain under the
|
|
||||||
// widget tester's fake clock, so these tests inject a timer-free fake.
|
|
||||||
// (NOTE: avoid pumpAndSettle — the autofocused field's cursor blink never
|
|
||||||
// settles; pump explicit frames instead.)
|
|
||||||
Future<FakeNoteRepository> pumpCapture(
|
|
||||||
WidgetTester tester, {
|
|
||||||
Map<String, Object> prefs = const {},
|
|
||||||
http.Client? httpClient,
|
|
||||||
List<Note> seed = const [],
|
|
||||||
FakeNoteRepository? repository,
|
|
||||||
LocalBackup? localBackup,
|
|
||||||
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
|
||||||
// Defaults to true: these tests exercise today's full UI (priority/status
|
|
||||||
// dropdowns, sync status text, Guided). Tests for the new default-off
|
|
||||||
// behavior pass advancedMode: false explicitly.
|
|
||||||
ValueNotifier<AppSettings>? appSettings,
|
|
||||||
AnalyticsService? analytics,
|
|
||||||
}) async {
|
|
||||||
SharedPreferences.setMockInitialValues(prefs);
|
|
||||||
installFakeSecureStorage();
|
|
||||||
// Tall surface so a pushed settings screen builds its whole ListView.
|
|
||||||
tester.view.physicalSize = const Size(1200, 2800);
|
|
||||||
tester.view.devicePixelRatio = 1.0;
|
|
||||||
addTearDown(tester.view.resetPhysicalSize);
|
|
||||||
addTearDown(tester.view.resetDevicePixelRatio);
|
|
||||||
|
|
||||||
final repo = repository ?? FakeNoteRepository(seed);
|
|
||||||
addTearDown(repo.close);
|
|
||||||
// Default to an in-memory, no-op backup so tests never touch real disk
|
|
||||||
// (the production backup writes ~/todo/BACKLOG.md on the Linux test host).
|
|
||||||
final backup =
|
|
||||||
localBackup ??
|
|
||||||
LocalBackup(
|
|
||||||
fetch: repo.listNotes,
|
|
||||||
reader: () async => null,
|
|
||||||
writer: (_) async {},
|
|
||||||
debounce: Duration.zero,
|
|
||||||
);
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(
|
|
||||||
home: CaptureScreen(
|
|
||||||
repository: repo,
|
|
||||||
appSettings:
|
|
||||||
appSettings ??
|
|
||||||
ValueNotifier(const AppSettings(advancedMode: true)),
|
|
||||||
analytics: analytics,
|
|
||||||
httpClient: httpClient,
|
|
||||||
// Both injected so the widget never reaches for the platform: the
|
|
||||||
// real factories want the OS keystore and an application-support
|
|
||||||
// directory, neither of which exists under `flutter test`.
|
|
||||||
firebaseFactory: firebaseFactory ?? () async => null,
|
|
||||||
stateStore: InMemorySyncStateStore(),
|
|
||||||
localBackup: backup,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pump(); // flush initial stream + settings load
|
|
||||||
return repo;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Seeds a fully configured GitHub sync so the configured `_sync` path runs.
|
|
||||||
const configuredPrefs = {
|
|
||||||
'sync.owner': 'o',
|
|
||||||
'sync.repo': 'r',
|
|
||||||
'sync.token': 'tok',
|
|
||||||
};
|
|
||||||
|
|
||||||
testWidgets('defaults to Raw, with Guided available via the entry wizard', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpCapture(tester);
|
|
||||||
|
|
||||||
// Defaults to Raw: a single text field, no note persisted yet.
|
|
||||||
expect(find.byType(TextField), findsOneWidget);
|
|
||||||
expect(find.text('Guided'), findsOneWidget);
|
|
||||||
expect(find.text('0'), findsOneWidget);
|
|
||||||
|
|
||||||
// Tapping Guided on the empty draft opens the priority+template wizard
|
|
||||||
// rather than jumping straight into the stepper.
|
|
||||||
await tester.tap(find.text('Guided'));
|
|
||||||
await tester.pump();
|
|
||||||
expect(find.text('Step 1 of 2'), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Next'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.tap(find.text('Start'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// Now on step 1 of the full-screen step page.
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
|
||||||
expect(
|
|
||||||
find.text('1 / ${NoteTemplate.llmDesignSpec.sections.length}'),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
expect(find.textContaining('imperative'), findsOneWidget); // title helper
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('saving the untouched template creates no note', (tester) async {
|
|
||||||
final repo = await pumpCapture(tester);
|
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('New note'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(await repo.listNotes(), isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('typing into the template persists a note with defaults', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final repo = await pumpCapture(tester);
|
|
||||||
|
|
||||||
// The first field in the guided stepper is the title section.
|
|
||||||
await tester.enterText(find.byType(TextField).first, 'My idea');
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
final notes = await repo.listNotes();
|
|
||||||
expect(notes, hasLength(1));
|
|
||||||
expect(notes.single.text, contains('My idea'));
|
|
||||||
expect(notes.single.priority, Priority.medium);
|
|
||||||
expect(notes.single.status, Status.todo);
|
|
||||||
expect(find.text('1'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('the new-note action resets the template', (tester) async {
|
|
||||||
final repo = await pumpCapture(tester);
|
|
||||||
|
|
||||||
await tester.enterText(find.byType(TextField).first, 'A real idea');
|
|
||||||
await tester.pump();
|
|
||||||
await tester.tap(find.byTooltip('New note'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(await repo.listNotes(), hasLength(1));
|
|
||||||
// The editor reset to a fresh, empty Raw draft.
|
|
||||||
expect(find.byType(TextField), findsOneWidget);
|
|
||||||
final raw = tester.widget<TextField>(find.byType(TextField));
|
|
||||||
expect(raw.controller!.text, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('tapping Sync while unconfigured prompts to connect a backend', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpCapture(tester); // empty prefs → no token → not configured
|
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('Sync'));
|
|
||||||
await tester.pump(); // settings load + snackbar
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// The behaviour that matters is the routing, not the wording: an
|
|
||||||
// unconfigured device is sent to settings to connect a backend. Asserting
|
|
||||||
// on the snackbar text tied this to one phrasing, and the snackbar is
|
|
||||||
// gone by the time settings has pushed anyway.
|
|
||||||
expect(find.textContaining('Connect Firebase'), findsWidgets);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('the notes-list button navigates to the list screen', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpCapture(tester);
|
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('Notes'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300)); // route transition
|
|
||||||
|
|
||||||
expect(find.text('Notes'), findsOneWidget); // list screen app bar title
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('changing the priority dropdown updates the saved note', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final repo = await pumpCapture(tester);
|
|
||||||
|
|
||||||
await tester.enterText(find.byType(TextField).first, 'Prioritised idea');
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
await tester.tap(
|
|
||||||
find.byWidgetPredicate((w) => w is DropdownButton<Priority>),
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 400)); // menu open
|
|
||||||
await tester.tap(find.text('High').last);
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect((await repo.listNotes()).single.priority, Priority.high);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('changing the status dropdown updates the saved note', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final repo = await pumpCapture(tester);
|
|
||||||
|
|
||||||
await tester.enterText(find.byType(TextField).first, 'Status idea');
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
await tester.tap(
|
|
||||||
find.byWidgetPredicate((w) => w is DropdownButton<Status>),
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 400)); // menu open
|
|
||||||
await tester.tap(find.text('In progress').last);
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect((await repo.listNotes()).single.status, Status.inProgress);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Sync with a configured token runs the sync service', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// Empty remote directory → the service has nothing to merge and pushes
|
|
||||||
// this device's own log (PUT). The bare repo GET (not /contents/) returns
|
|
||||||
// 200 so crdt_sync's client treats the 404 dir as "empty", not missing.
|
|
||||||
final mock = MockClient((req) async {
|
|
||||||
if (req.method == 'PUT') return http.Response('{}', 200);
|
|
||||||
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
|
||||||
return http.Response('', 404);
|
|
||||||
});
|
|
||||||
await pumpCapture(tester, prefs: configuredPrefs, httpClient: mock);
|
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('Sync'));
|
|
||||||
await tester.pump(); // setState(_syncing = true)
|
|
||||||
await tester.pump(); // service runs, snackbar scheduled
|
|
||||||
await tester.pump(); // snackbar builds
|
|
||||||
|
|
||||||
// No firebaseFactory was injected, so this runs over GitHub alone --
|
|
||||||
// the status line must say so rather than reading identically to a
|
|
||||||
// Firebase-connected sync.
|
|
||||||
expect(
|
|
||||||
find.textContaining(
|
|
||||||
'Synced: GitHub-only (Firebase not connected) — merged 0 device',
|
|
||||||
),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Sync surfaces a failure from the sync service', (tester) async {
|
|
||||||
final mock = MockClient((_) async => throw Exception('offline'));
|
|
||||||
await pumpCapture(tester, prefs: configuredPrefs, httpClient: mock);
|
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('Sync'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// 'Sync failed:' is the snackbar; the status line says 'Sync failed at'.
|
|
||||||
expect(find.textContaining('Sync failed:'), findsOneWidget);
|
|
||||||
expect(find.textContaining('Sync failed at'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('manual sync reports peer files it could not decode', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// One peer file exists but holds garbage → merged 0, skipped 1.
|
|
||||||
final mock = MockClient((req) async {
|
|
||||||
if (req.method == 'PUT') return http.Response('{}', 200);
|
|
||||||
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
|
||||||
if (req.url.path.endsWith('/todo-sync/notes')) {
|
|
||||||
return http.Response('[{"name": "bad.json"}]', 200);
|
|
||||||
}
|
|
||||||
if (req.url.path.endsWith('/bad.json')) {
|
|
||||||
return http.Response(
|
|
||||||
'{"content": "${base64Encode(utf8.encode('{not a log'))}"}',
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return http.Response('', 404); // own-file sha probe → create fresh
|
|
||||||
});
|
|
||||||
await pumpCapture(tester, prefs: configuredPrefs, httpClient: mock);
|
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('Sync'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(
|
|
||||||
find.textContaining('skipped 1 unreadable file(s)'),
|
|
||||||
findsWidgets, // snackbar and status line both call it out
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('returning from settings adopts the saved configuration', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpCapture(tester);
|
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('Settings'));
|
|
||||||
await tester.pumpAndSettle(); // route transition
|
|
||||||
expect(find.byType(SettingsScreen), findsOneWidget); // settings is up
|
|
||||||
|
|
||||||
// GitHub sync settings (owner/repo/token) now live on the standalone
|
|
||||||
// GitHubMirrorScreen, reached via a link from SettingsScreen. The pop
|
|
||||||
// value itself is discarded by SettingsScreen; _openSettings always
|
|
||||||
// reloads from storage instead (a device-flow "Connect" saves the token
|
|
||||||
// without popping a result at all, so a stale in-memory value would be
|
|
||||||
// wrong there too). This exercises that reload-after-return path, then
|
|
||||||
// Back returns to capture.
|
|
||||||
await tester.tap(find.text('Advanced sync (GitHub)'));
|
|
||||||
await tester.pumpAndSettle(); // route transition
|
|
||||||
expect(find.byType(GitHubMirrorScreen), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Save'));
|
|
||||||
await tester.pumpAndSettle(); // save + pop transition back to Settings
|
|
||||||
expect(find.byType(SettingsScreen), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.pageBack();
|
|
||||||
await tester.pumpAndSettle(); // pop transition back to capture
|
|
||||||
|
|
||||||
expect(find.byType(SettingsScreen), findsNothing); // back on capture
|
|
||||||
expect(find.byTooltip('Settings'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
// A MockClient that records request methods and answers the sync flow:
|
|
||||||
// repo-exists GET (not /contents/) → 200, the (empty) log listing → 404,
|
|
||||||
// and the device's own PUT → 200.
|
|
||||||
MockClient recordingMock(List<String> methods) => MockClient((req) async {
|
|
||||||
methods.add(req.method);
|
|
||||||
if (req.method == 'PUT') return http.Response('{}', 200);
|
|
||||||
if (!req.url.path.contains('/contents/')) return http.Response('{}', 200);
|
|
||||||
return http.Response('', 404);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets(
|
|
||||||
'advancedMode off shows just the text field, no chrome or status text',
|
|
||||||
(tester) async {
|
|
||||||
await pumpCapture(
|
|
||||||
tester,
|
|
||||||
appSettings: ValueNotifier(const AppSettings(advancedMode: false)),
|
|
||||||
);
|
|
||||||
await tester.enterText(find.byType(TextField), 'A plain idea');
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// The editor's own template/mode chrome is gone.
|
|
||||||
expect(find.text('Guided'), findsNothing);
|
|
||||||
expect(find.text('Template'), findsNothing);
|
|
||||||
// The capture screen's priority/status row is gone.
|
|
||||||
expect(find.text('Priority'), findsNothing);
|
|
||||||
expect(find.text('Status'), findsNothing);
|
|
||||||
// Routine status chatter is gone; only a badge count remains.
|
|
||||||
expect(find.textContaining('Autosaves as you type'), findsNothing);
|
|
||||||
expect(find.text('1'), findsOneWidget);
|
|
||||||
// The note still persisted normally underneath the simplified UI.
|
|
||||||
expect(find.text('A plain idea'), findsOneWidget);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
testWidgets(
|
|
||||||
'draft text survives an advancedMode toggle mid-typing',
|
|
||||||
(tester) async {
|
|
||||||
final appSettings = ValueNotifier(
|
|
||||||
const AppSettings(advancedMode: true),
|
|
||||||
);
|
|
||||||
await pumpCapture(tester, appSettings: appSettings);
|
|
||||||
|
|
||||||
await tester.enterText(
|
|
||||||
find.byType(TextField).first,
|
|
||||||
'my important idea',
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// The Row above the editor is conditionally present, which shifts the
|
|
||||||
// editor's position in the Column whenever advancedMode changes at
|
|
||||||
// runtime — a key one level too shallow doesn't survive that
|
|
||||||
// reposition and Flutter remounts the editor with an empty draft.
|
|
||||||
appSettings.value = const AppSettings(advancedMode: false);
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
final field = tester.widget<TextField>(find.byType(TextField).first);
|
|
||||||
expect(field.controller?.text, contains('my important idea'));
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
testWidgets(
|
|
||||||
'auto-sync adopts a newer advancedMode value from Firebase',
|
|
||||||
(tester) async {
|
|
||||||
final remoteTime = DateTime(2026, 6);
|
|
||||||
final firebase = FirebaseRestClient(
|
|
||||||
databaseUrl: 'https://x-rtdb.europe-west1.firebasedatabase.app',
|
|
||||||
auth: FirebaseTokenProvider(
|
|
||||||
apiKey: 'AIzaKey',
|
|
||||||
store: InMemoryCredentialStore(
|
|
||||||
FirebaseCredentials(
|
|
||||||
idToken: 'id',
|
|
||||||
refreshToken: 'refresh',
|
|
||||||
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
httpClient: MockClient((request) async {
|
|
||||||
if (request.url.path == '/settings/advancedMode.json') {
|
|
||||||
return http.Response(
|
|
||||||
'{"value": "true", '
|
|
||||||
'"updatedAtMillis": "${remoteTime.millisecondsSinceEpoch}"}',
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (request.method == 'PUT') return http.Response(request.body, 200);
|
|
||||||
return http.Response('null', 200);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
final appSettings = ValueNotifier(
|
|
||||||
AppSettings(
|
|
||||||
advancedMode: false,
|
|
||||||
// Older than remoteTime, and non-null, so the reconciliation
|
|
||||||
// guard's `currentAt != null && !reconciledAt.isAfter(currentAt)`
|
|
||||||
// check actually evaluates both operands.
|
|
||||||
advancedModeUpdatedAt: remoteTime.subtract(
|
|
||||||
const Duration(days: 1),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
await pumpCapture(
|
|
||||||
tester,
|
|
||||||
prefs: configuredPrefs,
|
|
||||||
firebaseFactory: () async => firebase,
|
|
||||||
appSettings: appSettings,
|
|
||||||
);
|
|
||||||
await tester.pump(); // settings load → auto-sync (pull) …
|
|
||||||
await tester.pump(); // … then push, then reconcile
|
|
||||||
|
|
||||||
expect(appSettings.value.advancedMode, isTrue);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
testWidgets('logs app_open when analytics is injected', (tester) async {
|
|
||||||
const analytics = AnalyticsService(nodeId: 'device-a');
|
|
||||||
await pumpCapture(tester, analytics: analytics);
|
|
||||||
await tester.pump(); // flush the unawaited logEvent's prefs write
|
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
|
||||||
final buffer = prefs.getString('analytics.buffer');
|
|
||||||
expect(buffer, isNotNull);
|
|
||||||
expect(buffer, contains('app_open'));
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('auto-syncs on launch when configured', (tester) async {
|
|
||||||
final methods = <String>[];
|
|
||||||
await pumpCapture(
|
|
||||||
tester,
|
|
||||||
prefs: configuredPrefs,
|
|
||||||
httpClient: recordingMock(methods),
|
|
||||||
);
|
|
||||||
await tester.pump(); // settings load → auto-sync (pull) …
|
|
||||||
await tester.pump(); // … then push
|
|
||||||
|
|
||||||
expect(methods, contains('PUT')); // this device pushed its changeset
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('does not auto-sync when unconfigured', (tester) async {
|
|
||||||
final methods = <String>[];
|
|
||||||
await pumpCapture(tester, httpClient: recordingMock(methods)); // no token
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(methods, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('auto-syncs again when the app is backgrounded', (tester) async {
|
|
||||||
final methods = <String>[];
|
|
||||||
await pumpCapture(
|
|
||||||
tester,
|
|
||||||
prefs: configuredPrefs,
|
|
||||||
httpClient: recordingMock(methods),
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
methods.clear();
|
|
||||||
|
|
||||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// A sync ran. Not `contains('PUT')`: the launch sync above already pushed
|
|
||||||
// this log, so revision tracking correctly suppresses the second, unchanged
|
|
||||||
// push -- that suppression is the point of the revision cache.
|
|
||||||
expect(methods, isNotEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('auto-sync failure shows no snackbar but flags the status line', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final mock = MockClient((_) async => throw Exception('offline'));
|
|
||||||
await pumpCapture(tester, prefs: configuredPrefs, httpClient: mock);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// Capture must never be interrupted by a snackbar…
|
|
||||||
expect(find.byType(SnackBar), findsNothing);
|
|
||||||
// …but the failure is no longer swallowed: the status line shows it.
|
|
||||||
expect(find.textContaining('Sync failed at'), findsOneWidget);
|
|
||||||
expect(find.textContaining('offline'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets(
|
|
||||||
'auto-sync success shows no status text — sync is automatic and silent',
|
|
||||||
(tester) async {
|
|
||||||
final methods = <String>[];
|
|
||||||
await pumpCapture(
|
|
||||||
tester,
|
|
||||||
prefs: configuredPrefs,
|
|
||||||
httpClient: recordingMock(methods),
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// Only a failure is worth surfacing; a routine success is silent.
|
|
||||||
expect(find.textContaining('Synced at'), findsNothing);
|
|
||||||
expect(find.textContaining('merged 0 device(s)'), findsNothing);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
testWidgets('restores the last sync outcome on launch', (tester) async {
|
|
||||||
// Unconfigured (no token) so no launch auto-sync overwrites the restored
|
|
||||||
// status. A failure recorded on a previous run must still be visible.
|
|
||||||
await pumpCapture(
|
|
||||||
tester,
|
|
||||||
prefs: {
|
|
||||||
'sync.lastTime': DateTime(2026, 7, 16, 12).toIso8601String(),
|
|
||||||
'sync.lastOk': false,
|
|
||||||
'sync.lastDetail': 'Exception: rate limited',
|
|
||||||
},
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.textContaining('Sync failed at 12:00:00'), findsOneWidget);
|
|
||||||
expect(find.textContaining('rate limited'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('losing focus triggers a debounced auto-sync', (tester) async {
|
|
||||||
final methods = <String>[];
|
|
||||||
await pumpCapture(
|
|
||||||
tester,
|
|
||||||
prefs: configuredPrefs,
|
|
||||||
httpClient: recordingMock(methods),
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
methods.clear();
|
|
||||||
|
|
||||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
|
|
||||||
// A second signal (hidden also counts as focus loss) resets the debounce
|
|
||||||
// instead of double-firing.
|
|
||||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);
|
|
||||||
await tester.pump(
|
|
||||||
CaptureScreen.autoSyncDebounce - const Duration(seconds: 1),
|
|
||||||
);
|
|
||||||
expect(methods, isEmpty); // still inside the debounce window
|
|
||||||
|
|
||||||
await tester.pump(const Duration(seconds: 1));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// A sync ran. Not `contains('PUT')`: the first sync above already pushed
|
|
||||||
// this log, so revision tracking correctly suppresses the second, unchanged
|
|
||||||
// push -- that suppression is the point of the revision cache.
|
|
||||||
expect(methods, isNotEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('recovers notes from the local backup into an empty DB', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final markdown = NotesMarkdown.export([
|
|
||||||
Note(
|
|
||||||
id: 'r1',
|
|
||||||
text: '# Recovered idea',
|
|
||||||
priority: Priority.medium,
|
|
||||||
status: Status.todo,
|
|
||||||
createdAt: DateTime(2026, 6, 15),
|
|
||||||
updatedAt: DateTime(2026, 6, 15),
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
final backup = LocalBackup(
|
|
||||||
fetch: () async => const <Note>[],
|
|
||||||
reader: () async => markdown,
|
|
||||||
writer: (_) async {},
|
|
||||||
debounce: Duration.zero,
|
|
||||||
);
|
|
||||||
|
|
||||||
final repo = await pumpCapture(tester, localBackup: backup);
|
|
||||||
await tester.pump(); // recover → import
|
|
||||||
|
|
||||||
final notes = await repo.listNotes();
|
|
||||||
expect(notes, hasLength(1));
|
|
||||||
expect(notes.single.text, contains('Recovered idea'));
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('does not recover when the DB already has notes', (tester) async {
|
|
||||||
final backup = LocalBackup(
|
|
||||||
fetch: () async => const <Note>[],
|
|
||||||
reader: () async => NotesMarkdown.export([
|
|
||||||
Note(
|
|
||||||
id: 'r1',
|
|
||||||
text: '# From backup',
|
|
||||||
priority: Priority.medium,
|
|
||||||
status: Status.todo,
|
|
||||||
createdAt: DateTime(2026, 6, 15),
|
|
||||||
updatedAt: DateTime(2026, 6, 15),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
writer: (_) async {},
|
|
||||||
debounce: Duration.zero,
|
|
||||||
);
|
|
||||||
final seeded = Note(
|
|
||||||
id: 'local',
|
|
||||||
text: '# Existing',
|
|
||||||
priority: Priority.medium,
|
|
||||||
status: Status.todo,
|
|
||||||
createdAt: DateTime(2026, 6, 15),
|
|
||||||
updatedAt: DateTime(2026, 6, 15),
|
|
||||||
);
|
|
||||||
|
|
||||||
final repo = await pumpCapture(tester, seed: [seeded], localBackup: backup);
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// The backup is ignored because the DB was not empty.
|
|
||||||
final notes = await repo.listNotes();
|
|
||||||
expect(notes, hasLength(1));
|
|
||||||
expect(notes.single.id, 'local');
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('writes the local backup as notes change', (tester) async {
|
|
||||||
final writes = <String>[];
|
|
||||||
final repo = FakeNoteRepository();
|
|
||||||
// fetch pulls from the repo on write, mirroring production wiring.
|
|
||||||
final backup = LocalBackup(
|
|
||||||
fetch: repo.listNotes,
|
|
||||||
reader: () async => null,
|
|
||||||
writer: (md) async => writes.add(md),
|
|
||||||
debounce: Duration.zero,
|
|
||||||
);
|
|
||||||
|
|
||||||
await pumpCapture(tester, repository: repo, localBackup: backup);
|
|
||||||
await tester.enterText(find.byType(TextField).first, 'Backed up idea');
|
|
||||||
await tester
|
|
||||||
.pump(); // let the change tick → schedule → async fetch/write run
|
|
||||||
|
|
||||||
expect(writes, isNotEmpty);
|
|
||||||
expect(writes.last, contains('Backed up idea'));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
219
test/github_mirror_device_flow_test.dart
Normal file
219
test/github_mirror_device_flow_test.dart
Normal file
@ -0,0 +1,219 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
|
import 'package:url_launcher_platform_interface/link.dart';
|
||||||
|
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
import 'github_mirror_harness.dart';
|
||||||
|
|
||||||
|
/// Stub launcher that records the URL instead of opening it, so `_openPage`
|
||||||
|
/// can be exercised without a real platform channel.
|
||||||
|
class _FakeUrlLauncher extends UrlLauncherPlatform
|
||||||
|
with MockPlatformInterfaceMixin {
|
||||||
|
String? launched;
|
||||||
|
|
||||||
|
@override
|
||||||
|
final LinkDelegate? linkDelegate = null;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> supportsMode(PreferredLaunchMode mode) async => true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> launchUrl(String url, LaunchOptions options) async {
|
||||||
|
launched = url;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('device flow connects but surfaces a post-connect sync failure', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final mock = MockClient((req) async {
|
||||||
|
if (req.url.path.contains('device/code')) {
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({
|
||||||
|
'device_code': 'dev123',
|
||||||
|
'user_code': 'WXYZ-1234',
|
||||||
|
'verification_uri': 'https://github.com/login/device',
|
||||||
|
'interval': 0,
|
||||||
|
'expires_in': 900,
|
||||||
|
}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (req.url.path.contains('login/oauth/access_token')) {
|
||||||
|
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
||||||
|
}
|
||||||
|
return http.Response('boom', 500); // the sync's repo calls fail
|
||||||
|
});
|
||||||
|
|
||||||
|
await pumpMirror(
|
||||||
|
tester,
|
||||||
|
initial: const SyncSettings(
|
||||||
|
owner: 'o',
|
||||||
|
repo: 'r',
|
||||||
|
token: '',
|
||||||
|
clientId: 'cid',
|
||||||
|
),
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Connect GitHub'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 50));
|
||||||
|
for (var i = 0; i < 6; i++) {
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(find.textContaining('sync failed'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Save persists the settings and closes the screen', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
installFakeSecureStorage();
|
||||||
|
tester.view.physicalSize = const Size(1200, 2800);
|
||||||
|
tester.view.devicePixelRatio = 1.0;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
|
||||||
|
final repo = FakeNoteRepository();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
|
||||||
|
// Push GitHubMirrorScreen over a base route so _save's Navigator.pop has
|
||||||
|
// somewhere to return to (popping the root route is a no-op and hides
|
||||||
|
// the result).
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Builder(
|
||||||
|
builder: (context) => Scaffold(
|
||||||
|
body: Center(
|
||||||
|
child: ElevatedButton(
|
||||||
|
onPressed: () => Navigator.of(context).push(
|
||||||
|
MaterialPageRoute<SyncSettings>(
|
||||||
|
builder: (_) => GitHubMirrorScreen(
|
||||||
|
initial: const SyncSettings(
|
||||||
|
owner: 'o',
|
||||||
|
repo: 'r',
|
||||||
|
token: 'tok',
|
||||||
|
),
|
||||||
|
repository: repo,
|
||||||
|
appSettings: ValueNotifier(
|
||||||
|
const AppSettings(advancedMode: false),
|
||||||
|
),
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
stateStore: InMemorySyncStateStore(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: const Text('open'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('open'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 400)); // route transition
|
||||||
|
expect(find.byType(GitHubMirrorScreen), findsOneWidget); // screen is up
|
||||||
|
|
||||||
|
await tester.tap(find.text('Save'));
|
||||||
|
await tester.pump(); // run _save (persist + pop)
|
||||||
|
await tester.pump(const Duration(milliseconds: 400)); // pop transition
|
||||||
|
|
||||||
|
expect(find.text('open'), findsOneWidget); // back on the base route
|
||||||
|
final saved = await SyncSettings.load();
|
||||||
|
expect(saved.owner, 'o');
|
||||||
|
expect(saved.token, 'tok');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('device dialog: failed poll shows the error and Open launches', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final launcher = _FakeUrlLauncher();
|
||||||
|
UrlLauncherPlatform.instance = launcher;
|
||||||
|
|
||||||
|
// _openPage copies the code to the clipboard first; there's no
|
||||||
|
// clipboard plugin in the test host, so stub the channel to succeed.
|
||||||
|
final messenger =
|
||||||
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||||
|
messenger.setMockMethodCallHandler(
|
||||||
|
SystemChannels.platform,
|
||||||
|
(call) async => null,
|
||||||
|
);
|
||||||
|
addTearDown(
|
||||||
|
() => messenger.setMockMethodCallHandler(SystemChannels.platform, null),
|
||||||
|
);
|
||||||
|
|
||||||
|
final mock = MockClient((req) async {
|
||||||
|
if (req.url.path.contains('device/code')) {
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({
|
||||||
|
'device_code': 'dev123',
|
||||||
|
'user_code': 'WXYZ-1234',
|
||||||
|
'verification_uri': 'https://github.com/login/device',
|
||||||
|
'interval': 0,
|
||||||
|
'expires_in': 900,
|
||||||
|
}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Token endpoint: a terminal error ends the poll loop cleanly (no
|
||||||
|
// lingering timer to trip the tester's pending-timer guard).
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({'error': 'access_denied', 'error_description': 'nope'}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
await pumpMirror(
|
||||||
|
tester,
|
||||||
|
initial: const SyncSettings(
|
||||||
|
owner: 'o',
|
||||||
|
repo: 'r',
|
||||||
|
token: '',
|
||||||
|
clientId: 'cid',
|
||||||
|
),
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Connect GitHub'));
|
||||||
|
await tester.pump(); // requestDeviceCode
|
||||||
|
await tester.pump(); // dialog builds, poll starts (interval 0)
|
||||||
|
expect(find.text('WXYZ-1234'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.pump(const Duration(milliseconds: 1)); // _delay(0) fires
|
||||||
|
await tester.pump(); // token error throws → _error set
|
||||||
|
expect(find.textContaining('nope'), findsOneWidget); // error rendered
|
||||||
|
|
||||||
|
// Tap the "open on GitHub" action: copies the code and launches the URL.
|
||||||
|
// _openPage awaits Clipboard.setData then the launcher's supportsMode +
|
||||||
|
// launchUrl; pumpAndSettle drains them (no spinner is animating now
|
||||||
|
// that the error is shown, so it settles).
|
||||||
|
await tester.tap(find.byIcon(Icons.open_in_new));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(launcher.launched, 'https://github.com/login/device');
|
||||||
|
|
||||||
|
await tester.tap(find.text('Cancel'));
|
||||||
|
await tester.pumpAndSettle(); // finish the dialog pop animation
|
||||||
|
expect(find.text('WXYZ-1234'), findsNothing); // dialog dismissed
|
||||||
|
});
|
||||||
|
}
|
||||||
83
test/github_mirror_harness.dart
Normal file
83
test/github_mirror_harness.dart
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
/// The pumpMirror harness and the fake url_launcher.
|
||||||
|
///
|
||||||
|
/// Shared by the files `github_mirror_screen_test.dart` was split into for the
|
||||||
|
/// 250-line cap. Deliberately NOT named `*_test.dart`: the runner would
|
||||||
|
/// collect it and fail on the missing `main()`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
|
import 'package:url_launcher_platform_interface/link.dart';
|
||||||
|
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
/// Stub launcher that records the URL instead of opening it, so `_openPage`
|
||||||
|
/// can be exercised without a real platform channel.
|
||||||
|
class _FakeUrlLauncher extends UrlLauncherPlatform
|
||||||
|
with MockPlatformInterfaceMixin {
|
||||||
|
String? launched;
|
||||||
|
|
||||||
|
@override
|
||||||
|
final LinkDelegate? linkDelegate = null;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> supportsMode(PreferredLaunchMode mode) async => true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> launchUrl(String url, LaunchOptions options) async {
|
||||||
|
launched = url;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<FakeNoteRepository> pumpMirror(
|
||||||
|
WidgetTester tester, {
|
||||||
|
SyncSettings initial = const SyncSettings(
|
||||||
|
owner: 'kuhyx',
|
||||||
|
repo: 'syncs',
|
||||||
|
token: 't',
|
||||||
|
),
|
||||||
|
http.Client? httpClient,
|
||||||
|
FakeNoteRepository? repository,
|
||||||
|
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
||||||
|
ValueNotifier<AppSettings>? appSettings,
|
||||||
|
}) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
installFakeSecureStorage();
|
||||||
|
tester.view.physicalSize = const Size(1200, 2800);
|
||||||
|
tester.view.devicePixelRatio = 1.0;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
|
||||||
|
final repo = repository ?? FakeNoteRepository();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: GitHubMirrorScreen(
|
||||||
|
initial: initial,
|
||||||
|
repository: repo,
|
||||||
|
appSettings:
|
||||||
|
appSettings ??
|
||||||
|
ValueNotifier(const AppSettings(advancedMode: false)),
|
||||||
|
httpClient: httpClient,
|
||||||
|
firebaseFactory: firebaseFactory ?? () async => null,
|
||||||
|
stateStore: InMemorySyncStateStore(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
return repo;
|
||||||
|
}
|
||||||
@ -17,6 +17,8 @@ import 'package:url_launcher_platform_interface/url_launcher_platform_interface.
|
|||||||
import 'fake_note_repository.dart';
|
import 'fake_note_repository.dart';
|
||||||
import 'fake_secure_storage.dart';
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
import 'github_mirror_harness.dart';
|
||||||
|
|
||||||
/// Stub launcher that records the URL instead of opening it, so `_openPage`
|
/// Stub launcher that records the URL instead of opening it, so `_openPage`
|
||||||
/// can be exercised without a real platform channel.
|
/// can be exercised without a real platform channel.
|
||||||
class _FakeUrlLauncher extends UrlLauncherPlatform
|
class _FakeUrlLauncher extends UrlLauncherPlatform
|
||||||
@ -37,45 +39,6 @@ class _FakeUrlLauncher extends UrlLauncherPlatform
|
|||||||
}
|
}
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
Future<FakeNoteRepository> pumpMirror(
|
|
||||||
WidgetTester tester, {
|
|
||||||
SyncSettings initial = const SyncSettings(
|
|
||||||
owner: 'kuhyx',
|
|
||||||
repo: 'syncs',
|
|
||||||
token: 't',
|
|
||||||
),
|
|
||||||
http.Client? httpClient,
|
|
||||||
FakeNoteRepository? repository,
|
|
||||||
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
|
||||||
ValueNotifier<AppSettings>? appSettings,
|
|
||||||
}) async {
|
|
||||||
SharedPreferences.setMockInitialValues({});
|
|
||||||
installFakeSecureStorage();
|
|
||||||
tester.view.physicalSize = const Size(1200, 2800);
|
|
||||||
tester.view.devicePixelRatio = 1.0;
|
|
||||||
addTearDown(tester.view.resetPhysicalSize);
|
|
||||||
addTearDown(tester.view.resetDevicePixelRatio);
|
|
||||||
|
|
||||||
final repo = repository ?? FakeNoteRepository();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(
|
|
||||||
home: GitHubMirrorScreen(
|
|
||||||
initial: initial,
|
|
||||||
repository: repo,
|
|
||||||
appSettings:
|
|
||||||
appSettings ??
|
|
||||||
ValueNotifier(const AppSettings(advancedMode: false)),
|
|
||||||
httpClient: httpClient,
|
|
||||||
firebaseFactory: firebaseFactory ?? () async => null,
|
|
||||||
stateStore: InMemorySyncStateStore(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
return repo;
|
|
||||||
}
|
|
||||||
|
|
||||||
testWidgets('Connect GitHub without a client id shows guidance', (
|
testWidgets('Connect GitHub without a client id shows guidance', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
@ -184,182 +147,4 @@ void main() {
|
|||||||
|
|
||||||
expect(find.textContaining('Connected and synced'), findsOneWidget);
|
expect(find.textContaining('Connected and synced'), findsOneWidget);
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('device flow connects but surfaces a post-connect sync failure', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final mock = MockClient((req) async {
|
|
||||||
if (req.url.path.contains('device/code')) {
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({
|
|
||||||
'device_code': 'dev123',
|
|
||||||
'user_code': 'WXYZ-1234',
|
|
||||||
'verification_uri': 'https://github.com/login/device',
|
|
||||||
'interval': 0,
|
|
||||||
'expires_in': 900,
|
|
||||||
}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (req.url.path.contains('login/oauth/access_token')) {
|
|
||||||
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
|
|
||||||
}
|
|
||||||
return http.Response('boom', 500); // the sync's repo calls fail
|
|
||||||
});
|
|
||||||
|
|
||||||
await pumpMirror(
|
|
||||||
tester,
|
|
||||||
initial: const SyncSettings(
|
|
||||||
owner: 'o',
|
|
||||||
repo: 'r',
|
|
||||||
token: '',
|
|
||||||
clientId: 'cid',
|
|
||||||
),
|
|
||||||
httpClient: mock,
|
|
||||||
);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Connect GitHub'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 50));
|
|
||||||
for (var i = 0; i < 6; i++) {
|
|
||||||
await tester.pump();
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(find.textContaining('sync failed'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Save persists the settings and closes the screen', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
SharedPreferences.setMockInitialValues({});
|
|
||||||
installFakeSecureStorage();
|
|
||||||
tester.view.physicalSize = const Size(1200, 2800);
|
|
||||||
tester.view.devicePixelRatio = 1.0;
|
|
||||||
addTearDown(tester.view.resetPhysicalSize);
|
|
||||||
addTearDown(tester.view.resetDevicePixelRatio);
|
|
||||||
|
|
||||||
final repo = FakeNoteRepository();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
|
|
||||||
// Push GitHubMirrorScreen over a base route so _save's Navigator.pop has
|
|
||||||
// somewhere to return to (popping the root route is a no-op and hides
|
|
||||||
// the result).
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(
|
|
||||||
home: Builder(
|
|
||||||
builder: (context) => Scaffold(
|
|
||||||
body: Center(
|
|
||||||
child: ElevatedButton(
|
|
||||||
onPressed: () => Navigator.of(context).push(
|
|
||||||
MaterialPageRoute<SyncSettings>(
|
|
||||||
builder: (_) => GitHubMirrorScreen(
|
|
||||||
initial: const SyncSettings(
|
|
||||||
owner: 'o',
|
|
||||||
repo: 'r',
|
|
||||||
token: 'tok',
|
|
||||||
),
|
|
||||||
repository: repo,
|
|
||||||
appSettings: ValueNotifier(
|
|
||||||
const AppSettings(advancedMode: false),
|
|
||||||
),
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
stateStore: InMemorySyncStateStore(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: const Text('open'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
await tester.tap(find.text('open'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 400)); // route transition
|
|
||||||
expect(find.byType(GitHubMirrorScreen), findsOneWidget); // screen is up
|
|
||||||
|
|
||||||
await tester.tap(find.text('Save'));
|
|
||||||
await tester.pump(); // run _save (persist + pop)
|
|
||||||
await tester.pump(const Duration(milliseconds: 400)); // pop transition
|
|
||||||
|
|
||||||
expect(find.text('open'), findsOneWidget); // back on the base route
|
|
||||||
final saved = await SyncSettings.load();
|
|
||||||
expect(saved.owner, 'o');
|
|
||||||
expect(saved.token, 'tok');
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('device dialog: failed poll shows the error and Open launches', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final launcher = _FakeUrlLauncher();
|
|
||||||
UrlLauncherPlatform.instance = launcher;
|
|
||||||
|
|
||||||
// _openPage copies the code to the clipboard first; there's no
|
|
||||||
// clipboard plugin in the test host, so stub the channel to succeed.
|
|
||||||
final messenger =
|
|
||||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
|
||||||
messenger.setMockMethodCallHandler(
|
|
||||||
SystemChannels.platform,
|
|
||||||
(call) async => null,
|
|
||||||
);
|
|
||||||
addTearDown(
|
|
||||||
() => messenger.setMockMethodCallHandler(SystemChannels.platform, null),
|
|
||||||
);
|
|
||||||
|
|
||||||
final mock = MockClient((req) async {
|
|
||||||
if (req.url.path.contains('device/code')) {
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({
|
|
||||||
'device_code': 'dev123',
|
|
||||||
'user_code': 'WXYZ-1234',
|
|
||||||
'verification_uri': 'https://github.com/login/device',
|
|
||||||
'interval': 0,
|
|
||||||
'expires_in': 900,
|
|
||||||
}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// Token endpoint: a terminal error ends the poll loop cleanly (no
|
|
||||||
// lingering timer to trip the tester's pending-timer guard).
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({'error': 'access_denied', 'error_description': 'nope'}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
await pumpMirror(
|
|
||||||
tester,
|
|
||||||
initial: const SyncSettings(
|
|
||||||
owner: 'o',
|
|
||||||
repo: 'r',
|
|
||||||
token: '',
|
|
||||||
clientId: 'cid',
|
|
||||||
),
|
|
||||||
httpClient: mock,
|
|
||||||
);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Connect GitHub'));
|
|
||||||
await tester.pump(); // requestDeviceCode
|
|
||||||
await tester.pump(); // dialog builds, poll starts (interval 0)
|
|
||||||
expect(find.text('WXYZ-1234'), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.pump(const Duration(milliseconds: 1)); // _delay(0) fires
|
|
||||||
await tester.pump(); // token error throws → _error set
|
|
||||||
expect(find.textContaining('nope'), findsOneWidget); // error rendered
|
|
||||||
|
|
||||||
// Tap the "open on GitHub" action: copies the code and launches the URL.
|
|
||||||
// _openPage awaits Clipboard.setData then the launcher's supportsMode +
|
|
||||||
// launchUrl; pumpAndSettle drains them (no spinner is animating now
|
|
||||||
// that the error is shown, so it settles).
|
|
||||||
await tester.tap(find.byIcon(Icons.open_in_new));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(launcher.launched, 'https://github.com/login/device');
|
|
||||||
|
|
||||||
await tester.tap(find.text('Cancel'));
|
|
||||||
await tester.pumpAndSettle(); // finish the dialog pop animation
|
|
||||||
expect(find.text('WXYZ-1234'), findsNothing); // dialog dismissed
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
135
test/note_editor_guided_test.dart
Normal file
135
test/note_editor_guided_test.dart
Normal file
@ -0,0 +1,135 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
import 'package:todo/ui/markdown_view.dart';
|
||||||
|
import 'package:todo/ui/note_editor.dart';
|
||||||
|
|
||||||
|
import 'note_editor_harness.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('guided: typing the title emits an assembled # heading', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final emitted = await pumpEditor(tester, initialTemplate: spec);
|
||||||
|
|
||||||
|
expect(find.byTooltip('Exit guided'), findsOneWidget);
|
||||||
|
await tester.enterText(find.byType(TextField).first, 'Dark mode');
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(emitted.last, startsWith('# Dark mode'));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('step page Next/Back navigate and progress counter updates', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpEditor(tester, initialTemplate: spec);
|
||||||
|
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||||||
|
expect(find.text('1 / ${spec.sections.length}'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Next'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('2 / ${spec.sections.length}'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Back'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('1 / ${spec.sections.length}'), findsOneWidget);
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('guided: the stepper walks the seven audited sections', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
// The user-visible contract of the 2026-07 template cut. Walks every step
|
||||||
|
// and asserts the label and its guidance are the ones on screen, so a
|
||||||
|
// section resurrected in note_template.dart cannot land unnoticed.
|
||||||
|
await pumpEditor(tester, initialTemplate: spec);
|
||||||
|
|
||||||
|
for (var i = 0; i < spec.sections.length; i++) {
|
||||||
|
final section = spec.sections[i];
|
||||||
|
expect(find.text('${i + 1} / ${spec.sections.length}'), findsOneWidget);
|
||||||
|
expect(
|
||||||
|
find.text(section.isTitle ? 'title' : section.label),
|
||||||
|
findsWidgets,
|
||||||
|
reason: 'step ${i + 1} should show "${section.label}"',
|
||||||
|
);
|
||||||
|
expect(find.text(section.helper), findsOneWidget);
|
||||||
|
if (i < spec.sections.length - 1) {
|
||||||
|
await tester.tap(find.text('Next'));
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The last step is `read first`; there is no Next past it.
|
||||||
|
expect(spec.sections.last.label, 'read first');
|
||||||
|
expect(find.text('Next'), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('pasting a bare link drops the draft to the blank template', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialMode: NoteEditorMode.raw,
|
||||||
|
);
|
||||||
|
expect(find.text('LLM design spec'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.enterText(
|
||||||
|
find.byType(TextField).first,
|
||||||
|
'https://example.com/x',
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// Freeform now, so there is no seven-step stepper to walk for a link.
|
||||||
|
expect(find.text('Blank'), findsOneWidget);
|
||||||
|
expect(find.text('Guided'), findsNothing);
|
||||||
|
|
||||||
|
// Adding prose puts the spec template back — lossless in both directions.
|
||||||
|
await tester.enterText(
|
||||||
|
find.byType(TextField).first,
|
||||||
|
'https://example.com/x — port this to Dart',
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('LLM design spec'), findsOneWidget);
|
||||||
|
expect(find.text('Guided'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('an explicit template choice survives further typing', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialMode: NoteEditorMode.raw,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('LLM design spec'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('Blank').last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Blank'), findsOneWidget);
|
||||||
|
|
||||||
|
// Prose would normally re-select the spec template; an explicit pick wins.
|
||||||
|
await tester.enterText(find.byType(TextField).first, 'build a thing');
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('Blank'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('switching to View renders the note as Markdown', (tester) async {
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialMode: NoteEditorMode.raw,
|
||||||
|
);
|
||||||
|
await tester.enterText(find.byType(TextField).first, '# Render me');
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
await tester.tap(find.text('View'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.byType(MarkdownView), findsOneWidget);
|
||||||
|
expect(find.text('Render me'), findsOneWidget); // rendered heading text
|
||||||
|
});
|
||||||
|
}
|
||||||
50
test/note_editor_harness.dart
Normal file
50
test/note_editor_harness.dart
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
/// The shared pumpEditor harness and template constants.
|
||||||
|
///
|
||||||
|
/// Shared by the files `note_editor_test.dart` was split into for the
|
||||||
|
/// 250-line cap. Deliberately NOT named `*_test.dart`: the runner would
|
||||||
|
/// collect it and fail on the missing `main()`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
import 'package:todo/ui/markdown_view.dart';
|
||||||
|
import 'package:todo/ui/note_editor.dart';
|
||||||
|
|
||||||
|
const spec = NoteTemplate.llmDesignSpec;
|
||||||
|
const blank = NoteTemplate.blank;
|
||||||
|
|
||||||
|
// Pumps an editor and exposes the latest text emitted via onChanged.
|
||||||
|
Future<List<String>> pumpEditor(
|
||||||
|
WidgetTester tester, {
|
||||||
|
String initialText = '',
|
||||||
|
NoteTemplate? initialTemplate,
|
||||||
|
NoteEditorMode initialMode = NoteEditorMode.guided,
|
||||||
|
Priority priority = Priority.defaultValue,
|
||||||
|
ValueChanged<Priority>? onPriorityChanged,
|
||||||
|
ValueChanged<bool>? onChromeVisibleChanged,
|
||||||
|
}) async {
|
||||||
|
final emitted = <String>[];
|
||||||
|
tester.view.physicalSize = const Size(1200, 2400);
|
||||||
|
tester.view.devicePixelRatio = 1.0;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: NoteEditor(
|
||||||
|
initialText: initialText,
|
||||||
|
initialTemplate: initialTemplate,
|
||||||
|
initialMode: initialMode,
|
||||||
|
priority: priority,
|
||||||
|
onPriorityChanged: onPriorityChanged ?? (_) {},
|
||||||
|
onChromeVisibleChanged: onChromeVisibleChanged ?? (_) {},
|
||||||
|
onChanged: emitted.add,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
return emitted;
|
||||||
|
}
|
||||||
172
test/note_editor_modes_test.dart
Normal file
172
test/note_editor_modes_test.dart
Normal file
@ -0,0 +1,172 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
import 'package:todo/ui/markdown_view.dart';
|
||||||
|
import 'package:todo/ui/note_editor.dart';
|
||||||
|
|
||||||
|
import 'note_editor_harness.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets(
|
||||||
|
'bare Guided back arrow returns to Raw, materialising the assembled text',
|
||||||
|
(tester) async {
|
||||||
|
final emitted = await pumpEditor(tester, initialTemplate: spec);
|
||||||
|
await tester.enterText(find.byType(TextField).first, 'T');
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Exit guided'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
final raw = tester.widget<TextField>(find.byType(TextField));
|
||||||
|
expect(raw.controller!.text, startsWith('# T'));
|
||||||
|
|
||||||
|
await tester.enterText(find.byType(TextField), '# T\n\n## what\nedited');
|
||||||
|
await tester.pump();
|
||||||
|
expect(emitted.last, contains('edited'));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('Raw → Guided is blocked with a snackbar when non-conforming', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialText: 'totally freeform text',
|
||||||
|
initialMode: NoteEditorMode.raw,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Structured template + non-conforming raw text → switching is refused.
|
||||||
|
await tester.tap(find.text('Guided'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.textContaining("doesn't match the template"), findsOneWidget);
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsNothing); // still raw
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'guided → Raw → Guided round-trips (skipping the wizard) when text still conforms',
|
||||||
|
(tester) async {
|
||||||
|
// Open guided from a conforming note (pre-fills the section controllers
|
||||||
|
// without typing into collapsed steps), so the assembled body conforms.
|
||||||
|
final conforming = assemble(spec, {'title': 'Keep', 'what': 'a body'});
|
||||||
|
await pumpEditor(tester, initialTemplate: spec, initialText: conforming);
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||||||
|
|
||||||
|
// Bare guided -> raw via the back arrow makes the (still conforming)
|
||||||
|
// body the source…
|
||||||
|
await tester.tap(find.byTooltip('Exit guided'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsNothing);
|
||||||
|
|
||||||
|
// …then raw -> guided re-parses the conforming body straight back into
|
||||||
|
// the bare stepper — no wizard, since the content isn't empty.
|
||||||
|
await tester.tap(find.text('Guided'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||||||
|
expect(find.text('Step 1 of 2'), findsNothing); // wizard was skipped
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('freeform template offers only View and Raw', (tester) async {
|
||||||
|
final emitted = await pumpEditor(tester, initialTemplate: blank);
|
||||||
|
|
||||||
|
expect(find.text('Guided'), findsNothing);
|
||||||
|
expect(find.text('View'), findsOneWidget);
|
||||||
|
expect(find.text('Raw'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.enterText(find.byType(TextField), 'free text');
|
||||||
|
await tester.pump();
|
||||||
|
expect(emitted.last, 'free text');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('switching template via the dropdown reloads the source', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialMode: NoteEditorMode.raw,
|
||||||
|
);
|
||||||
|
expect(find.text('Guided'), findsOneWidget); // structured: Guided offered
|
||||||
|
|
||||||
|
await tester.tap(find.text('LLM design spec').first); // open the menu
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('Blank').last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
// Freeform now: Guided is no longer offered.
|
||||||
|
expect(find.text('Guided'), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('detects a conforming note (no template given) as guided', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final conforming = assemble(spec, {'title': 'Detected', 'what': 'x'});
|
||||||
|
await pumpEditor(tester, initialText: conforming);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
find.byType(LinearProgressIndicator),
|
||||||
|
findsOneWidget,
|
||||||
|
); // guided by default
|
||||||
|
expect(find.byTooltip('Exit guided'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('detects a legacy note (no template given) as freeform raw', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpEditor(tester, initialText: 'old\n\nwhat — legacy');
|
||||||
|
|
||||||
|
// Non-conforming → blank/raw, no guided stepper offered.
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsNothing);
|
||||||
|
expect(find.text('Guided'), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('initialMode preview opens directly in the rendered view', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final conforming = assemble(spec, {'title': 'Preview me'});
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialText: conforming,
|
||||||
|
initialMode: NoteEditorMode.preview,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(find.byType(MarkdownView), findsOneWidget);
|
||||||
|
expect(find.text('Preview me'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Preview → Raw materialises the still-guided source', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final conforming = assemble(spec, {'title': 'Preview src', 'what': 'x'});
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialText: conforming,
|
||||||
|
initialMode: NoteEditorMode.preview,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Raw'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
final raw = tester.widget<TextField>(find.byType(TextField));
|
||||||
|
expect(raw.controller!.text, contains('Preview src'));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('initialMode guided falls back to Raw for non-conforming text', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialText: 'cannot be guided',
|
||||||
|
initialMode: NoteEditorMode.guided,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Guided was requested but the text does not conform → opened in Raw.
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsNothing);
|
||||||
|
final raw = tester.widget<TextField>(find.byType(TextField));
|
||||||
|
expect(raw.controller!.text, 'cannot be guided');
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -1,502 +0,0 @@
|
|||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
import 'package:todo/data/note_template.dart';
|
|
||||||
import 'package:todo/ui/markdown_view.dart';
|
|
||||||
import 'package:todo/ui/note_editor.dart';
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
const spec = NoteTemplate.llmDesignSpec;
|
|
||||||
const blank = NoteTemplate.blank;
|
|
||||||
|
|
||||||
// Pumps an editor and exposes the latest text emitted via onChanged.
|
|
||||||
Future<List<String>> pumpEditor(
|
|
||||||
WidgetTester tester, {
|
|
||||||
String initialText = '',
|
|
||||||
NoteTemplate? initialTemplate,
|
|
||||||
NoteEditorMode initialMode = NoteEditorMode.guided,
|
|
||||||
Priority priority = Priority.defaultValue,
|
|
||||||
ValueChanged<Priority>? onPriorityChanged,
|
|
||||||
ValueChanged<bool>? onChromeVisibleChanged,
|
|
||||||
}) async {
|
|
||||||
final emitted = <String>[];
|
|
||||||
tester.view.physicalSize = const Size(1200, 2400);
|
|
||||||
tester.view.devicePixelRatio = 1.0;
|
|
||||||
addTearDown(tester.view.resetPhysicalSize);
|
|
||||||
addTearDown(tester.view.resetDevicePixelRatio);
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(
|
|
||||||
home: Scaffold(
|
|
||||||
body: NoteEditor(
|
|
||||||
initialText: initialText,
|
|
||||||
initialTemplate: initialTemplate,
|
|
||||||
initialMode: initialMode,
|
|
||||||
priority: priority,
|
|
||||||
onPriorityChanged: onPriorityChanged ?? (_) {},
|
|
||||||
onChromeVisibleChanged: onChromeVisibleChanged ?? (_) {},
|
|
||||||
onChanged: emitted.add,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
return emitted;
|
|
||||||
}
|
|
||||||
|
|
||||||
testWidgets('guided: typing the title emits an assembled # heading', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final emitted = await pumpEditor(tester, initialTemplate: spec);
|
|
||||||
|
|
||||||
expect(find.byTooltip('Exit guided'), findsOneWidget);
|
|
||||||
await tester.enterText(find.byType(TextField).first, 'Dark mode');
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(emitted.last, startsWith('# Dark mode'));
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('step page Next/Back navigate and progress counter updates', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpEditor(tester, initialTemplate: spec);
|
|
||||||
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
|
||||||
expect(find.text('1 / ${spec.sections.length}'), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Next'));
|
|
||||||
await tester.pump();
|
|
||||||
expect(find.text('2 / ${spec.sections.length}'), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Back'));
|
|
||||||
await tester.pump();
|
|
||||||
expect(find.text('1 / ${spec.sections.length}'), findsOneWidget);
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('guided: the stepper walks the seven audited sections', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// The user-visible contract of the 2026-07 template cut. Walks every step
|
|
||||||
// and asserts the label and its guidance are the ones on screen, so a
|
|
||||||
// section resurrected in note_template.dart cannot land unnoticed.
|
|
||||||
await pumpEditor(tester, initialTemplate: spec);
|
|
||||||
|
|
||||||
for (var i = 0; i < spec.sections.length; i++) {
|
|
||||||
final section = spec.sections[i];
|
|
||||||
expect(find.text('${i + 1} / ${spec.sections.length}'), findsOneWidget);
|
|
||||||
expect(
|
|
||||||
find.text(section.isTitle ? 'title' : section.label),
|
|
||||||
findsWidgets,
|
|
||||||
reason: 'step ${i + 1} should show "${section.label}"',
|
|
||||||
);
|
|
||||||
expect(find.text(section.helper), findsOneWidget);
|
|
||||||
if (i < spec.sections.length - 1) {
|
|
||||||
await tester.tap(find.text('Next'));
|
|
||||||
await tester.pump();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The last step is `read first`; there is no Next past it.
|
|
||||||
expect(spec.sections.last.label, 'read first');
|
|
||||||
expect(find.text('Next'), findsNothing);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('pasting a bare link drops the draft to the blank template', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialMode: NoteEditorMode.raw,
|
|
||||||
);
|
|
||||||
expect(find.text('LLM design spec'), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.enterText(
|
|
||||||
find.byType(TextField).first,
|
|
||||||
'https://example.com/x',
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// Freeform now, so there is no seven-step stepper to walk for a link.
|
|
||||||
expect(find.text('Blank'), findsOneWidget);
|
|
||||||
expect(find.text('Guided'), findsNothing);
|
|
||||||
|
|
||||||
// Adding prose puts the spec template back — lossless in both directions.
|
|
||||||
await tester.enterText(
|
|
||||||
find.byType(TextField).first,
|
|
||||||
'https://example.com/x — port this to Dart',
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
expect(find.text('LLM design spec'), findsOneWidget);
|
|
||||||
expect(find.text('Guided'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('an explicit template choice survives further typing', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialMode: NoteEditorMode.raw,
|
|
||||||
);
|
|
||||||
|
|
||||||
await tester.tap(find.text('LLM design spec'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
await tester.tap(find.text('Blank').last);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(find.text('Blank'), findsOneWidget);
|
|
||||||
|
|
||||||
// Prose would normally re-select the spec template; an explicit pick wins.
|
|
||||||
await tester.enterText(find.byType(TextField).first, 'build a thing');
|
|
||||||
await tester.pump();
|
|
||||||
expect(find.text('Blank'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('switching to View renders the note as Markdown', (tester) async {
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialMode: NoteEditorMode.raw,
|
|
||||||
);
|
|
||||||
await tester.enterText(find.byType(TextField).first, '# Render me');
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
await tester.tap(find.text('View'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.byType(MarkdownView), findsOneWidget);
|
|
||||||
expect(find.text('Render me'), findsOneWidget); // rendered heading text
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets(
|
|
||||||
'bare Guided back arrow returns to Raw, materialising the assembled text',
|
|
||||||
(tester) async {
|
|
||||||
final emitted = await pumpEditor(tester, initialTemplate: spec);
|
|
||||||
await tester.enterText(find.byType(TextField).first, 'T');
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('Exit guided'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
final raw = tester.widget<TextField>(find.byType(TextField));
|
|
||||||
expect(raw.controller!.text, startsWith('# T'));
|
|
||||||
|
|
||||||
await tester.enterText(find.byType(TextField), '# T\n\n## what\nedited');
|
|
||||||
await tester.pump();
|
|
||||||
expect(emitted.last, contains('edited'));
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
testWidgets('Raw → Guided is blocked with a snackbar when non-conforming', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialText: 'totally freeform text',
|
|
||||||
initialMode: NoteEditorMode.raw,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Structured template + non-conforming raw text → switching is refused.
|
|
||||||
await tester.tap(find.text('Guided'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.textContaining("doesn't match the template"), findsOneWidget);
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsNothing); // still raw
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets(
|
|
||||||
'guided → Raw → Guided round-trips (skipping the wizard) when text still conforms',
|
|
||||||
(tester) async {
|
|
||||||
// Open guided from a conforming note (pre-fills the section controllers
|
|
||||||
// without typing into collapsed steps), so the assembled body conforms.
|
|
||||||
final conforming = assemble(spec, {'title': 'Keep', 'what': 'a body'});
|
|
||||||
await pumpEditor(tester, initialTemplate: spec, initialText: conforming);
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
|
||||||
|
|
||||||
// Bare guided -> raw via the back arrow makes the (still conforming)
|
|
||||||
// body the source…
|
|
||||||
await tester.tap(find.byTooltip('Exit guided'));
|
|
||||||
await tester.pump();
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsNothing);
|
|
||||||
|
|
||||||
// …then raw -> guided re-parses the conforming body straight back into
|
|
||||||
// the bare stepper — no wizard, since the content isn't empty.
|
|
||||||
await tester.tap(find.text('Guided'));
|
|
||||||
await tester.pump();
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
|
||||||
expect(find.text('Step 1 of 2'), findsNothing); // wizard was skipped
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
testWidgets('freeform template offers only View and Raw', (tester) async {
|
|
||||||
final emitted = await pumpEditor(tester, initialTemplate: blank);
|
|
||||||
|
|
||||||
expect(find.text('Guided'), findsNothing);
|
|
||||||
expect(find.text('View'), findsOneWidget);
|
|
||||||
expect(find.text('Raw'), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.enterText(find.byType(TextField), 'free text');
|
|
||||||
await tester.pump();
|
|
||||||
expect(emitted.last, 'free text');
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('switching template via the dropdown reloads the source', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialMode: NoteEditorMode.raw,
|
|
||||||
);
|
|
||||||
expect(find.text('Guided'), findsOneWidget); // structured: Guided offered
|
|
||||||
|
|
||||||
await tester.tap(find.text('LLM design spec').first); // open the menu
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
await tester.tap(find.text('Blank').last);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
// Freeform now: Guided is no longer offered.
|
|
||||||
expect(find.text('Guided'), findsNothing);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('detects a conforming note (no template given) as guided', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final conforming = assemble(spec, {'title': 'Detected', 'what': 'x'});
|
|
||||||
await pumpEditor(tester, initialText: conforming);
|
|
||||||
|
|
||||||
expect(
|
|
||||||
find.byType(LinearProgressIndicator),
|
|
||||||
findsOneWidget,
|
|
||||||
); // guided by default
|
|
||||||
expect(find.byTooltip('Exit guided'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('detects a legacy note (no template given) as freeform raw', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpEditor(tester, initialText: 'old\n\nwhat — legacy');
|
|
||||||
|
|
||||||
// Non-conforming → blank/raw, no guided stepper offered.
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsNothing);
|
|
||||||
expect(find.text('Guided'), findsNothing);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('initialMode preview opens directly in the rendered view', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final conforming = assemble(spec, {'title': 'Preview me'});
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialText: conforming,
|
|
||||||
initialMode: NoteEditorMode.preview,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(find.byType(MarkdownView), findsOneWidget);
|
|
||||||
expect(find.text('Preview me'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Preview → Raw materialises the still-guided source', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final conforming = assemble(spec, {'title': 'Preview src', 'what': 'x'});
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialText: conforming,
|
|
||||||
initialMode: NoteEditorMode.preview,
|
|
||||||
);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Raw'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
final raw = tester.widget<TextField>(find.byType(TextField));
|
|
||||||
expect(raw.controller!.text, contains('Preview src'));
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('initialMode guided falls back to Raw for non-conforming text', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialText: 'cannot be guided',
|
|
||||||
initialMode: NoteEditorMode.guided,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Guided was requested but the text does not conform → opened in Raw.
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsNothing);
|
|
||||||
final raw = tester.widget<TextField>(find.byType(TextField));
|
|
||||||
expect(raw.controller!.text, 'cannot be guided');
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets(
|
|
||||||
'tapping Guided on an empty draft opens the priority+template wizard',
|
|
||||||
(tester) async {
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialMode: NoteEditorMode.raw,
|
|
||||||
);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Guided'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.text('Step 1 of 2'), findsOneWidget);
|
|
||||||
expect(find.byType(DropdownButtonFormField<Priority>), findsOneWidget);
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsNothing);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
testWidgets(
|
|
||||||
'the wizard Next/Back moves between priority and template steps',
|
|
||||||
(tester) async {
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialMode: NoteEditorMode.raw,
|
|
||||||
);
|
|
||||||
await tester.tap(find.text('Guided'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
await tester.tap(find.text('Next'));
|
|
||||||
await tester.pump();
|
|
||||||
expect(find.text('Step 2 of 2'), findsOneWidget);
|
|
||||||
expect(find.byType(DropdownButtonFormField<String>), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Back'));
|
|
||||||
await tester.pump();
|
|
||||||
expect(find.text('Step 1 of 2'), findsOneWidget);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
testWidgets('the wizard template step only offers structured templates', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialMode: NoteEditorMode.raw,
|
|
||||||
);
|
|
||||||
await tester.tap(find.text('Guided'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.tap(find.text('Next'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
await tester.tap(find.text('LLM design spec').first); // open the menu
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(find.text('Blank'), findsNothing);
|
|
||||||
|
|
||||||
// Select the (only) offered template, exercising the dropdown's onChanged.
|
|
||||||
await tester.tap(find.text('LLM design spec').last);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(find.text('Step 2 of 2'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets(
|
|
||||||
'wizard Start commits the chosen priority and enters the bare stepper',
|
|
||||||
(tester) async {
|
|
||||||
Priority? committed;
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialMode: NoteEditorMode.raw,
|
|
||||||
onPriorityChanged: (p) => committed = p,
|
|
||||||
);
|
|
||||||
await tester.tap(find.text('Guided'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
await tester.tap(find.byType(DropdownButtonFormField<Priority>));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
await tester.tap(find.text('High').last);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.tap(find.text('Next'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.tap(find.text('Start'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(committed, Priority.high);
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
|
||||||
expect(find.byTooltip('Exit guided'), findsOneWidget);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
testWidgets('wizard Cancel returns to Raw with the chrome restored', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final chromeVisible = <bool>[];
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialMode: NoteEditorMode.raw,
|
|
||||||
onChromeVisibleChanged: chromeVisible.add,
|
|
||||||
);
|
|
||||||
await tester.tap(find.text('Guided'));
|
|
||||||
await tester.pump();
|
|
||||||
expect(chromeVisible.last, false);
|
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('Cancel'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(chromeVisible.last, true);
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsNothing);
|
|
||||||
expect(find.text('Raw'), findsOneWidget); // chrome's mode selector is back
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('exiting bare Guided via the back arrow restores the chrome', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final chromeVisible = <bool>[];
|
|
||||||
final conforming = assemble(spec, {'title': 'X', 'what': 'a body'});
|
|
||||||
await pumpEditor(
|
|
||||||
tester,
|
|
||||||
initialTemplate: spec,
|
|
||||||
initialText: conforming,
|
|
||||||
onChromeVisibleChanged: chromeVisible.add,
|
|
||||||
);
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('Exit guided'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(chromeVisible, contains(true));
|
|
||||||
expect(find.text('Raw'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('last step shows Done instead of Next', (tester) async {
|
|
||||||
await pumpEditor(tester, initialTemplate: spec);
|
|
||||||
|
|
||||||
// Navigate to the final step.
|
|
||||||
for (var i = 0; i < spec.sections.length - 1; i++) {
|
|
||||||
await tester.tap(find.text('Next'));
|
|
||||||
await tester.pump();
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(find.text('Done'), findsOneWidget);
|
|
||||||
expect(find.text('Next'), findsNothing);
|
|
||||||
expect(
|
|
||||||
find.text('${spec.sections.length} / ${spec.sections.length}'),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Done on last step exits Guided and materialises text into Raw', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpEditor(tester, initialTemplate: spec);
|
|
||||||
await tester.enterText(find.byType(TextField).first, 'My title');
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
for (var i = 0; i < spec.sections.length - 1; i++) {
|
|
||||||
await tester.tap(find.text('Next'));
|
|
||||||
await tester.pump();
|
|
||||||
}
|
|
||||||
await tester.tap(find.text('Done'));
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.byType(LinearProgressIndicator), findsNothing);
|
|
||||||
final raw = tester.widget<TextField>(find.byType(TextField));
|
|
||||||
expect(raw.controller!.text, startsWith('# My title'));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
180
test/note_editor_wizard_test.dart
Normal file
180
test/note_editor_wizard_test.dart
Normal file
@ -0,0 +1,180 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_template.dart';
|
||||||
|
import 'package:todo/ui/markdown_view.dart';
|
||||||
|
import 'package:todo/ui/note_editor.dart';
|
||||||
|
|
||||||
|
import 'note_editor_harness.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets(
|
||||||
|
'tapping Guided on an empty draft opens the priority+template wizard',
|
||||||
|
(tester) async {
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialMode: NoteEditorMode.raw,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Guided'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.text('Step 1 of 2'), findsOneWidget);
|
||||||
|
expect(find.byType(DropdownButtonFormField<Priority>), findsOneWidget);
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsNothing);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'the wizard Next/Back moves between priority and template steps',
|
||||||
|
(tester) async {
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialMode: NoteEditorMode.raw,
|
||||||
|
);
|
||||||
|
await tester.tap(find.text('Guided'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Next'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('Step 2 of 2'), findsOneWidget);
|
||||||
|
expect(find.byType(DropdownButtonFormField<String>), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Back'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('Step 1 of 2'), findsOneWidget);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('the wizard template step only offers structured templates', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialMode: NoteEditorMode.raw,
|
||||||
|
);
|
||||||
|
await tester.tap(find.text('Guided'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(find.text('Next'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
await tester.tap(find.text('LLM design spec').first); // open the menu
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Blank'), findsNothing);
|
||||||
|
|
||||||
|
// Select the (only) offered template, exercising the dropdown's onChanged.
|
||||||
|
await tester.tap(find.text('LLM design spec').last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Step 2 of 2'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'wizard Start commits the chosen priority and enters the bare stepper',
|
||||||
|
(tester) async {
|
||||||
|
Priority? committed;
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialMode: NoteEditorMode.raw,
|
||||||
|
onPriorityChanged: (p) => committed = p,
|
||||||
|
);
|
||||||
|
await tester.tap(find.text('Guided'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
await tester.tap(find.byType(DropdownButtonFormField<Priority>));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('High').last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Next'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(find.text('Start'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(committed, Priority.high);
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||||||
|
expect(find.byTooltip('Exit guided'), findsOneWidget);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('wizard Cancel returns to Raw with the chrome restored', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final chromeVisible = <bool>[];
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialMode: NoteEditorMode.raw,
|
||||||
|
onChromeVisibleChanged: chromeVisible.add,
|
||||||
|
);
|
||||||
|
await tester.tap(find.text('Guided'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(chromeVisible.last, false);
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Cancel'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(chromeVisible.last, true);
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsNothing);
|
||||||
|
expect(find.text('Raw'), findsOneWidget); // chrome's mode selector is back
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('exiting bare Guided via the back arrow restores the chrome', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final chromeVisible = <bool>[];
|
||||||
|
final conforming = assemble(spec, {'title': 'X', 'what': 'a body'});
|
||||||
|
await pumpEditor(
|
||||||
|
tester,
|
||||||
|
initialTemplate: spec,
|
||||||
|
initialText: conforming,
|
||||||
|
onChromeVisibleChanged: chromeVisible.add,
|
||||||
|
);
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Exit guided'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(chromeVisible, contains(true));
|
||||||
|
expect(find.text('Raw'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('last step shows Done instead of Next', (tester) async {
|
||||||
|
await pumpEditor(tester, initialTemplate: spec);
|
||||||
|
|
||||||
|
// Navigate to the final step.
|
||||||
|
for (var i = 0; i < spec.sections.length - 1; i++) {
|
||||||
|
await tester.tap(find.text('Next'));
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(find.text('Done'), findsOneWidget);
|
||||||
|
expect(find.text('Next'), findsNothing);
|
||||||
|
expect(
|
||||||
|
find.text('${spec.sections.length} / ${spec.sections.length}'),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Done on last step exits Guided and materialises text into Raw', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpEditor(tester, initialTemplate: spec);
|
||||||
|
await tester.enterText(find.byType(TextField).first, 'My title');
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
for (var i = 0; i < spec.sections.length - 1; i++) {
|
||||||
|
await tester.tap(find.text('Next'));
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
await tester.tap(find.text('Done'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.byType(LinearProgressIndicator), findsNothing);
|
||||||
|
final raw = tester.widget<TextField>(find.byType(TextField));
|
||||||
|
expect(raw.controller!.text, startsWith('# My title'));
|
||||||
|
});
|
||||||
|
}
|
||||||
114
test/note_repository_crud_test.dart
Normal file
114
test/note_repository_crud_test.dart
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
/// Core CRUD, tombstones, sorting, and priority defaults.
|
||||||
|
///
|
||||||
|
/// One of four files `note_repository_test.dart` was split into for the
|
||||||
|
/// 250-line cap. Each carries its own `setUpAll(sqfliteFfiInit)`: without it
|
||||||
|
/// sqflite is never initialised and every test in the file fails.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||||
|
// SqliteCrdt is needed to seed the legacy DB in migration tests; hide its Hlc
|
||||||
|
// so the crdt_sync Hlc/Record are unambiguous.
|
||||||
|
import 'package:sqlite_crdt/sqlite_crdt.dart' hide Hlc;
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/data/repository_factory_io.dart';
|
||||||
|
|
||||||
|
import 'note_repository_helpers.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUpAll(sqfliteFfiInit);
|
||||||
|
|
||||||
|
test('upsert then list returns the note', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
|
||||||
|
await repo.upsert(noteFixture('a', 'first idea'));
|
||||||
|
final notes = await repo.listNotes();
|
||||||
|
|
||||||
|
expect(notes, hasLength(1));
|
||||||
|
expect(notes.single.text, 'first idea');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deleted notes are excluded from reads (tombstone filter)', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
|
||||||
|
await repo.upsert(noteFixture('a', 'keep me'));
|
||||||
|
await repo.upsert(noteFixture('b', 'delete me'));
|
||||||
|
await repo.delete('b');
|
||||||
|
|
||||||
|
final notes = await repo.listNotes();
|
||||||
|
expect(notes, hasLength(1));
|
||||||
|
expect(notes.single.text, 'keep me');
|
||||||
|
|
||||||
|
// The tombstone must survive in the exported log so the deletion syncs.
|
||||||
|
final log = repo.exportLog();
|
||||||
|
expect(log['b']!.deleted, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('modifiedDesc sort orders most-recently-updated first', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
|
||||||
|
await repo.upsert(noteFixture('a', 'older', updatedAt: DateTime(2026)));
|
||||||
|
await repo.upsert(noteFixture('b', 'newer', updatedAt: DateTime(2026, 6)));
|
||||||
|
|
||||||
|
final notes = await repo.listNotes(sort: NoteSort.modifiedDesc);
|
||||||
|
expect(notes.map((n) => n.text), ['newer', 'older']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('priority sort orders highest first', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
|
||||||
|
await repo.upsert(noteFixture('a', 'low', priority: Priority.low));
|
||||||
|
await repo.upsert(noteFixture('b', 'high', priority: Priority.high));
|
||||||
|
|
||||||
|
final notes = await repo.listNotes(sort: NoteSort.priorityDesc);
|
||||||
|
expect(notes.first.text, 'high');
|
||||||
|
expect(notes.last.text, 'low');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('priority sort breaks ties by most-recently-updated', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture(
|
||||||
|
'a',
|
||||||
|
'older',
|
||||||
|
priority: Priority.high,
|
||||||
|
updatedAt: DateTime(2026),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture(
|
||||||
|
'b',
|
||||||
|
'newer',
|
||||||
|
priority: Priority.high,
|
||||||
|
updatedAt: DateTime(2026, 6),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final notes = await repo.listNotes(sort: NoteSort.priorityDesc);
|
||||||
|
expect(notes.map((n) => n.text), ['newer', 'older']);
|
||||||
|
});
|
||||||
|
|
||||||
|
group('priority defaults', () {
|
||||||
|
test('fromValue maps legacy/unknown values to medium', () {
|
||||||
|
expect(Priority.fromValue(0), Priority.medium); // old "none"
|
||||||
|
expect(Priority.fromValue(null), Priority.medium);
|
||||||
|
expect(Priority.fromValue(99), Priority.medium);
|
||||||
|
// Known values still round-trip.
|
||||||
|
expect(Priority.fromValue(1), Priority.low);
|
||||||
|
expect(Priority.fromValue(2), Priority.medium);
|
||||||
|
expect(Priority.fromValue(3), Priority.high);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
238
test/note_repository_filters_test.dart
Normal file
238
test/note_repository_filters_test.dart
Normal file
@ -0,0 +1,238 @@
|
|||||||
|
/// Search, attribute/date filters, and NoteFilter itself.
|
||||||
|
///
|
||||||
|
/// One of four files `note_repository_test.dart` was split into for the
|
||||||
|
/// 250-line cap. Each carries its own `setUpAll(sqfliteFfiInit)`: without it
|
||||||
|
/// sqflite is never initialised and every test in the file fails.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||||
|
// SqliteCrdt is needed to seed the legacy DB in migration tests; hide its Hlc
|
||||||
|
// so the crdt_sync Hlc/Record are unambiguous.
|
||||||
|
import 'package:sqlite_crdt/sqlite_crdt.dart' hide Hlc;
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/data/repository_factory_io.dart';
|
||||||
|
|
||||||
|
import 'note_repository_helpers.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUpAll(sqfliteFfiInit);
|
||||||
|
|
||||||
|
group('text search', () {
|
||||||
|
test('matches a case-insensitive substring', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await repo.upsert(noteFixture('a', 'Buy MILK and eggs'));
|
||||||
|
await repo.upsert(noteFixture('b', 'call the dentist'));
|
||||||
|
|
||||||
|
final notes = await repo.listNotes(
|
||||||
|
filter: const NoteFilter(query: 'milk'),
|
||||||
|
);
|
||||||
|
expect(notes.map((n) => n.id), ['a']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('escapes LIKE wildcards so % is matched literally', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await repo.upsert(noteFixture('pct', 'a%b'));
|
||||||
|
await repo.upsert(noteFixture('plain', 'axb'));
|
||||||
|
|
||||||
|
// Without escaping, 'a%b' as a LIKE pattern would also match 'axb'.
|
||||||
|
final notes = await repo.listNotes(
|
||||||
|
filter: const NoteFilter(query: 'a%b'),
|
||||||
|
);
|
||||||
|
expect(notes.map((n) => n.id), ['pct']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('attribute filters', () {
|
||||||
|
test('priority filter includes only the selected priorities', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await repo.upsert(noteFixture('lo', 'l', priority: Priority.low));
|
||||||
|
await repo.upsert(noteFixture('me', 'm', priority: Priority.medium));
|
||||||
|
await repo.upsert(noteFixture('hi', 'h', priority: Priority.high));
|
||||||
|
|
||||||
|
final notes = await repo.listNotes(
|
||||||
|
filter: const NoteFilter(priorities: {Priority.low, Priority.high}),
|
||||||
|
);
|
||||||
|
expect(notes.map((n) => n.id).toSet(), {'lo', 'hi'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('status filter includes only the selected statuses', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await repo.upsert(noteFixture('t', 'todo', status: Status.todo));
|
||||||
|
await repo.upsert(noteFixture('d', 'done', status: Status.done));
|
||||||
|
await repo.upsert(noteFixture('x', 'gone', status: Status.abandoned));
|
||||||
|
|
||||||
|
final notes = await repo.listNotes(
|
||||||
|
filter: const NoteFilter(statuses: {Status.todo, Status.inProgress}),
|
||||||
|
);
|
||||||
|
expect(notes.map((n) => n.id), ['t']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('date range filters', () {
|
||||||
|
final jan = DateTime(2026, 1, 15, 10);
|
||||||
|
final jun = DateTime(2026, 6, 15, 10);
|
||||||
|
|
||||||
|
test('created range bounds are inclusive by calendar day', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture('j', 'jan', createdAt: jan, updatedAt: jan),
|
||||||
|
);
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture('u', 'jun', createdAt: jun, updatedAt: jun),
|
||||||
|
);
|
||||||
|
|
||||||
|
// A single-day range on Jan 15 includes the 10:00 note that day.
|
||||||
|
final notes = await repo.listNotes(
|
||||||
|
filter: NoteFilter(
|
||||||
|
createdFrom: DateTime(2026, 1, 15),
|
||||||
|
createdTo: DateTime(2026, 1, 15),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(notes.map((n) => n.id), ['j']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('created and updated ranges apply independently', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
// Created in Jan, but last updated in Jun.
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture('e', 'edited later', createdAt: jan, updatedAt: jun),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Matches on the updated range...
|
||||||
|
final byUpdated = await repo.listNotes(
|
||||||
|
filter: NoteFilter(
|
||||||
|
updatedFrom: DateTime(2026, 6, 1),
|
||||||
|
updatedTo: DateTime(2026, 6, 30),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(byUpdated.map((n) => n.id), ['e']);
|
||||||
|
|
||||||
|
// ...but not when the created range excludes January.
|
||||||
|
final byCreated = await repo.listNotes(
|
||||||
|
filter: NoteFilter(
|
||||||
|
createdFrom: DateTime(2026, 6, 1),
|
||||||
|
createdTo: DateTime(2026, 6, 30),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(byCreated, isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('filters combine with AND', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture(
|
||||||
|
'match',
|
||||||
|
'urgent report',
|
||||||
|
priority: Priority.high,
|
||||||
|
status: Status.inProgress,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture(
|
||||||
|
'wrongPrio',
|
||||||
|
'urgent report',
|
||||||
|
priority: Priority.low,
|
||||||
|
status: Status.inProgress,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture(
|
||||||
|
'wrongText',
|
||||||
|
'casual note',
|
||||||
|
priority: Priority.high,
|
||||||
|
status: Status.inProgress,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final notes = await repo.listNotes(
|
||||||
|
filter: const NoteFilter(
|
||||||
|
query: 'urgent',
|
||||||
|
priorities: {Priority.high},
|
||||||
|
statuses: {Status.inProgress},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(notes.map((n) => n.id), ['match']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('date-range filters bound by whole calendar days', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture(
|
||||||
|
'jan',
|
||||||
|
'january idea',
|
||||||
|
createdAt: DateTime(2026, 1, 10),
|
||||||
|
updatedAt: DateTime(2026, 1, 10),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture(
|
||||||
|
'mar',
|
||||||
|
'march idea',
|
||||||
|
createdAt: DateTime(2026, 3, 10),
|
||||||
|
updatedAt: DateTime(2026, 3, 10),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final byCreated = await repo.listNotes(
|
||||||
|
filter: NoteFilter(
|
||||||
|
createdFrom: DateTime(2026, 2, 1),
|
||||||
|
createdTo: DateTime(2026, 4, 1),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(byCreated.map((n) => n.text), ['march idea']);
|
||||||
|
|
||||||
|
final byUpdated = await repo.listNotes(
|
||||||
|
filter: NoteFilter(
|
||||||
|
updatedFrom: DateTime(2026, 1, 1),
|
||||||
|
updatedTo: DateTime(2026, 1, 31),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(byUpdated.map((n) => n.text), ['january idea']);
|
||||||
|
});
|
||||||
|
|
||||||
|
group('NoteFilter', () {
|
||||||
|
test('a default filter is empty (all facets cleared)', () {
|
||||||
|
// Evaluates the full conjunction in `isEmpty`, including the date bounds.
|
||||||
|
const filter = NoteFilter();
|
||||||
|
expect(filter.isEmpty, isTrue);
|
||||||
|
expect(filter.activeCount, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a filter with any facet set is not empty', () {
|
||||||
|
expect(const NoteFilter(query: 'x').isEmpty, isFalse);
|
||||||
|
expect(const NoteFilter(statuses: {Status.done}).isEmpty, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('copyWith with no arguments preserves every facet', () {
|
||||||
|
final base = NoteFilter(
|
||||||
|
query: 'milk',
|
||||||
|
priorities: const {Priority.high},
|
||||||
|
statuses: const {Status.todo},
|
||||||
|
createdFrom: DateTime(2026, 1, 1),
|
||||||
|
updatedTo: DateTime(2026, 2, 2),
|
||||||
|
);
|
||||||
|
final clone = base.copyWith();
|
||||||
|
expect(clone.query, base.query);
|
||||||
|
expect(clone.priorities, base.priorities);
|
||||||
|
expect(clone.statuses, base.statuses);
|
||||||
|
expect(clone.createdFrom, base.createdFrom);
|
||||||
|
expect(clone.updatedTo, base.updatedTo);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
31
test/note_repository_helpers.dart
Normal file
31
test/note_repository_helpers.dart
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
/// Shared fixtures for the note_repository test files.
|
||||||
|
///
|
||||||
|
/// `note_repository_test.dart` was split by concern for file size; these are
|
||||||
|
/// the pieces every split needs. Deliberately NOT named `*_test.dart`: the
|
||||||
|
/// runner would collect it and fail on the missing `main()`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
|
||||||
|
/// A note with sensible defaults, timestamped now unless told otherwise.
|
||||||
|
///
|
||||||
|
/// Each test file builds its own notes rather than sharing a corpus, so a
|
||||||
|
/// change to one file's fixtures cannot silently retune another's assertions.
|
||||||
|
Note noteFixture(
|
||||||
|
String id,
|
||||||
|
String text, {
|
||||||
|
Priority priority = Priority.medium,
|
||||||
|
Status status = Status.todo,
|
||||||
|
DateTime? createdAt,
|
||||||
|
DateTime? updatedAt,
|
||||||
|
}) {
|
||||||
|
final now = DateTime.now();
|
||||||
|
return Note(
|
||||||
|
id: id,
|
||||||
|
text: text,
|
||||||
|
priority: priority,
|
||||||
|
status: status,
|
||||||
|
createdAt: createdAt ?? now,
|
||||||
|
updatedAt: updatedAt ?? now,
|
||||||
|
);
|
||||||
|
}
|
||||||
182
test/note_repository_migration_test.dart
Normal file
182
test/note_repository_migration_test.dart
Normal file
@ -0,0 +1,182 @@
|
|||||||
|
/// Schema migrations from the legacy sqlite_crdt database.
|
||||||
|
///
|
||||||
|
/// One of four files `note_repository_test.dart` was split into for the
|
||||||
|
/// 250-line cap. Each carries its own `setUpAll(sqfliteFfiInit)`: without it
|
||||||
|
/// sqflite is never initialised and every test in the file fails.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||||
|
// SqliteCrdt is needed to seed the legacy DB in migration tests; hide its Hlc
|
||||||
|
// so the crdt_sync Hlc/Record are unambiguous.
|
||||||
|
import 'package:sqlite_crdt/sqlite_crdt.dart' hide Hlc;
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/data/repository_factory_io.dart';
|
||||||
|
|
||||||
|
import 'note_repository_helpers.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUpAll(sqfliteFfiInit);
|
||||||
|
|
||||||
|
test('v2→v3 migration backfills priority 0 to medium', () async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
final dir = await Directory.systemTemp.createTemp('todo_migration');
|
||||||
|
final path = '${dir.path}/todo.db';
|
||||||
|
addTearDown(() => dir.delete(recursive: true));
|
||||||
|
|
||||||
|
// Build a v2 database (status column present, no priority backfill) and
|
||||||
|
// insert a legacy note with the old priority 0 ("none").
|
||||||
|
final v2 = await SqliteCrdt.open(
|
||||||
|
path,
|
||||||
|
version: 2,
|
||||||
|
onCreate: (db, version) async {
|
||||||
|
await db.execute('''
|
||||||
|
CREATE TABLE notes (
|
||||||
|
id TEXT NOT NULL,
|
||||||
|
text TEXT NOT NULL DEFAULT '',
|
||||||
|
priority INTEGER NOT NULL DEFAULT 0,
|
||||||
|
status INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
)
|
||||||
|
''');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
final now = DateTime.now().toIso8601String();
|
||||||
|
await v2.execute(
|
||||||
|
'INSERT INTO notes (id, text, priority, status, created_at, updated_at) '
|
||||||
|
'VALUES (?1, ?2, ?3, ?4, ?5, ?6)',
|
||||||
|
['legacy', 'old idea', 0, 0, now, now],
|
||||||
|
);
|
||||||
|
await v2.close();
|
||||||
|
|
||||||
|
// Reopening through the repository runs onUpgrade to v3.
|
||||||
|
final repo = await openRepositoryIn(p.dirname(path));
|
||||||
|
addTearDown(repo.close);
|
||||||
|
final notes = await repo.listNotes();
|
||||||
|
|
||||||
|
expect(notes.single.id, 'legacy');
|
||||||
|
expect(notes.single.priority, Priority.medium);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('v1→v2 migration adds the status column with a default', () async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
final dir = await Directory.systemTemp.createTemp('todo_migration_v1');
|
||||||
|
final path = '${dir.path}/todo.db';
|
||||||
|
addTearDown(() => dir.delete(recursive: true));
|
||||||
|
|
||||||
|
// v1 schema predates the status column entirely.
|
||||||
|
final v1 = await SqliteCrdt.open(
|
||||||
|
path,
|
||||||
|
version: 1,
|
||||||
|
onCreate: (db, version) async {
|
||||||
|
await db.execute('''
|
||||||
|
CREATE TABLE notes (
|
||||||
|
id TEXT NOT NULL,
|
||||||
|
text TEXT NOT NULL DEFAULT '',
|
||||||
|
priority INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
)
|
||||||
|
''');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
final now = DateTime.now().toIso8601String();
|
||||||
|
await v1.execute(
|
||||||
|
'INSERT INTO notes (id, text, priority, created_at, updated_at) '
|
||||||
|
'VALUES (?1, ?2, ?3, ?4, ?5)',
|
||||||
|
['old', 'pre-status idea', 1, now, now],
|
||||||
|
);
|
||||||
|
await v1.close();
|
||||||
|
|
||||||
|
// Reopening runs onUpgrade v1→v2 (adds status, default todo) then v2→v3.
|
||||||
|
final repo = await openRepositoryIn(p.dirname(path));
|
||||||
|
addTearDown(repo.close);
|
||||||
|
final notes = await repo.listNotes();
|
||||||
|
expect(notes.single.id, 'old');
|
||||||
|
expect(notes.single.status, Status.todo); // backfilled default
|
||||||
|
});
|
||||||
|
|
||||||
|
group('migration from a legacy sqlite_crdt database', () {
|
||||||
|
// Writes a v3 legacy DB at [path] with one live note and one tombstone,
|
||||||
|
// exactly as the pre-crdt_sync app would have left it.
|
||||||
|
Future<String> seedLegacyDb(String dir) async {
|
||||||
|
final path = '$dir/todo.db';
|
||||||
|
final legacy = await SqliteCrdt.open(
|
||||||
|
path,
|
||||||
|
version: 3,
|
||||||
|
onCreate: (db, _) async {
|
||||||
|
await db.execute('''
|
||||||
|
CREATE TABLE notes (
|
||||||
|
id TEXT NOT NULL,
|
||||||
|
text TEXT NOT NULL DEFAULT '',
|
||||||
|
priority INTEGER NOT NULL DEFAULT 2,
|
||||||
|
status INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
)
|
||||||
|
''');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
Future<void> insert(String id, String text, int status) => legacy.execute(
|
||||||
|
'INSERT INTO notes (id, text, priority, status, created_at, '
|
||||||
|
'updated_at) VALUES (?1, ?2, 3, ?3, ?4, ?4)',
|
||||||
|
[id, text, status, '2026-01-01T00:00:00.000'],
|
||||||
|
);
|
||||||
|
await insert('live', 'kept idea', Status.inProgress.value);
|
||||||
|
await insert('gone', 'deleted idea', Status.todo.value);
|
||||||
|
await legacy.execute('DELETE FROM notes WHERE id = ?1', ['gone']);
|
||||||
|
await legacy.close();
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('imports live notes and preserves tombstones, once', () async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
final dir = await Directory.systemTemp.createTemp('todo_migrate');
|
||||||
|
addTearDown(() => dir.delete(recursive: true));
|
||||||
|
final path = await seedLegacyDb(dir.path);
|
||||||
|
|
||||||
|
final repo = await openRepositoryIn(p.dirname(path));
|
||||||
|
addTearDown(repo.close);
|
||||||
|
|
||||||
|
// The live note migrated with its fields intact...
|
||||||
|
final notes = await repo.listNotes();
|
||||||
|
expect(notes.map((n) => n.text), ['kept idea']);
|
||||||
|
expect(notes.single.priority, Priority.high);
|
||||||
|
expect(notes.single.status, Status.inProgress);
|
||||||
|
// ...and the deletion carried over as a sticky tombstone.
|
||||||
|
expect(repo.exportLog()['gone']!.deleted, isTrue);
|
||||||
|
expect(repo.nodeId, isNotEmpty);
|
||||||
|
|
||||||
|
// Reopening does not re-run migration: a note added after the first open
|
||||||
|
// survives, and the (still-present) legacy DB is not re-imported.
|
||||||
|
await repo.upsert(noteFixture('new', 'added post-migration'));
|
||||||
|
await repo.close();
|
||||||
|
final reopened = await openRepositoryIn(p.dirname(path));
|
||||||
|
addTearDown(reopened.close);
|
||||||
|
final texts = (await reopened.listNotes()).map((n) => n.text).toSet();
|
||||||
|
expect(texts, {'kept idea', 'added post-migration'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a fresh install with no legacy DB starts empty', () async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
final dir = await Directory.systemTemp.createTemp('todo_fresh');
|
||||||
|
addTearDown(() => dir.delete(recursive: true));
|
||||||
|
|
||||||
|
final repo = await openRepositoryIn(dir.path);
|
||||||
|
addTearDown(repo.close);
|
||||||
|
|
||||||
|
expect(await repo.listNotes(), isEmpty);
|
||||||
|
expect(repo.nodeId, isNotEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
234
test/note_repository_streams_test.dart
Normal file
234
test/note_repository_streams_test.dart
Normal file
@ -0,0 +1,234 @@
|
|||||||
|
/// Import merging, watch streams, and the changes tick.
|
||||||
|
///
|
||||||
|
/// One of four files `note_repository_test.dart` was split into for the
|
||||||
|
/// 250-line cap. Each carries its own `setUpAll(sqfliteFfiInit)`: without it
|
||||||
|
/// sqflite is never initialised and every test in the file fails.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||||
|
// SqliteCrdt is needed to seed the legacy DB in migration tests; hide its Hlc
|
||||||
|
// so the crdt_sync Hlc/Record are unambiguous.
|
||||||
|
import 'package:sqlite_crdt/sqlite_crdt.dart' hide Hlc;
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/data/repository_factory_io.dart';
|
||||||
|
|
||||||
|
import 'note_repository_helpers.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUpAll(sqfliteFfiInit);
|
||||||
|
|
||||||
|
group('importNotes (safe merge)', () {
|
||||||
|
test('restores at the note\'s own edit time, not "now"', () async {
|
||||||
|
// Regression guard. Recovery used to stamp fresh clocks on every
|
||||||
|
// restored note, so a device that recovered from a backup outranked
|
||||||
|
// every other device under per-field last-writer-wins and silently
|
||||||
|
// overwrote newer edits made elsewhere. Observed for real: a restored
|
||||||
|
// desktop rewrote 245 of 330 field clocks to "now".
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
final edited = DateTime(2026, 3, 4, 5, 6, 7);
|
||||||
|
|
||||||
|
await repo.importNotes([
|
||||||
|
noteFixture(
|
||||||
|
'restored',
|
||||||
|
'from a backup',
|
||||||
|
createdAt: edited,
|
||||||
|
updatedAt: edited,
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
|
final field = repo.exportLog()['restored']!.fields['text']!;
|
||||||
|
expect(
|
||||||
|
field.$2.wallTimeMs,
|
||||||
|
edited.millisecondsSinceEpoch,
|
||||||
|
reason:
|
||||||
|
'clock must come from updatedAt so a restore cannot outrank '
|
||||||
|
'genuinely newer data on another device',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('adds notes whose id is not present locally', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await repo.upsert(noteFixture('a', 'local'));
|
||||||
|
|
||||||
|
final outcome = await repo.importNotes([noteFixture('b', 'incoming')]);
|
||||||
|
|
||||||
|
expect(outcome.added, 1);
|
||||||
|
expect(outcome.updated, 0);
|
||||||
|
expect(outcome.skipped, 0);
|
||||||
|
expect((await repo.listNotes()).map((n) => n.id).toSet(), {'a', 'b'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('overwrites a local note only when the import is newer', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
final old = DateTime(2026, 1, 1);
|
||||||
|
final newer = DateTime(2026, 6, 1);
|
||||||
|
await repo.upsert(noteFixture('a', 'local-old', updatedAt: old));
|
||||||
|
|
||||||
|
final outcome = await repo.importNotes([
|
||||||
|
noteFixture('a', 'imported-new', updatedAt: newer),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(outcome.updated, 1);
|
||||||
|
final stored = (await repo.listNotes()).single;
|
||||||
|
expect(stored.text, 'imported-new');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('never clobbers a newer local edit with a stale import', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
final stale = DateTime(2026, 1, 1);
|
||||||
|
final fresh = DateTime(2026, 6, 1);
|
||||||
|
// Local note is the freshly-edited one.
|
||||||
|
await repo.upsert(noteFixture('a', 'local-fresh', updatedAt: fresh));
|
||||||
|
|
||||||
|
final outcome = await repo.importNotes([
|
||||||
|
noteFixture('a', 'backup-stale', updatedAt: stale),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(outcome.skipped, 1);
|
||||||
|
expect(outcome.updated, 0);
|
||||||
|
// The newer local edit survives — "never lose ideas".
|
||||||
|
expect((await repo.listNotes()).single.text, 'local-fresh');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('sorting and streams', () {
|
||||||
|
test('createdDesc and alphabetical orderings', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
final t1 = DateTime(2026, 1, 1);
|
||||||
|
final t2 = DateTime(2026, 2, 1);
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture('a', 'banana', createdAt: t1, updatedAt: t1),
|
||||||
|
);
|
||||||
|
await repo.upsert(
|
||||||
|
noteFixture('b', 'apple', createdAt: t2, updatedAt: t2),
|
||||||
|
);
|
||||||
|
|
||||||
|
final byCreated = await repo.listNotes(sort: NoteSort.createdDesc);
|
||||||
|
expect(byCreated.first.id, 'b'); // newest created first
|
||||||
|
|
||||||
|
final alpha = await repo.listNotes(sort: NoteSort.alphabetical);
|
||||||
|
expect(alpha.map((n) => n.text), ['apple', 'banana']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('watchNotes and watchCount emit current state', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await repo.upsert(noteFixture('a', 'one'));
|
||||||
|
|
||||||
|
expect(await repo.watchNotes().first, hasLength(1));
|
||||||
|
expect(await repo.watchCount().first, 1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('nodeId, log export/import merge and close', () async {
|
||||||
|
// Each openInMemory repo owns its own in-memory log, so two of them model
|
||||||
|
// two independent devices directly.
|
||||||
|
final source = await NoteRepository.openInMemory(nodeId: 'source');
|
||||||
|
final target = await NoteRepository.openInMemory(nodeId: 'target');
|
||||||
|
addTearDown(target.close);
|
||||||
|
|
||||||
|
expect(source.nodeId, 'source');
|
||||||
|
await source.upsert(noteFixture('a', 'shared idea'));
|
||||||
|
final log = source.exportLog();
|
||||||
|
await source.close();
|
||||||
|
|
||||||
|
await target.importLog(log);
|
||||||
|
final merged = await target.listNotes();
|
||||||
|
expect(merged.single.text, 'shared idea');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('watchNotes emits the seed then re-emits after each change', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
final lengths = <int>[];
|
||||||
|
final sub = repo.watchNotes().listen((notes) => lengths.add(notes.length));
|
||||||
|
|
||||||
|
await repo.upsert(noteFixture('a', 'first'));
|
||||||
|
await repo.upsert(noteFixture('b', 'second'));
|
||||||
|
await pumpEventQueue();
|
||||||
|
await sub.cancel();
|
||||||
|
|
||||||
|
expect(lengths.first, 0); // seed
|
||||||
|
expect(lengths.last, 2); // after both writes
|
||||||
|
});
|
||||||
|
|
||||||
|
test('watchCount emits the seed then re-emits after a change', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
final counts = <int>[];
|
||||||
|
final sub = repo.watchCount().listen(counts.add);
|
||||||
|
|
||||||
|
await repo.upsert(noteFixture('a', 'x'));
|
||||||
|
await pumpEventQueue();
|
||||||
|
await sub.cancel();
|
||||||
|
|
||||||
|
expect(counts.first, 0);
|
||||||
|
expect(counts.last, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a foreign record missing timestamps falls back to the epoch', () async {
|
||||||
|
// A note this app writes always has both timestamps; this guards a
|
||||||
|
// malformed record arriving from another device via importLog.
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await repo.importLog({
|
||||||
|
'partial': Record(
|
||||||
|
id: 'partial',
|
||||||
|
fields: {'text': ('no dates', Hlc.newTick('other'))},
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
final only = (await repo.listNotes()).single;
|
||||||
|
expect(only.text, 'no dates');
|
||||||
|
final epoch = DateTime.fromMillisecondsSinceEpoch(0);
|
||||||
|
expect(only.createdAt, epoch);
|
||||||
|
expect(only.updatedAt, epoch);
|
||||||
|
});
|
||||||
|
|
||||||
|
group('changes', () {
|
||||||
|
test('ticks once per write across upsert, delete, and merge', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
var ticks = 0;
|
||||||
|
final sub = repo.changes.listen((_) => ticks++);
|
||||||
|
addTearDown(sub.cancel);
|
||||||
|
|
||||||
|
await repo.upsert(noteFixture('a', 'x'));
|
||||||
|
await repo.delete('a');
|
||||||
|
|
||||||
|
// A log from another device, merged in, must also tick.
|
||||||
|
final other = await NoteRepository.openInMemory(nodeId: 'other');
|
||||||
|
addTearDown(other.close);
|
||||||
|
await other.upsert(noteFixture('b', 'from other'));
|
||||||
|
await repo.importLog(other.exportLog());
|
||||||
|
|
||||||
|
await pumpEventQueue(); // let the broadcast events dispatch
|
||||||
|
expect(ticks, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('importNotes ticks once per note it writes', () async {
|
||||||
|
final repo = await NoteRepository.openInMemory();
|
||||||
|
addTearDown(repo.close);
|
||||||
|
var ticks = 0;
|
||||||
|
final sub = repo.changes.listen((_) => ticks++);
|
||||||
|
addTearDown(sub.cancel);
|
||||||
|
|
||||||
|
await repo.importNotes([noteFixture('a', 'x'), noteFixture('b', 'y')]);
|
||||||
|
|
||||||
|
await pumpEventQueue();
|
||||||
|
expect(ticks, 2); // two new notes → two upserts → two ticks
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -1,677 +0,0 @@
|
|||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
|
||||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
|
||||||
// SqliteCrdt is needed to seed the legacy DB in migration tests; hide its Hlc
|
|
||||||
// so the crdt_sync Hlc/Record are unambiguous.
|
|
||||||
import 'package:sqlite_crdt/sqlite_crdt.dart' hide Hlc;
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
import 'package:todo/data/note_repository.dart';
|
|
||||||
import 'package:todo/data/repository_factory_io.dart';
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
setUpAll(sqfliteFfiInit);
|
|
||||||
|
|
||||||
Note note(
|
|
||||||
String id,
|
|
||||||
String text, {
|
|
||||||
Priority priority = Priority.medium,
|
|
||||||
Status status = Status.todo,
|
|
||||||
DateTime? createdAt,
|
|
||||||
DateTime? updatedAt,
|
|
||||||
}) {
|
|
||||||
final now = DateTime.now();
|
|
||||||
return Note(
|
|
||||||
id: id,
|
|
||||||
text: text,
|
|
||||||
priority: priority,
|
|
||||||
status: status,
|
|
||||||
createdAt: createdAt ?? now,
|
|
||||||
updatedAt: updatedAt ?? now,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
test('upsert then list returns the note', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
|
|
||||||
await repo.upsert(note('a', 'first idea'));
|
|
||||||
final notes = await repo.listNotes();
|
|
||||||
|
|
||||||
expect(notes, hasLength(1));
|
|
||||||
expect(notes.single.text, 'first idea');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('deleted notes are excluded from reads (tombstone filter)', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
|
|
||||||
await repo.upsert(note('a', 'keep me'));
|
|
||||||
await repo.upsert(note('b', 'delete me'));
|
|
||||||
await repo.delete('b');
|
|
||||||
|
|
||||||
final notes = await repo.listNotes();
|
|
||||||
expect(notes, hasLength(1));
|
|
||||||
expect(notes.single.text, 'keep me');
|
|
||||||
|
|
||||||
// The tombstone must survive in the exported log so the deletion syncs.
|
|
||||||
final log = repo.exportLog();
|
|
||||||
expect(log['b']!.deleted, isTrue);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('modifiedDesc sort orders most-recently-updated first', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
|
|
||||||
await repo.upsert(note('a', 'older', updatedAt: DateTime(2026)));
|
|
||||||
await repo.upsert(note('b', 'newer', updatedAt: DateTime(2026, 6)));
|
|
||||||
|
|
||||||
final notes = await repo.listNotes(sort: NoteSort.modifiedDesc);
|
|
||||||
expect(notes.map((n) => n.text), ['newer', 'older']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('priority sort orders highest first', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
|
|
||||||
await repo.upsert(note('a', 'low', priority: Priority.low));
|
|
||||||
await repo.upsert(note('b', 'high', priority: Priority.high));
|
|
||||||
|
|
||||||
final notes = await repo.listNotes(sort: NoteSort.priorityDesc);
|
|
||||||
expect(notes.first.text, 'high');
|
|
||||||
expect(notes.last.text, 'low');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('priority sort breaks ties by most-recently-updated', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
|
|
||||||
await repo.upsert(
|
|
||||||
note('a', 'older', priority: Priority.high, updatedAt: DateTime(2026)),
|
|
||||||
);
|
|
||||||
await repo.upsert(
|
|
||||||
note('b', 'newer', priority: Priority.high, updatedAt: DateTime(2026, 6)),
|
|
||||||
);
|
|
||||||
|
|
||||||
final notes = await repo.listNotes(sort: NoteSort.priorityDesc);
|
|
||||||
expect(notes.map((n) => n.text), ['newer', 'older']);
|
|
||||||
});
|
|
||||||
|
|
||||||
group('text search', () {
|
|
||||||
test('matches a case-insensitive substring', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await repo.upsert(note('a', 'Buy MILK and eggs'));
|
|
||||||
await repo.upsert(note('b', 'call the dentist'));
|
|
||||||
|
|
||||||
final notes = await repo.listNotes(
|
|
||||||
filter: const NoteFilter(query: 'milk'),
|
|
||||||
);
|
|
||||||
expect(notes.map((n) => n.id), ['a']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('escapes LIKE wildcards so % is matched literally', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await repo.upsert(note('pct', 'a%b'));
|
|
||||||
await repo.upsert(note('plain', 'axb'));
|
|
||||||
|
|
||||||
// Without escaping, 'a%b' as a LIKE pattern would also match 'axb'.
|
|
||||||
final notes = await repo.listNotes(
|
|
||||||
filter: const NoteFilter(query: 'a%b'),
|
|
||||||
);
|
|
||||||
expect(notes.map((n) => n.id), ['pct']);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('attribute filters', () {
|
|
||||||
test('priority filter includes only the selected priorities', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await repo.upsert(note('lo', 'l', priority: Priority.low));
|
|
||||||
await repo.upsert(note('me', 'm', priority: Priority.medium));
|
|
||||||
await repo.upsert(note('hi', 'h', priority: Priority.high));
|
|
||||||
|
|
||||||
final notes = await repo.listNotes(
|
|
||||||
filter: const NoteFilter(priorities: {Priority.low, Priority.high}),
|
|
||||||
);
|
|
||||||
expect(notes.map((n) => n.id).toSet(), {'lo', 'hi'});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('status filter includes only the selected statuses', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await repo.upsert(note('t', 'todo', status: Status.todo));
|
|
||||||
await repo.upsert(note('d', 'done', status: Status.done));
|
|
||||||
await repo.upsert(note('x', 'gone', status: Status.abandoned));
|
|
||||||
|
|
||||||
final notes = await repo.listNotes(
|
|
||||||
filter: const NoteFilter(statuses: {Status.todo, Status.inProgress}),
|
|
||||||
);
|
|
||||||
expect(notes.map((n) => n.id), ['t']);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('date range filters', () {
|
|
||||||
final jan = DateTime(2026, 1, 15, 10);
|
|
||||||
final jun = DateTime(2026, 6, 15, 10);
|
|
||||||
|
|
||||||
test('created range bounds are inclusive by calendar day', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await repo.upsert(note('j', 'jan', createdAt: jan, updatedAt: jan));
|
|
||||||
await repo.upsert(note('u', 'jun', createdAt: jun, updatedAt: jun));
|
|
||||||
|
|
||||||
// A single-day range on Jan 15 includes the 10:00 note that day.
|
|
||||||
final notes = await repo.listNotes(
|
|
||||||
filter: NoteFilter(
|
|
||||||
createdFrom: DateTime(2026, 1, 15),
|
|
||||||
createdTo: DateTime(2026, 1, 15),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(notes.map((n) => n.id), ['j']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('created and updated ranges apply independently', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
// Created in Jan, but last updated in Jun.
|
|
||||||
await repo.upsert(
|
|
||||||
note('e', 'edited later', createdAt: jan, updatedAt: jun),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Matches on the updated range...
|
|
||||||
final byUpdated = await repo.listNotes(
|
|
||||||
filter: NoteFilter(
|
|
||||||
updatedFrom: DateTime(2026, 6, 1),
|
|
||||||
updatedTo: DateTime(2026, 6, 30),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(byUpdated.map((n) => n.id), ['e']);
|
|
||||||
|
|
||||||
// ...but not when the created range excludes January.
|
|
||||||
final byCreated = await repo.listNotes(
|
|
||||||
filter: NoteFilter(
|
|
||||||
createdFrom: DateTime(2026, 6, 1),
|
|
||||||
createdTo: DateTime(2026, 6, 30),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(byCreated, isEmpty);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('filters combine with AND', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await repo.upsert(
|
|
||||||
note(
|
|
||||||
'match',
|
|
||||||
'urgent report',
|
|
||||||
priority: Priority.high,
|
|
||||||
status: Status.inProgress,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await repo.upsert(
|
|
||||||
note(
|
|
||||||
'wrongPrio',
|
|
||||||
'urgent report',
|
|
||||||
priority: Priority.low,
|
|
||||||
status: Status.inProgress,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await repo.upsert(
|
|
||||||
note(
|
|
||||||
'wrongText',
|
|
||||||
'casual note',
|
|
||||||
priority: Priority.high,
|
|
||||||
status: Status.inProgress,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
final notes = await repo.listNotes(
|
|
||||||
filter: const NoteFilter(
|
|
||||||
query: 'urgent',
|
|
||||||
priorities: {Priority.high},
|
|
||||||
statuses: {Status.inProgress},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(notes.map((n) => n.id), ['match']);
|
|
||||||
});
|
|
||||||
|
|
||||||
group('priority defaults', () {
|
|
||||||
test('fromValue maps legacy/unknown values to medium', () {
|
|
||||||
expect(Priority.fromValue(0), Priority.medium); // old "none"
|
|
||||||
expect(Priority.fromValue(null), Priority.medium);
|
|
||||||
expect(Priority.fromValue(99), Priority.medium);
|
|
||||||
// Known values still round-trip.
|
|
||||||
expect(Priority.fromValue(1), Priority.low);
|
|
||||||
expect(Priority.fromValue(2), Priority.medium);
|
|
||||||
expect(Priority.fromValue(3), Priority.high);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('importNotes (safe merge)', () {
|
|
||||||
test('restores at the note\'s own edit time, not "now"', () async {
|
|
||||||
// Regression guard. Recovery used to stamp fresh clocks on every
|
|
||||||
// restored note, so a device that recovered from a backup outranked
|
|
||||||
// every other device under per-field last-writer-wins and silently
|
|
||||||
// overwrote newer edits made elsewhere. Observed for real: a restored
|
|
||||||
// desktop rewrote 245 of 330 field clocks to "now".
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
final edited = DateTime(2026, 3, 4, 5, 6, 7);
|
|
||||||
|
|
||||||
await repo.importNotes([
|
|
||||||
note('restored', 'from a backup', createdAt: edited, updatedAt: edited),
|
|
||||||
]);
|
|
||||||
|
|
||||||
final field = repo.exportLog()['restored']!.fields['text']!;
|
|
||||||
expect(
|
|
||||||
field.$2.wallTimeMs,
|
|
||||||
edited.millisecondsSinceEpoch,
|
|
||||||
reason:
|
|
||||||
'clock must come from updatedAt so a restore cannot outrank '
|
|
||||||
'genuinely newer data on another device',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('adds notes whose id is not present locally', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await repo.upsert(note('a', 'local'));
|
|
||||||
|
|
||||||
final outcome = await repo.importNotes([note('b', 'incoming')]);
|
|
||||||
|
|
||||||
expect(outcome.added, 1);
|
|
||||||
expect(outcome.updated, 0);
|
|
||||||
expect(outcome.skipped, 0);
|
|
||||||
expect((await repo.listNotes()).map((n) => n.id).toSet(), {'a', 'b'});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('overwrites a local note only when the import is newer', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
final old = DateTime(2026, 1, 1);
|
|
||||||
final newer = DateTime(2026, 6, 1);
|
|
||||||
await repo.upsert(note('a', 'local-old', updatedAt: old));
|
|
||||||
|
|
||||||
final outcome = await repo.importNotes([
|
|
||||||
note('a', 'imported-new', updatedAt: newer),
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(outcome.updated, 1);
|
|
||||||
final stored = (await repo.listNotes()).single;
|
|
||||||
expect(stored.text, 'imported-new');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('never clobbers a newer local edit with a stale import', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
final stale = DateTime(2026, 1, 1);
|
|
||||||
final fresh = DateTime(2026, 6, 1);
|
|
||||||
// Local note is the freshly-edited one.
|
|
||||||
await repo.upsert(note('a', 'local-fresh', updatedAt: fresh));
|
|
||||||
|
|
||||||
final outcome = await repo.importNotes([
|
|
||||||
note('a', 'backup-stale', updatedAt: stale),
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(outcome.skipped, 1);
|
|
||||||
expect(outcome.updated, 0);
|
|
||||||
// The newer local edit survives — "never lose ideas".
|
|
||||||
expect((await repo.listNotes()).single.text, 'local-fresh');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('v2→v3 migration backfills priority 0 to medium', () async {
|
|
||||||
SharedPreferences.setMockInitialValues({});
|
|
||||||
final dir = await Directory.systemTemp.createTemp('todo_migration');
|
|
||||||
final path = '${dir.path}/todo.db';
|
|
||||||
addTearDown(() => dir.delete(recursive: true));
|
|
||||||
|
|
||||||
// Build a v2 database (status column present, no priority backfill) and
|
|
||||||
// insert a legacy note with the old priority 0 ("none").
|
|
||||||
final v2 = await SqliteCrdt.open(
|
|
||||||
path,
|
|
||||||
version: 2,
|
|
||||||
onCreate: (db, version) async {
|
|
||||||
await db.execute('''
|
|
||||||
CREATE TABLE notes (
|
|
||||||
id TEXT NOT NULL,
|
|
||||||
text TEXT NOT NULL DEFAULT '',
|
|
||||||
priority INTEGER NOT NULL DEFAULT 0,
|
|
||||||
status INTEGER NOT NULL DEFAULT 0,
|
|
||||||
created_at TEXT NOT NULL,
|
|
||||||
updated_at TEXT NOT NULL,
|
|
||||||
PRIMARY KEY (id)
|
|
||||||
)
|
|
||||||
''');
|
|
||||||
},
|
|
||||||
);
|
|
||||||
final now = DateTime.now().toIso8601String();
|
|
||||||
await v2.execute(
|
|
||||||
'INSERT INTO notes (id, text, priority, status, created_at, updated_at) '
|
|
||||||
'VALUES (?1, ?2, ?3, ?4, ?5, ?6)',
|
|
||||||
['legacy', 'old idea', 0, 0, now, now],
|
|
||||||
);
|
|
||||||
await v2.close();
|
|
||||||
|
|
||||||
// Reopening through the repository runs onUpgrade to v3.
|
|
||||||
final repo = await openRepositoryIn(p.dirname(path));
|
|
||||||
addTearDown(repo.close);
|
|
||||||
final notes = await repo.listNotes();
|
|
||||||
|
|
||||||
expect(notes.single.id, 'legacy');
|
|
||||||
expect(notes.single.priority, Priority.medium);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('v1→v2 migration adds the status column with a default', () async {
|
|
||||||
SharedPreferences.setMockInitialValues({});
|
|
||||||
final dir = await Directory.systemTemp.createTemp('todo_migration_v1');
|
|
||||||
final path = '${dir.path}/todo.db';
|
|
||||||
addTearDown(() => dir.delete(recursive: true));
|
|
||||||
|
|
||||||
// v1 schema predates the status column entirely.
|
|
||||||
final v1 = await SqliteCrdt.open(
|
|
||||||
path,
|
|
||||||
version: 1,
|
|
||||||
onCreate: (db, version) async {
|
|
||||||
await db.execute('''
|
|
||||||
CREATE TABLE notes (
|
|
||||||
id TEXT NOT NULL,
|
|
||||||
text TEXT NOT NULL DEFAULT '',
|
|
||||||
priority INTEGER NOT NULL DEFAULT 0,
|
|
||||||
created_at TEXT NOT NULL,
|
|
||||||
updated_at TEXT NOT NULL,
|
|
||||||
PRIMARY KEY (id)
|
|
||||||
)
|
|
||||||
''');
|
|
||||||
},
|
|
||||||
);
|
|
||||||
final now = DateTime.now().toIso8601String();
|
|
||||||
await v1.execute(
|
|
||||||
'INSERT INTO notes (id, text, priority, created_at, updated_at) '
|
|
||||||
'VALUES (?1, ?2, ?3, ?4, ?5)',
|
|
||||||
['old', 'pre-status idea', 1, now, now],
|
|
||||||
);
|
|
||||||
await v1.close();
|
|
||||||
|
|
||||||
// Reopening runs onUpgrade v1→v2 (adds status, default todo) then v2→v3.
|
|
||||||
final repo = await openRepositoryIn(p.dirname(path));
|
|
||||||
addTearDown(repo.close);
|
|
||||||
final notes = await repo.listNotes();
|
|
||||||
expect(notes.single.id, 'old');
|
|
||||||
expect(notes.single.status, Status.todo); // backfilled default
|
|
||||||
});
|
|
||||||
|
|
||||||
group('sorting and streams', () {
|
|
||||||
test('createdDesc and alphabetical orderings', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
final t1 = DateTime(2026, 1, 1);
|
|
||||||
final t2 = DateTime(2026, 2, 1);
|
|
||||||
await repo.upsert(note('a', 'banana', createdAt: t1, updatedAt: t1));
|
|
||||||
await repo.upsert(note('b', 'apple', createdAt: t2, updatedAt: t2));
|
|
||||||
|
|
||||||
final byCreated = await repo.listNotes(sort: NoteSort.createdDesc);
|
|
||||||
expect(byCreated.first.id, 'b'); // newest created first
|
|
||||||
|
|
||||||
final alpha = await repo.listNotes(sort: NoteSort.alphabetical);
|
|
||||||
expect(alpha.map((n) => n.text), ['apple', 'banana']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('watchNotes and watchCount emit current state', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await repo.upsert(note('a', 'one'));
|
|
||||||
|
|
||||||
expect(await repo.watchNotes().first, hasLength(1));
|
|
||||||
expect(await repo.watchCount().first, 1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('nodeId, log export/import merge and close', () async {
|
|
||||||
// Each openInMemory repo owns its own in-memory log, so two of them model
|
|
||||||
// two independent devices directly.
|
|
||||||
final source = await NoteRepository.openInMemory(nodeId: 'source');
|
|
||||||
final target = await NoteRepository.openInMemory(nodeId: 'target');
|
|
||||||
addTearDown(target.close);
|
|
||||||
|
|
||||||
expect(source.nodeId, 'source');
|
|
||||||
await source.upsert(note('a', 'shared idea'));
|
|
||||||
final log = source.exportLog();
|
|
||||||
await source.close();
|
|
||||||
|
|
||||||
await target.importLog(log);
|
|
||||||
final merged = await target.listNotes();
|
|
||||||
expect(merged.single.text, 'shared idea');
|
|
||||||
});
|
|
||||||
|
|
||||||
group('migration from a legacy sqlite_crdt database', () {
|
|
||||||
// Writes a v3 legacy DB at [path] with one live note and one tombstone,
|
|
||||||
// exactly as the pre-crdt_sync app would have left it.
|
|
||||||
Future<String> seedLegacyDb(String dir) async {
|
|
||||||
final path = '$dir/todo.db';
|
|
||||||
final legacy = await SqliteCrdt.open(
|
|
||||||
path,
|
|
||||||
version: 3,
|
|
||||||
onCreate: (db, _) async {
|
|
||||||
await db.execute('''
|
|
||||||
CREATE TABLE notes (
|
|
||||||
id TEXT NOT NULL,
|
|
||||||
text TEXT NOT NULL DEFAULT '',
|
|
||||||
priority INTEGER NOT NULL DEFAULT 2,
|
|
||||||
status INTEGER NOT NULL DEFAULT 0,
|
|
||||||
created_at TEXT NOT NULL,
|
|
||||||
updated_at TEXT NOT NULL,
|
|
||||||
PRIMARY KEY (id)
|
|
||||||
)
|
|
||||||
''');
|
|
||||||
},
|
|
||||||
);
|
|
||||||
Future<void> insert(String id, String text, int status) => legacy.execute(
|
|
||||||
'INSERT INTO notes (id, text, priority, status, created_at, '
|
|
||||||
'updated_at) VALUES (?1, ?2, 3, ?3, ?4, ?4)',
|
|
||||||
[id, text, status, '2026-01-01T00:00:00.000'],
|
|
||||||
);
|
|
||||||
await insert('live', 'kept idea', Status.inProgress.value);
|
|
||||||
await insert('gone', 'deleted idea', Status.todo.value);
|
|
||||||
await legacy.execute('DELETE FROM notes WHERE id = ?1', ['gone']);
|
|
||||||
await legacy.close();
|
|
||||||
return path;
|
|
||||||
}
|
|
||||||
|
|
||||||
test('imports live notes and preserves tombstones, once', () async {
|
|
||||||
SharedPreferences.setMockInitialValues({});
|
|
||||||
final dir = await Directory.systemTemp.createTemp('todo_migrate');
|
|
||||||
addTearDown(() => dir.delete(recursive: true));
|
|
||||||
final path = await seedLegacyDb(dir.path);
|
|
||||||
|
|
||||||
final repo = await openRepositoryIn(p.dirname(path));
|
|
||||||
addTearDown(repo.close);
|
|
||||||
|
|
||||||
// The live note migrated with its fields intact...
|
|
||||||
final notes = await repo.listNotes();
|
|
||||||
expect(notes.map((n) => n.text), ['kept idea']);
|
|
||||||
expect(notes.single.priority, Priority.high);
|
|
||||||
expect(notes.single.status, Status.inProgress);
|
|
||||||
// ...and the deletion carried over as a sticky tombstone.
|
|
||||||
expect(repo.exportLog()['gone']!.deleted, isTrue);
|
|
||||||
expect(repo.nodeId, isNotEmpty);
|
|
||||||
|
|
||||||
// Reopening does not re-run migration: a note added after the first open
|
|
||||||
// survives, and the (still-present) legacy DB is not re-imported.
|
|
||||||
await repo.upsert(note('new', 'added post-migration'));
|
|
||||||
await repo.close();
|
|
||||||
final reopened = await openRepositoryIn(p.dirname(path));
|
|
||||||
addTearDown(reopened.close);
|
|
||||||
final texts = (await reopened.listNotes()).map((n) => n.text).toSet();
|
|
||||||
expect(texts, {'kept idea', 'added post-migration'});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a fresh install with no legacy DB starts empty', () async {
|
|
||||||
SharedPreferences.setMockInitialValues({});
|
|
||||||
final dir = await Directory.systemTemp.createTemp('todo_fresh');
|
|
||||||
addTearDown(() => dir.delete(recursive: true));
|
|
||||||
|
|
||||||
final repo = await openRepositoryIn(dir.path);
|
|
||||||
addTearDown(repo.close);
|
|
||||||
|
|
||||||
expect(await repo.listNotes(), isEmpty);
|
|
||||||
expect(repo.nodeId, isNotEmpty);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('watchNotes emits the seed then re-emits after each change', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
final lengths = <int>[];
|
|
||||||
final sub = repo.watchNotes().listen((notes) => lengths.add(notes.length));
|
|
||||||
|
|
||||||
await repo.upsert(note('a', 'first'));
|
|
||||||
await repo.upsert(note('b', 'second'));
|
|
||||||
await pumpEventQueue();
|
|
||||||
await sub.cancel();
|
|
||||||
|
|
||||||
expect(lengths.first, 0); // seed
|
|
||||||
expect(lengths.last, 2); // after both writes
|
|
||||||
});
|
|
||||||
|
|
||||||
test('watchCount emits the seed then re-emits after a change', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
final counts = <int>[];
|
|
||||||
final sub = repo.watchCount().listen(counts.add);
|
|
||||||
|
|
||||||
await repo.upsert(note('a', 'x'));
|
|
||||||
await pumpEventQueue();
|
|
||||||
await sub.cancel();
|
|
||||||
|
|
||||||
expect(counts.first, 0);
|
|
||||||
expect(counts.last, 1);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a foreign record missing timestamps falls back to the epoch', () async {
|
|
||||||
// A note this app writes always has both timestamps; this guards a
|
|
||||||
// malformed record arriving from another device via importLog.
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await repo.importLog({
|
|
||||||
'partial': Record(
|
|
||||||
id: 'partial',
|
|
||||||
fields: {'text': ('no dates', Hlc.newTick('other'))},
|
|
||||||
),
|
|
||||||
});
|
|
||||||
|
|
||||||
final only = (await repo.listNotes()).single;
|
|
||||||
expect(only.text, 'no dates');
|
|
||||||
final epoch = DateTime.fromMillisecondsSinceEpoch(0);
|
|
||||||
expect(only.createdAt, epoch);
|
|
||||||
expect(only.updatedAt, epoch);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('date-range filters bound by whole calendar days', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await repo.upsert(
|
|
||||||
note(
|
|
||||||
'jan',
|
|
||||||
'january idea',
|
|
||||||
createdAt: DateTime(2026, 1, 10),
|
|
||||||
updatedAt: DateTime(2026, 1, 10),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await repo.upsert(
|
|
||||||
note(
|
|
||||||
'mar',
|
|
||||||
'march idea',
|
|
||||||
createdAt: DateTime(2026, 3, 10),
|
|
||||||
updatedAt: DateTime(2026, 3, 10),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
final byCreated = await repo.listNotes(
|
|
||||||
filter: NoteFilter(
|
|
||||||
createdFrom: DateTime(2026, 2, 1),
|
|
||||||
createdTo: DateTime(2026, 4, 1),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(byCreated.map((n) => n.text), ['march idea']);
|
|
||||||
|
|
||||||
final byUpdated = await repo.listNotes(
|
|
||||||
filter: NoteFilter(
|
|
||||||
updatedFrom: DateTime(2026, 1, 1),
|
|
||||||
updatedTo: DateTime(2026, 1, 31),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(byUpdated.map((n) => n.text), ['january idea']);
|
|
||||||
});
|
|
||||||
|
|
||||||
group('NoteFilter', () {
|
|
||||||
test('a default filter is empty (all facets cleared)', () {
|
|
||||||
// Evaluates the full conjunction in `isEmpty`, including the date bounds.
|
|
||||||
const filter = NoteFilter();
|
|
||||||
expect(filter.isEmpty, isTrue);
|
|
||||||
expect(filter.activeCount, 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a filter with any facet set is not empty', () {
|
|
||||||
expect(const NoteFilter(query: 'x').isEmpty, isFalse);
|
|
||||||
expect(const NoteFilter(statuses: {Status.done}).isEmpty, isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('copyWith with no arguments preserves every facet', () {
|
|
||||||
final base = NoteFilter(
|
|
||||||
query: 'milk',
|
|
||||||
priorities: const {Priority.high},
|
|
||||||
statuses: const {Status.todo},
|
|
||||||
createdFrom: DateTime(2026, 1, 1),
|
|
||||||
updatedTo: DateTime(2026, 2, 2),
|
|
||||||
);
|
|
||||||
final clone = base.copyWith();
|
|
||||||
expect(clone.query, base.query);
|
|
||||||
expect(clone.priorities, base.priorities);
|
|
||||||
expect(clone.statuses, base.statuses);
|
|
||||||
expect(clone.createdFrom, base.createdFrom);
|
|
||||||
expect(clone.updatedTo, base.updatedTo);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('changes', () {
|
|
||||||
test('ticks once per write across upsert, delete, and merge', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
var ticks = 0;
|
|
||||||
final sub = repo.changes.listen((_) => ticks++);
|
|
||||||
addTearDown(sub.cancel);
|
|
||||||
|
|
||||||
await repo.upsert(note('a', 'x'));
|
|
||||||
await repo.delete('a');
|
|
||||||
|
|
||||||
// A log from another device, merged in, must also tick.
|
|
||||||
final other = await NoteRepository.openInMemory(nodeId: 'other');
|
|
||||||
addTearDown(other.close);
|
|
||||||
await other.upsert(note('b', 'from other'));
|
|
||||||
await repo.importLog(other.exportLog());
|
|
||||||
|
|
||||||
await pumpEventQueue(); // let the broadcast events dispatch
|
|
||||||
expect(ticks, 3);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('importNotes ticks once per note it writes', () async {
|
|
||||||
final repo = await NoteRepository.openInMemory();
|
|
||||||
addTearDown(repo.close);
|
|
||||||
var ticks = 0;
|
|
||||||
final sub = repo.changes.listen((_) => ticks++);
|
|
||||||
addTearDown(sub.cancel);
|
|
||||||
|
|
||||||
await repo.importNotes([note('a', 'x'), note('b', 'y')]);
|
|
||||||
|
|
||||||
await pumpEventQueue();
|
|
||||||
expect(ticks, 2); // two new notes → two upserts → two ticks
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
203
test/notes_list_filter_test.dart
Normal file
203
test/notes_list_filter_test.dart
Normal file
@ -0,0 +1,203 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/ui/notes_list_screen.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
|
||||||
|
import 'notes_list_harness.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('a Created date preset sets a created range on the filter', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
||||||
|
|
||||||
|
await tester.tap(find.byIcon(Icons.filter_list));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
// "Today" appears under both Created and Last-updated; the first is
|
||||||
|
// Created.
|
||||||
|
await tester.tap(find.text('Today').first);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(find.text('Apply'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
|
expect(repo.lastFilter!.createdFrom, isNotNull);
|
||||||
|
expect(repo.lastFilter!.createdTo, isNotNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('clearing the search box resets the query', (tester) async {
|
||||||
|
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
||||||
|
|
||||||
|
await tester.enterText(find.byType(TextField), 'foo');
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
expect(repo.lastFilter!.query, 'foo');
|
||||||
|
|
||||||
|
await tester.tap(find.byIcon(Icons.clear));
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
|
expect(repo.lastFilter!.query, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('renders relative-time labels for varied ages', (tester) async {
|
||||||
|
final now = DateTime.now();
|
||||||
|
Note aged(String id, Duration ago) => Note(
|
||||||
|
id: id,
|
||||||
|
text: 'note $id',
|
||||||
|
priority: Priority.medium,
|
||||||
|
status: Status.todo,
|
||||||
|
createdAt: now.subtract(ago),
|
||||||
|
updatedAt: now.subtract(ago),
|
||||||
|
);
|
||||||
|
await pumpList(
|
||||||
|
tester,
|
||||||
|
seed: [
|
||||||
|
aged('s', const Duration(seconds: 10)),
|
||||||
|
aged('m', const Duration(minutes: 5)),
|
||||||
|
aged('h', const Duration(hours: 2)),
|
||||||
|
aged('d', const Duration(days: 3)),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(find.textContaining('just now'), findsOneWidget);
|
||||||
|
expect(find.textContaining('5m ago'), findsOneWidget);
|
||||||
|
expect(find.textContaining('2h ago'), findsOneWidget);
|
||||||
|
expect(find.textContaining('3d ago'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Clear all resets the filter sheet to the default', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
||||||
|
|
||||||
|
await tester.tap(find.byIcon(Icons.filter_list));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
await tester.tap(find.text('Done')); // add a non-default status
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(find.text('Clear all'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(find.text('Apply'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
|
expect(repo.lastFilter!.statuses, {Status.todo, Status.inProgress});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a date range can be set then cleared with Any', (tester) async {
|
||||||
|
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
||||||
|
|
||||||
|
await tester.tap(find.byIcon(Icons.filter_list));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
await tester.tap(find.text('7 days').first); // Created: last 7 days
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(find.text('Any').first); // clear that range
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(find.text('Apply'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
|
expect(repo.lastFilter!.createdFrom, isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Custom… opens the range picker (cancel keeps no range)', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
||||||
|
|
||||||
|
await tester.tap(find.byIcon(Icons.filter_list));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
await tester.tap(find.text('Custom…').first);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300)); // picker opens
|
||||||
|
// The full-screen range picker dismisses via a close icon, not a label.
|
||||||
|
await tester.tap(find.byIcon(Icons.close));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
|
await tester.tap(find.text('Apply'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
|
expect(repo.lastFilter!.createdFrom, isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('filter sheet toggles a priority and a Last-updated preset', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
||||||
|
|
||||||
|
await tester.tap(find.byIcon(Icons.filter_list));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
|
await tester.tap(find.text('High')); // priority chip toggle
|
||||||
|
// Second "Today" belongs to the Last-updated section.
|
||||||
|
await tester.tap(find.text('Today').last);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(find.text('Apply'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
|
expect(repo.lastFilter!.priorities, contains(Priority.high));
|
||||||
|
expect(repo.lastFilter!.updatedFrom, isNotNull);
|
||||||
|
expect(repo.lastFilter!.updatedTo, isNotNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a 30-day preset then Custom… confirms the seeded range', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
||||||
|
|
||||||
|
await tester.tap(find.byIcon(Icons.filter_list));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
|
await tester.tap(find.text('30 days').first); // _applyDays(30)
|
||||||
|
await tester.pump();
|
||||||
|
// Custom… opens the range picker seeded with the 30-day range
|
||||||
|
// (initialDateRange != null); confirming with Save returns that range.
|
||||||
|
await tester.tap(find.text('Custom…').first);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300)); // picker opens
|
||||||
|
await tester.tap(find.text('Save'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
await tester.tap(find.text('Apply'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
|
expect(repo.lastFilter!.createdFrom, isNotNull);
|
||||||
|
expect(repo.lastFilter!.createdTo, isNotNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('per-note sheet changes priority via a chip', (tester) async {
|
||||||
|
final repo = await pumpList(tester, seed: [note('a', 'Repriortise me')]);
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Quick actions'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
await tester.tap(find.text('Low')); // default is Medium → change to Low
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect((await repo.listNotes()).single.priority, Priority.low);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('tapping a note opens the detail screen', (tester) async {
|
||||||
|
await pumpList(tester, seed: [note('a', '# Open me\n\nbody')]);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Open me'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 300)); // route transition
|
||||||
|
|
||||||
|
// The detail screen shows the note title in its app bar plus the
|
||||||
|
// Priority/Status meta dropdowns and the editor mode toggle.
|
||||||
|
expect(find.text('Priority'), findsOneWidget);
|
||||||
|
expect(find.text('View'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
44
test/notes_list_harness.dart
Normal file
44
test/notes_list_harness.dart
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
/// The shared pumpList harness and its fixed-clock note fixture.
|
||||||
|
///
|
||||||
|
/// Shared by the files `notes_list_screen_test.dart` was split into for the
|
||||||
|
/// 250-line cap. Deliberately NOT named `*_test.dart`: the runner would
|
||||||
|
/// collect it and fail on the missing `main()`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/ui/notes_list_screen.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
|
||||||
|
Note note(
|
||||||
|
String id,
|
||||||
|
String text, {
|
||||||
|
Priority priority = Priority.medium,
|
||||||
|
Status status = Status.todo,
|
||||||
|
}) {
|
||||||
|
final now = DateTime(2026, 6, 15, 9);
|
||||||
|
return Note(
|
||||||
|
id: id,
|
||||||
|
text: text,
|
||||||
|
priority: priority,
|
||||||
|
status: status,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<FakeNoteRepository> pumpList(
|
||||||
|
WidgetTester tester, {
|
||||||
|
List<Note> seed = const [],
|
||||||
|
}) async {
|
||||||
|
final repo = FakeNoteRepository(seed);
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(home: NotesListScreen(repository: repo)),
|
||||||
|
);
|
||||||
|
await tester.pump(); // flush the initial stream emit
|
||||||
|
return repo;
|
||||||
|
}
|
||||||
@ -6,37 +6,9 @@ import 'package:todo/ui/notes_list_screen.dart';
|
|||||||
|
|
||||||
import 'fake_note_repository.dart';
|
import 'fake_note_repository.dart';
|
||||||
|
|
||||||
|
import 'notes_list_harness.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
Note note(
|
|
||||||
String id,
|
|
||||||
String text, {
|
|
||||||
Priority priority = Priority.medium,
|
|
||||||
Status status = Status.todo,
|
|
||||||
}) {
|
|
||||||
final now = DateTime(2026, 6, 15, 9);
|
|
||||||
return Note(
|
|
||||||
id: id,
|
|
||||||
text: text,
|
|
||||||
priority: priority,
|
|
||||||
status: status,
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<FakeNoteRepository> pumpList(
|
|
||||||
WidgetTester tester, {
|
|
||||||
List<Note> seed = const [],
|
|
||||||
}) async {
|
|
||||||
final repo = FakeNoteRepository(seed);
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(home: NotesListScreen(repository: repo)),
|
|
||||||
);
|
|
||||||
await tester.pump(); // flush the initial stream emit
|
|
||||||
return repo;
|
|
||||||
}
|
|
||||||
|
|
||||||
testWidgets('renders notes with a status · priority · time subtitle', (
|
testWidgets('renders notes with a status · priority · time subtitle', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
@ -152,196 +124,4 @@ void main() {
|
|||||||
// variant rather than "No notes yet" — either way, an empty message.
|
// variant rather than "No notes yet" — either way, an empty message.
|
||||||
expect(find.textContaining('No notes'), findsOneWidget);
|
expect(find.textContaining('No notes'), findsOneWidget);
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('a Created date preset sets a created range on the filter', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
|
||||||
|
|
||||||
await tester.tap(find.byIcon(Icons.filter_list));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
// "Today" appears under both Created and Last-updated; the first is
|
|
||||||
// Created.
|
|
||||||
await tester.tap(find.text('Today').first);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.tap(find.text('Apply'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
|
|
||||||
expect(repo.lastFilter!.createdFrom, isNotNull);
|
|
||||||
expect(repo.lastFilter!.createdTo, isNotNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('clearing the search box resets the query', (tester) async {
|
|
||||||
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
|
||||||
|
|
||||||
await tester.enterText(find.byType(TextField), 'foo');
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
expect(repo.lastFilter!.query, 'foo');
|
|
||||||
|
|
||||||
await tester.tap(find.byIcon(Icons.clear));
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
|
|
||||||
expect(repo.lastFilter!.query, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('renders relative-time labels for varied ages', (tester) async {
|
|
||||||
final now = DateTime.now();
|
|
||||||
Note aged(String id, Duration ago) => Note(
|
|
||||||
id: id,
|
|
||||||
text: 'note $id',
|
|
||||||
priority: Priority.medium,
|
|
||||||
status: Status.todo,
|
|
||||||
createdAt: now.subtract(ago),
|
|
||||||
updatedAt: now.subtract(ago),
|
|
||||||
);
|
|
||||||
await pumpList(
|
|
||||||
tester,
|
|
||||||
seed: [
|
|
||||||
aged('s', const Duration(seconds: 10)),
|
|
||||||
aged('m', const Duration(minutes: 5)),
|
|
||||||
aged('h', const Duration(hours: 2)),
|
|
||||||
aged('d', const Duration(days: 3)),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(find.textContaining('just now'), findsOneWidget);
|
|
||||||
expect(find.textContaining('5m ago'), findsOneWidget);
|
|
||||||
expect(find.textContaining('2h ago'), findsOneWidget);
|
|
||||||
expect(find.textContaining('3d ago'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Clear all resets the filter sheet to the default', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
|
||||||
|
|
||||||
await tester.tap(find.byIcon(Icons.filter_list));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
await tester.tap(find.text('Done')); // add a non-default status
|
|
||||||
await tester.pump();
|
|
||||||
await tester.tap(find.text('Clear all'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.tap(find.text('Apply'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
|
|
||||||
expect(repo.lastFilter!.statuses, {Status.todo, Status.inProgress});
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('a date range can be set then cleared with Any', (tester) async {
|
|
||||||
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
|
||||||
|
|
||||||
await tester.tap(find.byIcon(Icons.filter_list));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
await tester.tap(find.text('7 days').first); // Created: last 7 days
|
|
||||||
await tester.pump();
|
|
||||||
await tester.tap(find.text('Any').first); // clear that range
|
|
||||||
await tester.pump();
|
|
||||||
await tester.tap(find.text('Apply'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
|
|
||||||
expect(repo.lastFilter!.createdFrom, isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Custom… opens the range picker (cancel keeps no range)', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
|
||||||
|
|
||||||
await tester.tap(find.byIcon(Icons.filter_list));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
await tester.tap(find.text('Custom…').first);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300)); // picker opens
|
|
||||||
// The full-screen range picker dismisses via a close icon, not a label.
|
|
||||||
await tester.tap(find.byIcon(Icons.close));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
|
|
||||||
await tester.tap(find.text('Apply'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
|
|
||||||
expect(repo.lastFilter!.createdFrom, isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('filter sheet toggles a priority and a Last-updated preset', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
|
||||||
|
|
||||||
await tester.tap(find.byIcon(Icons.filter_list));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
|
|
||||||
await tester.tap(find.text('High')); // priority chip toggle
|
|
||||||
// Second "Today" belongs to the Last-updated section.
|
|
||||||
await tester.tap(find.text('Today').last);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.tap(find.text('Apply'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
|
|
||||||
expect(repo.lastFilter!.priorities, contains(Priority.high));
|
|
||||||
expect(repo.lastFilter!.updatedFrom, isNotNull);
|
|
||||||
expect(repo.lastFilter!.updatedTo, isNotNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('a 30-day preset then Custom… confirms the seeded range', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final repo = await pumpList(tester, seed: [note('a', 'x')]);
|
|
||||||
|
|
||||||
await tester.tap(find.byIcon(Icons.filter_list));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
|
|
||||||
await tester.tap(find.text('30 days').first); // _applyDays(30)
|
|
||||||
await tester.pump();
|
|
||||||
// Custom… opens the range picker seeded with the 30-day range
|
|
||||||
// (initialDateRange != null); confirming with Save returns that range.
|
|
||||||
await tester.tap(find.text('Custom…').first);
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300)); // picker opens
|
|
||||||
await tester.tap(find.text('Save'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
await tester.tap(find.text('Apply'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
|
|
||||||
expect(repo.lastFilter!.createdFrom, isNotNull);
|
|
||||||
expect(repo.lastFilter!.createdTo, isNotNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('per-note sheet changes priority via a chip', (tester) async {
|
|
||||||
final repo = await pumpList(tester, seed: [note('a', 'Repriortise me')]);
|
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('Quick actions'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
await tester.tap(find.text('Low')); // default is Medium → change to Low
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect((await repo.listNotes()).single.priority, Priority.low);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('tapping a note opens the detail screen', (tester) async {
|
|
||||||
await pumpList(tester, seed: [note('a', '# Open me\n\nbody')]);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Open me'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump(const Duration(milliseconds: 300)); // route transition
|
|
||||||
|
|
||||||
// The detail screen shows the note title in its app bar plus the
|
|
||||||
// Priority/Status meta dropdowns and the editor mode toggle.
|
|
||||||
expect(find.text('Priority'), findsOneWidget);
|
|
||||||
expect(find.text('View'), findsOneWidget);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
80
test/port_guard_fakes.dart
Normal file
80
test/port_guard_fakes.dart
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
/// The FakeProbe and the ss/proc fixtures.
|
||||||
|
///
|
||||||
|
/// Shared by the files `port_guard_test.dart` was split into for the
|
||||||
|
/// 250-line cap. Deliberately NOT named `*_test.dart`: the runner would
|
||||||
|
/// collect it and fail on the missing `main()`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:todo/desktop/port_guard.dart';
|
||||||
|
|
||||||
|
/// Real `ss -tlnp` output, including the header row and the run-together
|
||||||
|
/// `Peer Address:PortProcess` column that iproute2 actually prints.
|
||||||
|
const _ssOutput = '''
|
||||||
|
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
|
||||||
|
LISTEN 0 4096 0.0.0.0:5355 0.0.0.0:*
|
||||||
|
LISTEN 0 128 127.0.0.1:8730 0.0.0.0:* users:(("dart:todo_deskt",pid=61687,fd=7))
|
||||||
|
LISTEN 0 511 127.0.0.1:9000 0.0.0.0:* users:(("node",pid=1234,fd=20))
|
||||||
|
''';
|
||||||
|
|
||||||
|
/// A [SystemProbe] whose every answer is scripted by the test.
|
||||||
|
class FakeProbe implements SystemProbe {
|
||||||
|
FakeProbe({
|
||||||
|
this.pid,
|
||||||
|
this.description,
|
||||||
|
this.cmdlines = const [],
|
||||||
|
this.inUse = const [true],
|
||||||
|
this.freeAfter,
|
||||||
|
});
|
||||||
|
|
||||||
|
int? pid;
|
||||||
|
ProcessDescription? description;
|
||||||
|
List<List<String>> cmdlines;
|
||||||
|
|
||||||
|
/// Answers for successive [portInUse] calls; the last one repeats.
|
||||||
|
List<bool> inUse;
|
||||||
|
|
||||||
|
/// When set, the port frees only once this signal has been delivered.
|
||||||
|
///
|
||||||
|
/// Keyed on the signal rather than on elapsed time so the escalation test
|
||||||
|
/// cannot flake on a slow machine.
|
||||||
|
ProcessSignal? freeAfter;
|
||||||
|
|
||||||
|
final List<ProcessSignal> signalsSent = [];
|
||||||
|
int portInUseCalls = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<int?> listenerPid(int port) async => pid;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<ProcessDescription?> describe(int pid) async => description;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<List<String>>> processCmdlines() async => cmdlines;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> portInUse(int port) async {
|
||||||
|
portInUseCalls++;
|
||||||
|
if (freeAfter != null) return !signalsSent.contains(freeAfter);
|
||||||
|
return inUse[(portInUseCalls - 1).clamp(0, inUse.length - 1)];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool signal(int pid, ProcessSignal signal) {
|
||||||
|
signalsSent.add(signal);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const _profile = '/home/kuchy/.local/share/todo-desktop/profile';
|
||||||
|
|
||||||
|
/// Fast timings so the reap tests do not slow the suite down.
|
||||||
|
Future<bool> _reap(PortGuard guard, int pid, int port) => guard.reap(
|
||||||
|
pid,
|
||||||
|
port,
|
||||||
|
termWait: const Duration(milliseconds: 60),
|
||||||
|
killWait: const Duration(milliseconds: 60),
|
||||||
|
pollInterval: const Duration(milliseconds: 5),
|
||||||
|
);
|
||||||
136
test/port_guard_linux_probe_test.dart
Normal file
136
test/port_guard_linux_probe_test.dart
Normal file
@ -0,0 +1,136 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:todo/desktop/port_guard.dart';
|
||||||
|
|
||||||
|
import 'port_guard_fakes.dart';
|
||||||
|
|
||||||
|
/// Real `ss -tlnp` output, including the header row and the run-together
|
||||||
|
/// `Peer Address:PortProcess` column that iproute2 actually prints.
|
||||||
|
const _ssOutput = '''
|
||||||
|
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
|
||||||
|
LISTEN 0 4096 0.0.0.0:5355 0.0.0.0:*
|
||||||
|
LISTEN 0 128 127.0.0.1:8730 0.0.0.0:* users:(("dart:todo_deskt",pid=61687,fd=7))
|
||||||
|
LISTEN 0 511 127.0.0.1:9000 0.0.0.0:* users:(("node",pid=1234,fd=20))
|
||||||
|
''';
|
||||||
|
|
||||||
|
/// A [SystemProbe] whose every answer is scripted by the test.
|
||||||
|
class FakeProbe implements SystemProbe {
|
||||||
|
FakeProbe({
|
||||||
|
this.pid,
|
||||||
|
this.description,
|
||||||
|
this.cmdlines = const [],
|
||||||
|
this.inUse = const [true],
|
||||||
|
this.freeAfter,
|
||||||
|
});
|
||||||
|
|
||||||
|
int? pid;
|
||||||
|
ProcessDescription? description;
|
||||||
|
List<List<String>> cmdlines;
|
||||||
|
|
||||||
|
/// Answers for successive [portInUse] calls; the last one repeats.
|
||||||
|
List<bool> inUse;
|
||||||
|
|
||||||
|
/// When set, the port frees only once this signal has been delivered.
|
||||||
|
///
|
||||||
|
/// Keyed on the signal rather than on elapsed time so the escalation test
|
||||||
|
/// cannot flake on a slow machine.
|
||||||
|
ProcessSignal? freeAfter;
|
||||||
|
|
||||||
|
final List<ProcessSignal> signalsSent = [];
|
||||||
|
int portInUseCalls = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<int?> listenerPid(int port) async => pid;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<ProcessDescription?> describe(int pid) async => description;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<List<String>>> processCmdlines() async => cmdlines;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> portInUse(int port) async {
|
||||||
|
portInUseCalls++;
|
||||||
|
if (freeAfter != null) return !signalsSent.contains(freeAfter);
|
||||||
|
return inUse[(portInUseCalls - 1).clamp(0, inUse.length - 1)];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool signal(int pid, ProcessSignal signal) {
|
||||||
|
signalsSent.add(signal);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const _profile = '/home/kuchy/.local/share/todo-desktop/profile';
|
||||||
|
|
||||||
|
/// Fast timings so the reap tests do not slow the suite down.
|
||||||
|
Future<bool> _reap(PortGuard guard, int pid, int port) => guard.reap(
|
||||||
|
pid,
|
||||||
|
port,
|
||||||
|
termWait: const Duration(milliseconds: 60),
|
||||||
|
killWait: const Duration(milliseconds: 60),
|
||||||
|
pollInterval: const Duration(milliseconds: 5),
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('LinuxSystemProbe against the real host', () {
|
||||||
|
test('portInUse tracks a real socket', () async {
|
||||||
|
const probe = LinuxSystemProbe();
|
||||||
|
final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
addTearDown(() async => socket.close());
|
||||||
|
expect(await probe.portInUse(socket.port), isTrue);
|
||||||
|
await socket.close();
|
||||||
|
expect(await probe.portInUse(socket.port), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('listenerPid finds this process holding a real port', () async {
|
||||||
|
const probe = LinuxSystemProbe();
|
||||||
|
final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
addTearDown(() async => socket.close());
|
||||||
|
// Proves the parser works against genuine `ss` output, not a fixture.
|
||||||
|
expect(await probe.listenerPid(socket.port), pid);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('listenerPid returns null when ss is unavailable', () async {
|
||||||
|
const probe = LinuxSystemProbe(ssExecutable: 'ss-does-not-exist');
|
||||||
|
expect(await probe.listenerPid(8730), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('describe reads this process', () async {
|
||||||
|
const probe = LinuxSystemProbe();
|
||||||
|
final description = await probe.describe(pid);
|
||||||
|
expect(description, isNotNull);
|
||||||
|
expect(description!.cmdline, isNotEmpty);
|
||||||
|
expect(description.exeTarget, isNotEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('describe tolerates an unreadable executable link', () async {
|
||||||
|
// pid 1 belongs to root: its cmdline is world-readable but /proc/1/exe
|
||||||
|
// is not, which is the branch under test.
|
||||||
|
const probe = LinuxSystemProbe();
|
||||||
|
final description = await probe.describe(1);
|
||||||
|
expect(description, isNotNull);
|
||||||
|
expect(description!.exeTarget, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('describe returns null for a process that does not exist', () async {
|
||||||
|
const probe = LinuxSystemProbe();
|
||||||
|
expect(await probe.describe(0x7FFFFFFF), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('processCmdlines lists real processes', () async {
|
||||||
|
const probe = LinuxSystemProbe();
|
||||||
|
final cmdlines = await probe.processCmdlines();
|
||||||
|
expect(cmdlines, isNotEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('signal terminates a real child process', () async {
|
||||||
|
const probe = LinuxSystemProbe();
|
||||||
|
final child = await Process.start('sleep', ['30']);
|
||||||
|
expect(probe.signal(child.pid, ProcessSignal.sigterm), isTrue);
|
||||||
|
expect(await child.exitCode, isNot(0));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
204
test/port_guard_parsing_test.dart
Normal file
204
test/port_guard_parsing_test.dart
Normal file
@ -0,0 +1,204 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:todo/desktop/port_guard.dart';
|
||||||
|
|
||||||
|
import 'port_guard_fakes.dart';
|
||||||
|
|
||||||
|
/// Real `ss -tlnp` output, including the header row and the run-together
|
||||||
|
/// `Peer Address:PortProcess` column that iproute2 actually prints.
|
||||||
|
const _ssOutput = '''
|
||||||
|
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
|
||||||
|
LISTEN 0 4096 0.0.0.0:5355 0.0.0.0:*
|
||||||
|
LISTEN 0 128 127.0.0.1:8730 0.0.0.0:* users:(("dart:todo_deskt",pid=61687,fd=7))
|
||||||
|
LISTEN 0 511 127.0.0.1:9000 0.0.0.0:* users:(("node",pid=1234,fd=20))
|
||||||
|
''';
|
||||||
|
|
||||||
|
/// A [SystemProbe] whose every answer is scripted by the test.
|
||||||
|
class FakeProbe implements SystemProbe {
|
||||||
|
FakeProbe({
|
||||||
|
this.pid,
|
||||||
|
this.description,
|
||||||
|
this.cmdlines = const [],
|
||||||
|
this.inUse = const [true],
|
||||||
|
this.freeAfter,
|
||||||
|
});
|
||||||
|
|
||||||
|
int? pid;
|
||||||
|
ProcessDescription? description;
|
||||||
|
List<List<String>> cmdlines;
|
||||||
|
|
||||||
|
/// Answers for successive [portInUse] calls; the last one repeats.
|
||||||
|
List<bool> inUse;
|
||||||
|
|
||||||
|
/// When set, the port frees only once this signal has been delivered.
|
||||||
|
///
|
||||||
|
/// Keyed on the signal rather than on elapsed time so the escalation test
|
||||||
|
/// cannot flake on a slow machine.
|
||||||
|
ProcessSignal? freeAfter;
|
||||||
|
|
||||||
|
final List<ProcessSignal> signalsSent = [];
|
||||||
|
int portInUseCalls = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<int?> listenerPid(int port) async => pid;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<ProcessDescription?> describe(int pid) async => description;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<List<String>>> processCmdlines() async => cmdlines;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> portInUse(int port) async {
|
||||||
|
portInUseCalls++;
|
||||||
|
if (freeAfter != null) return !signalsSent.contains(freeAfter);
|
||||||
|
return inUse[(portInUseCalls - 1).clamp(0, inUse.length - 1)];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool signal(int pid, ProcessSignal signal) {
|
||||||
|
signalsSent.add(signal);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const _profile = '/home/kuchy/.local/share/todo-desktop/profile';
|
||||||
|
|
||||||
|
/// Fast timings so the reap tests do not slow the suite down.
|
||||||
|
Future<bool> _reap(PortGuard guard, int pid, int port) => guard.reap(
|
||||||
|
pid,
|
||||||
|
port,
|
||||||
|
termWait: const Duration(milliseconds: 60),
|
||||||
|
killWait: const Duration(milliseconds: 60),
|
||||||
|
pollInterval: const Duration(milliseconds: 5),
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('parseListenerPid', () {
|
||||||
|
test('finds the pid holding the requested port', () {
|
||||||
|
expect(parseListenerPid(_ssOutput, 8730), 61687);
|
||||||
|
expect(parseListenerPid(_ssOutput, 9000), 1234);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns null when no line listens on the port', () {
|
||||||
|
expect(parseListenerPid(_ssOutput, 7777), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns null when ss hides the owning pid', () {
|
||||||
|
// ss omits the users:(...) column for another user's socket.
|
||||||
|
const hidden = 'LISTEN 0 128 127.0.0.1:8730 0.0.0.0:*';
|
||||||
|
expect(parseListenerPid(hidden, 8730), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ignores short and empty lines', () {
|
||||||
|
expect(parseListenerPid('\nLISTEN 0 128\n', 8730), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not match a port that is only a suffix', () {
|
||||||
|
const other =
|
||||||
|
'LISTEN 0 128 127.0.0.1:18730 0.0.0.0:* '
|
||||||
|
'users:(("x",pid=5,fd=7))';
|
||||||
|
expect(parseListenerPid(other, 8730), isNull);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('isTodoWrapper', () {
|
||||||
|
test('accepts the installed binary', () {
|
||||||
|
expect(isTodoWrapper('/opt/todo/bin/todo_desktop', []), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts a binary replaced by an upgrade', () {
|
||||||
|
expect(
|
||||||
|
isTodoWrapper('/opt/todo/bin/todo_desktop (deleted)', []),
|
||||||
|
isTrue,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts a development run out of the repo', () {
|
||||||
|
expect(
|
||||||
|
isTodoWrapper('/usr/lib/dart/bin/dart', [
|
||||||
|
'dart',
|
||||||
|
'run',
|
||||||
|
'bin/todo_desktop.dart',
|
||||||
|
'--web-root',
|
||||||
|
'build/web',
|
||||||
|
]),
|
||||||
|
isTrue,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects an unrelated process', () {
|
||||||
|
expect(
|
||||||
|
isTodoWrapper('/usr/bin/python3.14', [
|
||||||
|
'python3',
|
||||||
|
'-m',
|
||||||
|
'http.server',
|
||||||
|
'8730',
|
||||||
|
]),
|
||||||
|
isFalse,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('hasWindowAttached', () {
|
||||||
|
// Chrome rewrites argv into one space-joined string, so this is the shape
|
||||||
|
// that actually appears in /proc for a browser window.
|
||||||
|
const collapsed = [
|
||||||
|
'/opt/thorium-browser/thorium --app=http://localhost:8730 '
|
||||||
|
'--user-data-dir=$_profile --class=todo --no-first-run',
|
||||||
|
];
|
||||||
|
|
||||||
|
test('matches a browser whose argv collapsed into one token', () {
|
||||||
|
expect(hasWindowAttached([collapsed], _profile), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('matches a normally separated argument vector', () {
|
||||||
|
expect(
|
||||||
|
hasWindowAttached(
|
||||||
|
[
|
||||||
|
['thorium', '--user-data-dir=$_profile', '--class=todo'],
|
||||||
|
],
|
||||||
|
_profile,
|
||||||
|
),
|
||||||
|
isTrue,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('matches when the flag is the final argument', () {
|
||||||
|
expect(
|
||||||
|
hasWindowAttached(
|
||||||
|
[
|
||||||
|
['thorium', '--user-data-dir=$_profile'],
|
||||||
|
],
|
||||||
|
_profile,
|
||||||
|
),
|
||||||
|
isTrue,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not match a sibling profile directory', () {
|
||||||
|
expect(
|
||||||
|
hasWindowAttached(
|
||||||
|
[
|
||||||
|
['thorium', '--user-data-dir=${_profile}2'],
|
||||||
|
],
|
||||||
|
_profile,
|
||||||
|
),
|
||||||
|
isFalse,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not match when no process mentions the profile', () {
|
||||||
|
expect(
|
||||||
|
hasWindowAttached(
|
||||||
|
[
|
||||||
|
['bash', '-c', 'sleep 1'],
|
||||||
|
],
|
||||||
|
_profile,
|
||||||
|
),
|
||||||
|
isFalse,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -3,6 +3,8 @@ import 'dart:io';
|
|||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:todo/desktop/port_guard.dart';
|
import 'package:todo/desktop/port_guard.dart';
|
||||||
|
|
||||||
|
import 'port_guard_fakes.dart';
|
||||||
|
|
||||||
/// Real `ss -tlnp` output, including the header row and the run-together
|
/// Real `ss -tlnp` output, including the header row and the run-together
|
||||||
/// `Peer Address:PortProcess` column that iproute2 actually prints.
|
/// `Peer Address:PortProcess` column that iproute2 actually prints.
|
||||||
const _ssOutput = '''
|
const _ssOutput = '''
|
||||||
@ -73,133 +75,6 @@ Future<bool> _reap(PortGuard guard, int pid, int port) => guard.reap(
|
|||||||
);
|
);
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
group('parseListenerPid', () {
|
|
||||||
test('finds the pid holding the requested port', () {
|
|
||||||
expect(parseListenerPid(_ssOutput, 8730), 61687);
|
|
||||||
expect(parseListenerPid(_ssOutput, 9000), 1234);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('returns null when no line listens on the port', () {
|
|
||||||
expect(parseListenerPid(_ssOutput, 7777), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('returns null when ss hides the owning pid', () {
|
|
||||||
// ss omits the users:(...) column for another user's socket.
|
|
||||||
const hidden = 'LISTEN 0 128 127.0.0.1:8730 0.0.0.0:*';
|
|
||||||
expect(parseListenerPid(hidden, 8730), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('ignores short and empty lines', () {
|
|
||||||
expect(parseListenerPid('\nLISTEN 0 128\n', 8730), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('does not match a port that is only a suffix', () {
|
|
||||||
const other =
|
|
||||||
'LISTEN 0 128 127.0.0.1:18730 0.0.0.0:* '
|
|
||||||
'users:(("x",pid=5,fd=7))';
|
|
||||||
expect(parseListenerPid(other, 8730), isNull);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('isTodoWrapper', () {
|
|
||||||
test('accepts the installed binary', () {
|
|
||||||
expect(isTodoWrapper('/opt/todo/bin/todo_desktop', []), isTrue);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('accepts a binary replaced by an upgrade', () {
|
|
||||||
expect(
|
|
||||||
isTodoWrapper('/opt/todo/bin/todo_desktop (deleted)', []),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('accepts a development run out of the repo', () {
|
|
||||||
expect(
|
|
||||||
isTodoWrapper('/usr/lib/dart/bin/dart', [
|
|
||||||
'dart',
|
|
||||||
'run',
|
|
||||||
'bin/todo_desktop.dart',
|
|
||||||
'--web-root',
|
|
||||||
'build/web',
|
|
||||||
]),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('rejects an unrelated process', () {
|
|
||||||
expect(
|
|
||||||
isTodoWrapper('/usr/bin/python3.14', [
|
|
||||||
'python3',
|
|
||||||
'-m',
|
|
||||||
'http.server',
|
|
||||||
'8730',
|
|
||||||
]),
|
|
||||||
isFalse,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('hasWindowAttached', () {
|
|
||||||
// Chrome rewrites argv into one space-joined string, so this is the shape
|
|
||||||
// that actually appears in /proc for a browser window.
|
|
||||||
const collapsed = [
|
|
||||||
'/opt/thorium-browser/thorium --app=http://localhost:8730 '
|
|
||||||
'--user-data-dir=$_profile --class=todo --no-first-run',
|
|
||||||
];
|
|
||||||
|
|
||||||
test('matches a browser whose argv collapsed into one token', () {
|
|
||||||
expect(hasWindowAttached([collapsed], _profile), isTrue);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('matches a normally separated argument vector', () {
|
|
||||||
expect(
|
|
||||||
hasWindowAttached(
|
|
||||||
[
|
|
||||||
['thorium', '--user-data-dir=$_profile', '--class=todo'],
|
|
||||||
],
|
|
||||||
_profile,
|
|
||||||
),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('matches when the flag is the final argument', () {
|
|
||||||
expect(
|
|
||||||
hasWindowAttached(
|
|
||||||
[
|
|
||||||
['thorium', '--user-data-dir=$_profile'],
|
|
||||||
],
|
|
||||||
_profile,
|
|
||||||
),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('does not match a sibling profile directory', () {
|
|
||||||
expect(
|
|
||||||
hasWindowAttached(
|
|
||||||
[
|
|
||||||
['thorium', '--user-data-dir=${_profile}2'],
|
|
||||||
],
|
|
||||||
_profile,
|
|
||||||
),
|
|
||||||
isFalse,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('does not match when no process mentions the profile', () {
|
|
||||||
expect(
|
|
||||||
hasWindowAttached(
|
|
||||||
[
|
|
||||||
['bash', '-c', 'sleep 1'],
|
|
||||||
],
|
|
||||||
_profile,
|
|
||||||
),
|
|
||||||
isFalse,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('PortGuard.resolve', () {
|
group('PortGuard.resolve', () {
|
||||||
test('retries the bind when the port came free', () async {
|
test('retries the bind when the port came free', () async {
|
||||||
final guard = PortGuard(
|
final guard = PortGuard(
|
||||||
@ -343,63 +218,4 @@ void main() {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
group('LinuxSystemProbe against the real host', () {
|
|
||||||
test('portInUse tracks a real socket', () async {
|
|
||||||
const probe = LinuxSystemProbe();
|
|
||||||
final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
|
|
||||||
addTearDown(() async => socket.close());
|
|
||||||
expect(await probe.portInUse(socket.port), isTrue);
|
|
||||||
await socket.close();
|
|
||||||
expect(await probe.portInUse(socket.port), isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('listenerPid finds this process holding a real port', () async {
|
|
||||||
const probe = LinuxSystemProbe();
|
|
||||||
final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
|
|
||||||
addTearDown(() async => socket.close());
|
|
||||||
// Proves the parser works against genuine `ss` output, not a fixture.
|
|
||||||
expect(await probe.listenerPid(socket.port), pid);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('listenerPid returns null when ss is unavailable', () async {
|
|
||||||
const probe = LinuxSystemProbe(ssExecutable: 'ss-does-not-exist');
|
|
||||||
expect(await probe.listenerPid(8730), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('describe reads this process', () async {
|
|
||||||
const probe = LinuxSystemProbe();
|
|
||||||
final description = await probe.describe(pid);
|
|
||||||
expect(description, isNotNull);
|
|
||||||
expect(description!.cmdline, isNotEmpty);
|
|
||||||
expect(description.exeTarget, isNotEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('describe tolerates an unreadable executable link', () async {
|
|
||||||
// pid 1 belongs to root: its cmdline is world-readable but /proc/1/exe
|
|
||||||
// is not, which is the branch under test.
|
|
||||||
const probe = LinuxSystemProbe();
|
|
||||||
final description = await probe.describe(1);
|
|
||||||
expect(description, isNotNull);
|
|
||||||
expect(description!.exeTarget, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('describe returns null for a process that does not exist', () async {
|
|
||||||
const probe = LinuxSystemProbe();
|
|
||||||
expect(await probe.describe(0x7FFFFFFF), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('processCmdlines lists real processes', () async {
|
|
||||||
const probe = LinuxSystemProbe();
|
|
||||||
final cmdlines = await probe.processCmdlines();
|
|
||||||
expect(cmdlines, isNotEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('signal terminates a real child process', () async {
|
|
||||||
const probe = LinuxSystemProbe();
|
|
||||||
final child = await Process.start('sleep', ['30']);
|
|
||||||
expect(probe.signal(child.pid, ProcessSignal.sigterm), isTrue);
|
|
||||||
expect(await child.exitCode, isNot(0));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
197
test/settings_screen_backup_test.dart
Normal file
197
test/settings_screen_backup_test.dart
Normal file
@ -0,0 +1,197 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||||
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/sync/backlog_export_io.dart';
|
||||||
|
import 'package:todo/sync/notes_markdown.dart';
|
||||||
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
|
import 'package:todo/ui/settings_screen.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
import 'settings_screen_harness.dart';
|
||||||
|
|
||||||
|
/// Stub file picker that returns a fixed in-memory file (no disk I/O, so the
|
||||||
|
/// `_import` flow stays timer-free and deterministic under the widget tester).
|
||||||
|
class _FakeFileSelector extends FileSelectorPlatform
|
||||||
|
with MockPlatformInterfaceMixin {
|
||||||
|
_FakeFileSelector(this.file);
|
||||||
|
final XFile? file;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<XFile?> openFile({
|
||||||
|
List<XTypeGroup>? acceptedTypeGroups,
|
||||||
|
String? initialDirectory,
|
||||||
|
String? confirmButtonText,
|
||||||
|
}) async => file;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Repository whose reads fail, to exercise the export error path.
|
||||||
|
class _ExplodingRepo extends FakeNoteRepository {
|
||||||
|
@override
|
||||||
|
Future<List<Note>> listNotes({
|
||||||
|
NoteSort sort = NoteSort.modifiedDesc,
|
||||||
|
NoteFilter filter = const NoteFilter(),
|
||||||
|
}) async => throw Exception('db down');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// File picker stub that throws, to exercise the import error path.
|
||||||
|
class _ThrowingFileSelector extends FileSelectorPlatform
|
||||||
|
with MockPlatformInterfaceMixin {
|
||||||
|
@override
|
||||||
|
Future<XFile?> openFile({
|
||||||
|
List<XTypeGroup>? acceptedTypeGroups,
|
||||||
|
String? initialDirectory,
|
||||||
|
String? confirmButtonText,
|
||||||
|
}) async => throw Exception('picker blew up');
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('BackupSlot wiring through Sync settings', () {
|
||||||
|
// These prove the closures SettingsScreen builds for
|
||||||
|
// SyncSettingsScreen's BackupSlot actually call todo's real
|
||||||
|
// export/import — the shared package's own suite covers the generic
|
||||||
|
// BackupSlot UI (button taps, status text), so these focus on the real
|
||||||
|
// behavior behind the closures instead of re-asserting status text.
|
||||||
|
|
||||||
|
testWidgets('Export notes writes the backlog file (desktop)', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
// Redirect HOME: this test does real file I/O, and without the
|
||||||
|
// override it overwrites the user's canonical ~/todo/BACKLOG.md with
|
||||||
|
// the fake note below on every test run.
|
||||||
|
final home = Directory.systemTemp.createTempSync('todo_export_home');
|
||||||
|
resolveExportHome = () => home.path;
|
||||||
|
addTearDown(() {
|
||||||
|
resolveExportHome = () =>
|
||||||
|
Platform.environment['HOME'] ?? Directory.current.path;
|
||||||
|
home.deleteSync(recursive: true);
|
||||||
|
});
|
||||||
|
|
||||||
|
await pumpSettings(
|
||||||
|
tester,
|
||||||
|
seed: [
|
||||||
|
Note(
|
||||||
|
id: 'n',
|
||||||
|
text: 'an idea',
|
||||||
|
priority: Priority.medium,
|
||||||
|
status: Status.todo,
|
||||||
|
createdAt: DateTime(2026, 6, 15),
|
||||||
|
updatedAt: DateTime(2026, 6, 15),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sync settings'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
// _export does real file I/O on desktop, so drive it under runAsync.
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await tester.tap(find.text('Export notes'));
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||||
|
});
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
final file = File('${home.path}/todo/BACKLOG.md');
|
||||||
|
expect(file.existsSync(), isTrue);
|
||||||
|
expect(file.readAsStringSync(), contains('an idea'));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Export surfaces a failure when the repository read fails', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpSettings(tester, repository: _ExplodingRepo());
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sync settings'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
await tester.tap(find.text('Export notes'));
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||||
|
});
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.textContaining('Export failed'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Import notes reads the picked file and merges', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
// Round-trip a known note through the export format so the picked
|
||||||
|
// file is valid input the importer can parse and merge.
|
||||||
|
final markdown = NotesMarkdown.export([
|
||||||
|
Note(
|
||||||
|
id: 'imported-1',
|
||||||
|
text: 'an imported idea',
|
||||||
|
priority: Priority.high,
|
||||||
|
status: Status.inProgress,
|
||||||
|
createdAt: DateTime(2026, 6, 15),
|
||||||
|
updatedAt: DateTime(2026, 6, 15),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
FileSelectorPlatform.instance = _FakeFileSelector(
|
||||||
|
XFile.fromData(utf8.encode(markdown), name: 'backlog.md'),
|
||||||
|
);
|
||||||
|
|
||||||
|
final repo = await pumpSettings(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sync settings'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Import notes'));
|
||||||
|
await tester.pump(); // openFile resolves (in-memory)
|
||||||
|
await tester.pump(); // read + parse + merge + setState
|
||||||
|
|
||||||
|
expect((await repo.listNotes()).single.text, 'an imported idea');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Import shows nothing when the picker is cancelled', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
FileSelectorPlatform.instance = _FakeFileSelector(null); // cancelled
|
||||||
|
final repo = await pumpSettings(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sync settings'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Import notes'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
// The shared screen can't distinguish "cancelled" from "nothing
|
||||||
|
// imported" — it reports "Imported notes." either way, since
|
||||||
|
// BackupSlot.import() returns normally on cancel. The behavior that
|
||||||
|
// actually matters, that nothing was merged, is what's asserted here.
|
||||||
|
expect(await repo.listNotes(), isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Import surfaces a failure from the picker', (tester) async {
|
||||||
|
FileSelectorPlatform.instance = _ThrowingFileSelector();
|
||||||
|
final repo = await pumpSettings(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sync settings'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Import notes'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(find.textContaining('Import failed'), findsOneWidget);
|
||||||
|
expect(await repo.listNotes(), isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
116
test/settings_screen_harness.dart
Normal file
116
test/settings_screen_harness.dart
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
/// The pumpSettings harness and its file-selector fakes.
|
||||||
|
///
|
||||||
|
/// Shared by the files `settings_screen_test.dart` was split into for the
|
||||||
|
/// 250-line cap. Deliberately NOT named `*_test.dart`: the runner would
|
||||||
|
/// collect it and fail on the missing `main()`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||||
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
|
import 'package:todo/data/app_settings.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/sync/backlog_export_io.dart';
|
||||||
|
import 'package:todo/sync/notes_markdown.dart';
|
||||||
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
|
import 'package:todo/ui/github_mirror_screen.dart';
|
||||||
|
import 'package:todo/ui/settings_screen.dart';
|
||||||
|
|
||||||
|
import 'fake_note_repository.dart';
|
||||||
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
/// Stub file picker that returns a fixed in-memory file (no disk I/O, so the
|
||||||
|
/// `_import` flow stays timer-free and deterministic under the widget tester).
|
||||||
|
class _FakeFileSelector extends FileSelectorPlatform
|
||||||
|
with MockPlatformInterfaceMixin {
|
||||||
|
_FakeFileSelector(this.file);
|
||||||
|
final XFile? file;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<XFile?> openFile({
|
||||||
|
List<XTypeGroup>? acceptedTypeGroups,
|
||||||
|
String? initialDirectory,
|
||||||
|
String? confirmButtonText,
|
||||||
|
}) async => file;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Repository whose reads fail, to exercise the export error path.
|
||||||
|
class _ExplodingRepo extends FakeNoteRepository {
|
||||||
|
@override
|
||||||
|
Future<List<Note>> listNotes({
|
||||||
|
NoteSort sort = NoteSort.modifiedDesc,
|
||||||
|
NoteFilter filter = const NoteFilter(),
|
||||||
|
}) async => throw Exception('db down');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// File picker stub that throws, to exercise the import error path.
|
||||||
|
class _ThrowingFileSelector extends FileSelectorPlatform
|
||||||
|
with MockPlatformInterfaceMixin {
|
||||||
|
@override
|
||||||
|
Future<XFile?> openFile({
|
||||||
|
List<XTypeGroup>? acceptedTypeGroups,
|
||||||
|
String? initialDirectory,
|
||||||
|
String? confirmButtonText,
|
||||||
|
}) async => throw Exception('picker blew up');
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<FakeNoteRepository> pumpSettings(
|
||||||
|
WidgetTester tester, {
|
||||||
|
SyncSettings initial = const SyncSettings(
|
||||||
|
owner: 'kuhyx',
|
||||||
|
repo: 'syncs',
|
||||||
|
token: 't',
|
||||||
|
),
|
||||||
|
http.Client? httpClient,
|
||||||
|
List<Note> seed = const [],
|
||||||
|
FakeNoteRepository? repository,
|
||||||
|
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
||||||
|
ValueNotifier<AppSettings>? appSettings,
|
||||||
|
AnalyticsService? analytics,
|
||||||
|
}) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
installFakeSecureStorage();
|
||||||
|
// Tall surface so the whole settings ListView builds and the pushed
|
||||||
|
// Sync settings screen's Backup section (below the default 800×600
|
||||||
|
// fold) isn't lazy-skipped.
|
||||||
|
tester.view.physicalSize = const Size(1200, 2800);
|
||||||
|
tester.view.devicePixelRatio = 1.0;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
|
||||||
|
final repo = repository ?? FakeNoteRepository(seed);
|
||||||
|
addTearDown(repo.close);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: SettingsScreen(
|
||||||
|
initial: initial,
|
||||||
|
repository: repo,
|
||||||
|
appSettings:
|
||||||
|
appSettings ??
|
||||||
|
ValueNotifier(const AppSettings(advancedMode: false)),
|
||||||
|
analytics: analytics,
|
||||||
|
httpClient: httpClient,
|
||||||
|
// Injected so the widget never reaches for the platform: the real
|
||||||
|
// factory wants the OS keystore, which doesn't exist under
|
||||||
|
// `flutter test`.
|
||||||
|
firebaseFactory: firebaseFactory ?? () async => null,
|
||||||
|
accountLoader: () async => null,
|
||||||
|
sessionProbe: () async => false,
|
||||||
|
stateStore: InMemorySyncStateStore(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
return repo;
|
||||||
|
}
|
||||||
@ -23,6 +23,8 @@ import 'package:todo/ui/settings_screen.dart';
|
|||||||
import 'fake_note_repository.dart';
|
import 'fake_note_repository.dart';
|
||||||
import 'fake_secure_storage.dart';
|
import 'fake_secure_storage.dart';
|
||||||
|
|
||||||
|
import 'settings_screen_harness.dart';
|
||||||
|
|
||||||
/// Stub file picker that returns a fixed in-memory file (no disk I/O, so the
|
/// Stub file picker that returns a fixed in-memory file (no disk I/O, so the
|
||||||
/// `_import` flow stays timer-free and deterministic under the widget tester).
|
/// `_import` flow stays timer-free and deterministic under the widget tester).
|
||||||
class _FakeFileSelector extends FileSelectorPlatform
|
class _FakeFileSelector extends FileSelectorPlatform
|
||||||
@ -59,56 +61,6 @@ class _ThrowingFileSelector extends FileSelectorPlatform
|
|||||||
}
|
}
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
Future<FakeNoteRepository> pumpSettings(
|
|
||||||
WidgetTester tester, {
|
|
||||||
SyncSettings initial = const SyncSettings(
|
|
||||||
owner: 'kuhyx',
|
|
||||||
repo: 'syncs',
|
|
||||||
token: 't',
|
|
||||||
),
|
|
||||||
http.Client? httpClient,
|
|
||||||
List<Note> seed = const [],
|
|
||||||
FakeNoteRepository? repository,
|
|
||||||
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
|
||||||
ValueNotifier<AppSettings>? appSettings,
|
|
||||||
AnalyticsService? analytics,
|
|
||||||
}) async {
|
|
||||||
SharedPreferences.setMockInitialValues({});
|
|
||||||
installFakeSecureStorage();
|
|
||||||
// Tall surface so the whole settings ListView builds and the pushed
|
|
||||||
// Sync settings screen's Backup section (below the default 800×600
|
|
||||||
// fold) isn't lazy-skipped.
|
|
||||||
tester.view.physicalSize = const Size(1200, 2800);
|
|
||||||
tester.view.devicePixelRatio = 1.0;
|
|
||||||
addTearDown(tester.view.resetPhysicalSize);
|
|
||||||
addTearDown(tester.view.resetDevicePixelRatio);
|
|
||||||
|
|
||||||
final repo = repository ?? FakeNoteRepository(seed);
|
|
||||||
addTearDown(repo.close);
|
|
||||||
await tester.pumpWidget(
|
|
||||||
MaterialApp(
|
|
||||||
home: SettingsScreen(
|
|
||||||
initial: initial,
|
|
||||||
repository: repo,
|
|
||||||
appSettings:
|
|
||||||
appSettings ??
|
|
||||||
ValueNotifier(const AppSettings(advancedMode: false)),
|
|
||||||
analytics: analytics,
|
|
||||||
httpClient: httpClient,
|
|
||||||
// Injected so the widget never reaches for the platform: the real
|
|
||||||
// factory wants the OS keystore, which doesn't exist under
|
|
||||||
// `flutter test`.
|
|
||||||
firebaseFactory: firebaseFactory ?? () async => null,
|
|
||||||
accountLoader: () async => null,
|
|
||||||
sessionProbe: () async => false,
|
|
||||||
stateStore: InMemorySyncStateStore(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
return repo;
|
|
||||||
}
|
|
||||||
|
|
||||||
testWidgets(
|
testWidgets(
|
||||||
'Enable advanced toggles and persists locally with no client',
|
'Enable advanced toggles and persists locally with no client',
|
||||||
(tester) async {
|
(tester) async {
|
||||||
@ -254,138 +206,4 @@ void main() {
|
|||||||
// suite cannot write to the user's ~/todo.
|
// suite cannot write to the user's ~/todo.
|
||||||
expect(resolveExportHome(), Platform.environment['HOME']);
|
expect(resolveExportHome(), Platform.environment['HOME']);
|
||||||
});
|
});
|
||||||
|
|
||||||
group('BackupSlot wiring through Sync settings', () {
|
|
||||||
// These prove the closures SettingsScreen builds for
|
|
||||||
// SyncSettingsScreen's BackupSlot actually call todo's real
|
|
||||||
// export/import — the shared package's own suite covers the generic
|
|
||||||
// BackupSlot UI (button taps, status text), so these focus on the real
|
|
||||||
// behavior behind the closures instead of re-asserting status text.
|
|
||||||
|
|
||||||
testWidgets('Export notes writes the backlog file (desktop)', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// Redirect HOME: this test does real file I/O, and without the
|
|
||||||
// override it overwrites the user's canonical ~/todo/BACKLOG.md with
|
|
||||||
// the fake note below on every test run.
|
|
||||||
final home = Directory.systemTemp.createTempSync('todo_export_home');
|
|
||||||
resolveExportHome = () => home.path;
|
|
||||||
addTearDown(() {
|
|
||||||
resolveExportHome = () =>
|
|
||||||
Platform.environment['HOME'] ?? Directory.current.path;
|
|
||||||
home.deleteSync(recursive: true);
|
|
||||||
});
|
|
||||||
|
|
||||||
await pumpSettings(
|
|
||||||
tester,
|
|
||||||
seed: [
|
|
||||||
Note(
|
|
||||||
id: 'n',
|
|
||||||
text: 'an idea',
|
|
||||||
priority: Priority.medium,
|
|
||||||
status: Status.todo,
|
|
||||||
createdAt: DateTime(2026, 6, 15),
|
|
||||||
updatedAt: DateTime(2026, 6, 15),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sync settings'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
// _export does real file I/O on desktop, so drive it under runAsync.
|
|
||||||
await tester.runAsync(() async {
|
|
||||||
await tester.tap(find.text('Export notes'));
|
|
||||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
|
||||||
});
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
final file = File('${home.path}/todo/BACKLOG.md');
|
|
||||||
expect(file.existsSync(), isTrue);
|
|
||||||
expect(file.readAsStringSync(), contains('an idea'));
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Export surfaces a failure when the repository read fails', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await pumpSettings(tester, repository: _ExplodingRepo());
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sync settings'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.runAsync(() async {
|
|
||||||
await tester.tap(find.text('Export notes'));
|
|
||||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
|
||||||
});
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.textContaining('Export failed'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Import notes reads the picked file and merges', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
// Round-trip a known note through the export format so the picked
|
|
||||||
// file is valid input the importer can parse and merge.
|
|
||||||
final markdown = NotesMarkdown.export([
|
|
||||||
Note(
|
|
||||||
id: 'imported-1',
|
|
||||||
text: 'an imported idea',
|
|
||||||
priority: Priority.high,
|
|
||||||
status: Status.inProgress,
|
|
||||||
createdAt: DateTime(2026, 6, 15),
|
|
||||||
updatedAt: DateTime(2026, 6, 15),
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
FileSelectorPlatform.instance = _FakeFileSelector(
|
|
||||||
XFile.fromData(utf8.encode(markdown), name: 'backlog.md'),
|
|
||||||
);
|
|
||||||
|
|
||||||
final repo = await pumpSettings(tester);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sync settings'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.tap(find.text('Import notes'));
|
|
||||||
await tester.pump(); // openFile resolves (in-memory)
|
|
||||||
await tester.pump(); // read + parse + merge + setState
|
|
||||||
|
|
||||||
expect((await repo.listNotes()).single.text, 'an imported idea');
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Import shows nothing when the picker is cancelled', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
FileSelectorPlatform.instance = _FakeFileSelector(null); // cancelled
|
|
||||||
final repo = await pumpSettings(tester);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sync settings'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.tap(find.text('Import notes'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
// The shared screen can't distinguish "cancelled" from "nothing
|
|
||||||
// imported" — it reports "Imported notes." either way, since
|
|
||||||
// BackupSlot.import() returns normally on cancel. The behavior that
|
|
||||||
// actually matters, that nothing was merged, is what's asserted here.
|
|
||||||
expect(await repo.listNotes(), isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Import surfaces a failure from the picker', (tester) async {
|
|
||||||
FileSelectorPlatform.instance = _ThrowingFileSelector();
|
|
||||||
final repo = await pumpSettings(tester);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sync settings'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.tap(find.text('Import notes'));
|
|
||||||
await tester.pump();
|
|
||||||
await tester.pump();
|
|
||||||
|
|
||||||
expect(find.textContaining('Import failed'), findsOneWidget);
|
|
||||||
expect(await repo.listNotes(), isEmpty);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
161
test/sync_service_fakes.dart
Normal file
161
test/sync_service_fakes.dart
Normal file
@ -0,0 +1,161 @@
|
|||||||
|
/// The GitHub/remote fakes and note fixtures shared by the sync_service
|
||||||
|
/// test files.
|
||||||
|
///
|
||||||
|
/// `sync_service_test.dart` was split for the 250-line cap. The underscores
|
||||||
|
/// came off every name here: Dart privacy is library-scoped, so a `_Fake`
|
||||||
|
/// declared in one file is invisible to the next.
|
||||||
|
///
|
||||||
|
/// Deliberately NOT named `*_test.dart`: the runner would collect it and
|
||||||
|
/// fail on the missing `main()`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/sync/sync_service.dart';
|
||||||
|
|
||||||
|
http.Response response(int statusCode, [Object? jsonBody]) =>
|
||||||
|
http.Response(jsonEncode(jsonBody ?? {}), statusCode);
|
||||||
|
|
||||||
|
http.Response fileWith(String text, {String? sha}) =>
|
||||||
|
response(200, {'content': base64.encode(utf8.encode(text)), 'sha': ?sha});
|
||||||
|
|
||||||
|
class PutCall {
|
||||||
|
PutCall(this.path, this.body);
|
||||||
|
final String path;
|
||||||
|
final Map<String, dynamic> body;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mock GitHub Contents API router matching crdt_sync's client: GET
|
||||||
|
/// `.../contents/<key>` returns [contentResponses]`[key]` (404 if absent), the
|
||||||
|
/// bare repo-existence GET always succeeds, and every PUT is recorded.
|
||||||
|
({http.Client httpClient, List<PutCall> putCalls}) mockGitHub({
|
||||||
|
Map<String, http.Response> contentResponses = const {},
|
||||||
|
}) {
|
||||||
|
final putCalls = <PutCall>[];
|
||||||
|
final client = http_testing.MockClient((request) async {
|
||||||
|
final path = request.url.path;
|
||||||
|
if (!path.contains('/contents/')) return response(200); // repo-exists
|
||||||
|
final key = path.split('/contents/').last;
|
||||||
|
if (request.method == 'PUT') {
|
||||||
|
putCalls.add(
|
||||||
|
PutCall(key, jsonDecode(request.body) as Map<String, dynamic>),
|
||||||
|
);
|
||||||
|
return response(200);
|
||||||
|
}
|
||||||
|
return contentResponses[key] ?? response(404);
|
||||||
|
});
|
||||||
|
return (httpClient: client, putCalls: putCalls);
|
||||||
|
}
|
||||||
|
|
||||||
|
GitHubClient github(http.Client mock) =>
|
||||||
|
GitHubClient(owner: 'o', repo: 'r', token: 't', httpClient: mock);
|
||||||
|
|
||||||
|
Note note(String id, String text) => Note(
|
||||||
|
id: id,
|
||||||
|
text: text,
|
||||||
|
priority: Priority.medium,
|
||||||
|
status: Status.todo,
|
||||||
|
createdAt: DateTime(2026, 6, 15),
|
||||||
|
updatedAt: DateTime(2026, 6, 15),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// An in-memory [RemoteStore] that also serves revision maps in one read,
|
||||||
|
/// standing in for Firebase. Counts reads so tests can assert on *traffic*
|
||||||
|
/// rather than on the merge result.
|
||||||
|
class FakeRemote implements RemoteStore, BulkMapReader {
|
||||||
|
FakeRemote(this.files);
|
||||||
|
|
||||||
|
final Map<String, String> files;
|
||||||
|
final List<String> reads = [];
|
||||||
|
final List<String> writes = [];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) async => files.keys
|
||||||
|
.where((k) => k.startsWith('$path/'))
|
||||||
|
.map((k) => k.substring(path.length + 1).split('/').first)
|
||||||
|
.toSet()
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) async {
|
||||||
|
reads.add(path);
|
||||||
|
return files[path];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(
|
||||||
|
String path,
|
||||||
|
String text, {
|
||||||
|
required String message,
|
||||||
|
}) async {
|
||||||
|
writes.add(path);
|
||||||
|
files[path] = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Map<String, String>> getStringMap(String path) async => {
|
||||||
|
for (final e in files.entries)
|
||||||
|
if (e.key.startsWith('$path/')) e.key.substring(path.length + 1): e.value,
|
||||||
|
};
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) async =>
|
||||||
|
files.remove(path);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() async => true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [RemoteStore] with no bulk-map read, standing in for GitHub.
|
||||||
|
///
|
||||||
|
/// Delegates rather than extends: a subclass of [FakeRemote] would inherit
|
||||||
|
/// `BulkMapReader`, the very capability this fake exists to lack.
|
||||||
|
class FakeRemoteWithoutBulkRead implements RemoteStore {
|
||||||
|
FakeRemoteWithoutBulkRead(Map<String, String> files)
|
||||||
|
: _inner = FakeRemote(files);
|
||||||
|
|
||||||
|
final FakeRemote _inner;
|
||||||
|
|
||||||
|
List<String> get reads => _inner.reads;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) => _inner.listDirectory(path);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) => _inner.getFileText(path);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(
|
||||||
|
String path,
|
||||||
|
String text, {
|
||||||
|
required String message,
|
||||||
|
}) => _inner.putFileText(path, text, message: message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) =>
|
||||||
|
_inner.deleteFile(path, message: message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() => _inner.canAccessRemote();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() => _inner.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds a one-note log as it would arrive from another device.
|
||||||
|
Future<Log> buildPeerLog({String title = 'from phone'}) async {
|
||||||
|
final peer = await NoteRepository.openInMemory(nodeId: 'phone');
|
||||||
|
await peer.upsert(note('peer-note', title));
|
||||||
|
final log = peer.exportLog();
|
||||||
|
await peer.close();
|
||||||
|
return log;
|
||||||
|
}
|
||||||
95
test/sync_service_revision_test.dart
Normal file
95
test/sync_service_revision_test.dart
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/sync/sync_service.dart';
|
||||||
|
|
||||||
|
import 'sync_service_fakes.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('revision tracking', () {
|
||||||
|
late NoteRepository repo;
|
||||||
|
|
||||||
|
setUp(() async {
|
||||||
|
repo = await NoteRepository.openInMemory(nodeId: 'me');
|
||||||
|
});
|
||||||
|
|
||||||
|
tearDown(() async => repo.close());
|
||||||
|
|
||||||
|
test('skips a peer whose revision has not changed', () async {
|
||||||
|
// The saving the free-tier budget depends on: an unchanged ~150 KB peer
|
||||||
|
// log must not be downloaded again.
|
||||||
|
final peerLog = logToJson(await buildPeerLog());
|
||||||
|
final remote = FakeRemote({
|
||||||
|
'todo-sync/notes/phone.json': peerLog,
|
||||||
|
'todo-sync/revs/phone': revisionOf(peerLog),
|
||||||
|
});
|
||||||
|
final store = InMemorySyncStateStore();
|
||||||
|
|
||||||
|
await SyncService(stateStore: store).sync(repo, remote);
|
||||||
|
remote.reads.clear();
|
||||||
|
final second = await SyncService(stateStore: store).sync(repo, remote);
|
||||||
|
|
||||||
|
expect(remote.reads, isNot(contains('todo-sync/notes/phone.json')));
|
||||||
|
expect(second.skippedUnchanged, 1);
|
||||||
|
expect(second.mergedDevices, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('downloads again once the peer publishes a new revision', () async {
|
||||||
|
final first = logToJson(await buildPeerLog());
|
||||||
|
final remote = FakeRemote({
|
||||||
|
'todo-sync/notes/phone.json': first,
|
||||||
|
'todo-sync/revs/phone': revisionOf(first),
|
||||||
|
});
|
||||||
|
final store = InMemorySyncStateStore();
|
||||||
|
await SyncService(stateStore: store).sync(repo, remote);
|
||||||
|
remote.reads.clear();
|
||||||
|
|
||||||
|
final changed = logToJson(await buildPeerLog(title: 'changed'));
|
||||||
|
remote.files['todo-sync/notes/phone.json'] = changed;
|
||||||
|
remote.files['todo-sync/revs/phone'] = revisionOf(changed);
|
||||||
|
final second = await SyncService(stateStore: store).sync(repo, remote);
|
||||||
|
|
||||||
|
expect(remote.reads, contains('todo-sync/notes/phone.json'));
|
||||||
|
expect(second.mergedDevices, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('suppresses an unchanged push and publishes a revision', () async {
|
||||||
|
final remote = FakeRemote({});
|
||||||
|
final store = InMemorySyncStateStore();
|
||||||
|
|
||||||
|
final first = await SyncService(stateStore: store).sync(repo, remote);
|
||||||
|
expect(first.pushed, isTrue);
|
||||||
|
expect(remote.writes, [
|
||||||
|
'todo-sync/notes/me.json',
|
||||||
|
'todo-sync/revs/me',
|
||||||
|
]);
|
||||||
|
remote.writes.clear();
|
||||||
|
|
||||||
|
final second = await SyncService(stateStore: store).sync(repo, remote);
|
||||||
|
|
||||||
|
expect(second.pushed, isFalse);
|
||||||
|
expect(remote.writes, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('still syncs on a backend without a bulk-map read', () async {
|
||||||
|
// GitHub has no cheap revision map; correctness must not depend on the
|
||||||
|
// optimisation being available.
|
||||||
|
final peerLog = logToJson(await buildPeerLog());
|
||||||
|
final remote = FakeRemoteWithoutBulkRead({
|
||||||
|
'todo-sync/notes/phone.json': peerLog,
|
||||||
|
});
|
||||||
|
|
||||||
|
final result = await SyncService(
|
||||||
|
stateStore: InMemorySyncStateStore(),
|
||||||
|
).sync(repo, remote);
|
||||||
|
|
||||||
|
expect(result.mergedDevices, 1);
|
||||||
|
expect(remote.reads, contains('todo-sync/notes/phone.json'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -8,72 +8,27 @@ import 'package:todo/data/note.dart';
|
|||||||
import 'package:todo/data/note_repository.dart';
|
import 'package:todo/data/note_repository.dart';
|
||||||
import 'package:todo/sync/sync_service.dart';
|
import 'package:todo/sync/sync_service.dart';
|
||||||
|
|
||||||
http.Response _response(int statusCode, [Object? jsonBody]) =>
|
import 'sync_service_fakes.dart';
|
||||||
http.Response(jsonEncode(jsonBody ?? {}), statusCode);
|
|
||||||
|
|
||||||
http.Response _fileWith(String text, {String? sha}) =>
|
|
||||||
_response(200, {'content': base64.encode(utf8.encode(text)), 'sha': ?sha});
|
|
||||||
|
|
||||||
class _PutCall {
|
|
||||||
_PutCall(this.path, this.body);
|
|
||||||
final String path;
|
|
||||||
final Map<String, dynamic> body;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mock GitHub Contents API router matching crdt_sync's client: GET
|
|
||||||
/// `.../contents/<key>` returns [contentResponses]`[key]` (404 if absent), the
|
|
||||||
/// bare repo-existence GET always succeeds, and every PUT is recorded.
|
|
||||||
({http.Client httpClient, List<_PutCall> putCalls}) _mockGitHub({
|
|
||||||
Map<String, http.Response> contentResponses = const {},
|
|
||||||
}) {
|
|
||||||
final putCalls = <_PutCall>[];
|
|
||||||
final client = http_testing.MockClient((request) async {
|
|
||||||
final path = request.url.path;
|
|
||||||
if (!path.contains('/contents/')) return _response(200); // repo-exists
|
|
||||||
final key = path.split('/contents/').last;
|
|
||||||
if (request.method == 'PUT') {
|
|
||||||
putCalls.add(
|
|
||||||
_PutCall(key, jsonDecode(request.body) as Map<String, dynamic>),
|
|
||||||
);
|
|
||||||
return _response(200);
|
|
||||||
}
|
|
||||||
return contentResponses[key] ?? _response(404);
|
|
||||||
});
|
|
||||||
return (httpClient: client, putCalls: putCalls);
|
|
||||||
}
|
|
||||||
|
|
||||||
GitHubClient _github(http.Client mock) =>
|
|
||||||
GitHubClient(owner: 'o', repo: 'r', token: 't', httpClient: mock);
|
|
||||||
|
|
||||||
Note _note(String id, String text) => Note(
|
|
||||||
id: id,
|
|
||||||
text: text,
|
|
||||||
priority: Priority.medium,
|
|
||||||
status: Status.todo,
|
|
||||||
createdAt: DateTime(2026, 6, 15),
|
|
||||||
updatedAt: DateTime(2026, 6, 15),
|
|
||||||
);
|
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
_revisionTrackingTests();
|
|
||||||
test('pulls and merges another device, then pushes its own', () async {
|
test('pulls and merges another device, then pushes its own', () async {
|
||||||
final other = await NoteRepository.openInMemory(nodeId: 'otherNode');
|
final other = await NoteRepository.openInMemory(nodeId: 'otherNode');
|
||||||
await other.upsert(_note('x', 'from other device'));
|
await other.upsert(note('x', 'from other device'));
|
||||||
final otherLog = logToJson(other.exportLog());
|
final otherLog = logToJson(other.exportLog());
|
||||||
await other.close();
|
await other.close();
|
||||||
|
|
||||||
final (:httpClient, :putCalls) = _mockGitHub(
|
final (:httpClient, :putCalls) = mockGitHub(
|
||||||
contentResponses: {
|
contentResponses: {
|
||||||
'todo-sync/notes': _response(200, [
|
'todo-sync/notes': response(200, [
|
||||||
{'name': 'otherNode.json'},
|
{'name': 'otherNode.json'},
|
||||||
]),
|
]),
|
||||||
'todo-sync/notes/otherNode.json': _fileWith(otherLog),
|
'todo-sync/notes/otherNode.json': fileWith(otherLog),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
final local = await NoteRepository.openInMemory(nodeId: 'localNode');
|
final local = await NoteRepository.openInMemory(nodeId: 'localNode');
|
||||||
addTearDown(local.close);
|
addTearDown(local.close);
|
||||||
|
|
||||||
final result = await const SyncService().sync(local, _github(httpClient));
|
final result = await const SyncService().sync(local, github(httpClient));
|
||||||
|
|
||||||
expect(result.mergedDevices, 1);
|
expect(result.mergedDevices, 1);
|
||||||
expect(result.pushed, isTrue);
|
expect(result.pushed, isTrue);
|
||||||
@ -105,49 +60,49 @@ void main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('with no remote files, still pushes its own log', () async {
|
test('with no remote files, still pushes its own log', () async {
|
||||||
final (:httpClient, :putCalls) = _mockGitHub(
|
final (:httpClient, :putCalls) = mockGitHub(
|
||||||
contentResponses: {'todo-sync/notes': _response(200, <Object>[])},
|
contentResponses: {'todo-sync/notes': response(200, <Object>[])},
|
||||||
);
|
);
|
||||||
final local = await NoteRepository.openInMemory(nodeId: 'localNode');
|
final local = await NoteRepository.openInMemory(nodeId: 'localNode');
|
||||||
addTearDown(local.close);
|
addTearDown(local.close);
|
||||||
|
|
||||||
final result = await const SyncService().sync(local, _github(httpClient));
|
final result = await const SyncService().sync(local, github(httpClient));
|
||||||
expect(result.mergedDevices, 0);
|
expect(result.mergedDevices, 0);
|
||||||
expect(putCalls, hasLength(1));
|
expect(putCalls, hasLength(1));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('updates its own already-present file using its resolved sha', () async {
|
test('updates its own already-present file using its resolved sha', () async {
|
||||||
final (:httpClient, :putCalls) = _mockGitHub(
|
final (:httpClient, :putCalls) = mockGitHub(
|
||||||
contentResponses: {
|
contentResponses: {
|
||||||
'todo-sync/notes': _response(200, [
|
'todo-sync/notes': response(200, [
|
||||||
{'name': 'localNode.json'},
|
{'name': 'localNode.json'},
|
||||||
]),
|
]),
|
||||||
'todo-sync/notes/localNode.json': _fileWith('{}', sha: 'own-sha-123'),
|
'todo-sync/notes/localNode.json': fileWith('{}', sha: 'own-sha-123'),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
final local = await NoteRepository.openInMemory(nodeId: 'localNode');
|
final local = await NoteRepository.openInMemory(nodeId: 'localNode');
|
||||||
addTearDown(local.close);
|
addTearDown(local.close);
|
||||||
|
|
||||||
final result = await const SyncService().sync(local, _github(httpClient));
|
final result = await const SyncService().sync(local, github(httpClient));
|
||||||
expect(result.mergedDevices, 0); // own file is not a peer to merge
|
expect(result.mergedDevices, 0); // own file is not a peer to merge
|
||||||
expect(putCalls.single.body['sha'], 'own-sha-123'); // put reused the sha
|
expect(putCalls.single.body['sha'], 'own-sha-123'); // put reused the sha
|
||||||
});
|
});
|
||||||
|
|
||||||
test('a corrupt or wrong-shape peer file is skipped, not fatal', () async {
|
test('a corrupt or wrong-shape peer file is skipped, not fatal', () async {
|
||||||
final (:httpClient, :putCalls) = _mockGitHub(
|
final (:httpClient, :putCalls) = mockGitHub(
|
||||||
contentResponses: {
|
contentResponses: {
|
||||||
'todo-sync/notes': _response(200, [
|
'todo-sync/notes': response(200, [
|
||||||
{'name': 'bad1.json'},
|
{'name': 'bad1.json'},
|
||||||
{'name': 'bad2.json'},
|
{'name': 'bad2.json'},
|
||||||
]),
|
]),
|
||||||
'todo-sync/notes/bad1.json': _fileWith('{not json'),
|
'todo-sync/notes/bad1.json': fileWith('{not json'),
|
||||||
'todo-sync/notes/bad2.json': _fileWith('[]'),
|
'todo-sync/notes/bad2.json': fileWith('[]'),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
final local = await NoteRepository.openInMemory(nodeId: 'localNode');
|
final local = await NoteRepository.openInMemory(nodeId: 'localNode');
|
||||||
addTearDown(local.close);
|
addTearDown(local.close);
|
||||||
|
|
||||||
final result = await const SyncService().sync(local, _github(httpClient));
|
final result = await const SyncService().sync(local, github(httpClient));
|
||||||
expect(result.mergedDevices, 0); // both bad files skipped
|
expect(result.mergedDevices, 0); // both bad files skipped
|
||||||
expect(putCalls, hasLength(1));
|
expect(putCalls, hasLength(1));
|
||||||
// The skips are reported, not silent: that's how a peer device dropping
|
// The skips are reported, not silent: that's how a peer device dropping
|
||||||
@ -159,9 +114,9 @@ void main() {
|
|||||||
test('a listed-but-unfetchable peer file is reported as skipped', () async {
|
test('a listed-but-unfetchable peer file is reported as skipped', () async {
|
||||||
// The file appears in the directory listing but its GET 404s (deleted
|
// The file appears in the directory listing but its GET 404s (deleted
|
||||||
// between list and fetch, or contents unavailable).
|
// between list and fetch, or contents unavailable).
|
||||||
final (:httpClient, :putCalls) = _mockGitHub(
|
final (:httpClient, :putCalls) = mockGitHub(
|
||||||
contentResponses: {
|
contentResponses: {
|
||||||
'todo-sync/notes': _response(200, [
|
'todo-sync/notes': response(200, [
|
||||||
{'name': 'gone.json'},
|
{'name': 'gone.json'},
|
||||||
]),
|
]),
|
||||||
},
|
},
|
||||||
@ -169,188 +124,9 @@ void main() {
|
|||||||
final local = await NoteRepository.openInMemory(nodeId: 'localNode');
|
final local = await NoteRepository.openInMemory(nodeId: 'localNode');
|
||||||
addTearDown(local.close);
|
addTearDown(local.close);
|
||||||
|
|
||||||
final result = await const SyncService().sync(local, _github(httpClient));
|
final result = await const SyncService().sync(local, github(httpClient));
|
||||||
expect(result.mergedDevices, 0);
|
expect(result.mergedDevices, 0);
|
||||||
expect(result.skippedFiles, ['gone.json']);
|
expect(result.skippedFiles, ['gone.json']);
|
||||||
expect(putCalls, hasLength(1)); // the push still happened
|
expect(putCalls, hasLength(1)); // the push still happened
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An in-memory [RemoteStore] that also serves revision maps in one read,
|
|
||||||
/// standing in for Firebase. Counts reads so tests can assert on *traffic*
|
|
||||||
/// rather than on the merge result.
|
|
||||||
class _FakeRemote implements RemoteStore, BulkMapReader {
|
|
||||||
_FakeRemote(this.files);
|
|
||||||
|
|
||||||
final Map<String, String> files;
|
|
||||||
final List<String> reads = [];
|
|
||||||
final List<String> writes = [];
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<List<String>> listDirectory(String path) async => files.keys
|
|
||||||
.where((k) => k.startsWith('$path/'))
|
|
||||||
.map((k) => k.substring(path.length + 1).split('/').first)
|
|
||||||
.toSet()
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<String?> getFileText(String path) async {
|
|
||||||
reads.add(path);
|
|
||||||
return files[path];
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> putFileText(
|
|
||||||
String path,
|
|
||||||
String text, {
|
|
||||||
required String message,
|
|
||||||
}) async {
|
|
||||||
writes.add(path);
|
|
||||||
files[path] = text;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<Map<String, String>> getStringMap(String path) async => {
|
|
||||||
for (final e in files.entries)
|
|
||||||
if (e.key.startsWith('$path/')) e.key.substring(path.length + 1): e.value,
|
|
||||||
};
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> deleteFile(String path, {String message = ''}) async =>
|
|
||||||
files.remove(path);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<bool> canAccessRemote() async => true;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void close() {}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A [RemoteStore] with no bulk-map read, standing in for GitHub.
|
|
||||||
///
|
|
||||||
/// Delegates rather than extends: a subclass of [_FakeRemote] would inherit
|
|
||||||
/// `BulkMapReader`, the very capability this fake exists to lack.
|
|
||||||
class _FakeRemoteWithoutBulkRead implements RemoteStore {
|
|
||||||
_FakeRemoteWithoutBulkRead(Map<String, String> files)
|
|
||||||
: _inner = _FakeRemote(files);
|
|
||||||
|
|
||||||
final _FakeRemote _inner;
|
|
||||||
|
|
||||||
List<String> get reads => _inner.reads;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<List<String>> listDirectory(String path) => _inner.listDirectory(path);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<String?> getFileText(String path) => _inner.getFileText(path);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> putFileText(
|
|
||||||
String path,
|
|
||||||
String text, {
|
|
||||||
required String message,
|
|
||||||
}) => _inner.putFileText(path, text, message: message);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> deleteFile(String path, {String message = ''}) =>
|
|
||||||
_inner.deleteFile(path, message: message);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<bool> canAccessRemote() => _inner.canAccessRemote();
|
|
||||||
|
|
||||||
@override
|
|
||||||
void close() => _inner.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _revisionTrackingTests() {
|
|
||||||
group('revision tracking', () {
|
|
||||||
late NoteRepository repo;
|
|
||||||
|
|
||||||
setUp(() async {
|
|
||||||
repo = await NoteRepository.openInMemory(nodeId: 'me');
|
|
||||||
});
|
|
||||||
|
|
||||||
tearDown(() async => repo.close());
|
|
||||||
|
|
||||||
test('skips a peer whose revision has not changed', () async {
|
|
||||||
// The saving the free-tier budget depends on: an unchanged ~150 KB peer
|
|
||||||
// log must not be downloaded again.
|
|
||||||
final peerLog = logToJson(await _peerLog());
|
|
||||||
final remote = _FakeRemote({
|
|
||||||
'todo-sync/notes/phone.json': peerLog,
|
|
||||||
'todo-sync/revs/phone': revisionOf(peerLog),
|
|
||||||
});
|
|
||||||
final store = InMemorySyncStateStore();
|
|
||||||
|
|
||||||
await SyncService(stateStore: store).sync(repo, remote);
|
|
||||||
remote.reads.clear();
|
|
||||||
final second = await SyncService(stateStore: store).sync(repo, remote);
|
|
||||||
|
|
||||||
expect(remote.reads, isNot(contains('todo-sync/notes/phone.json')));
|
|
||||||
expect(second.skippedUnchanged, 1);
|
|
||||||
expect(second.mergedDevices, 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('downloads again once the peer publishes a new revision', () async {
|
|
||||||
final first = logToJson(await _peerLog());
|
|
||||||
final remote = _FakeRemote({
|
|
||||||
'todo-sync/notes/phone.json': first,
|
|
||||||
'todo-sync/revs/phone': revisionOf(first),
|
|
||||||
});
|
|
||||||
final store = InMemorySyncStateStore();
|
|
||||||
await SyncService(stateStore: store).sync(repo, remote);
|
|
||||||
remote.reads.clear();
|
|
||||||
|
|
||||||
final changed = logToJson(await _peerLog(title: 'changed'));
|
|
||||||
remote.files['todo-sync/notes/phone.json'] = changed;
|
|
||||||
remote.files['todo-sync/revs/phone'] = revisionOf(changed);
|
|
||||||
final second = await SyncService(stateStore: store).sync(repo, remote);
|
|
||||||
|
|
||||||
expect(remote.reads, contains('todo-sync/notes/phone.json'));
|
|
||||||
expect(second.mergedDevices, 1);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('suppresses an unchanged push and publishes a revision', () async {
|
|
||||||
final remote = _FakeRemote({});
|
|
||||||
final store = InMemorySyncStateStore();
|
|
||||||
|
|
||||||
final first = await SyncService(stateStore: store).sync(repo, remote);
|
|
||||||
expect(first.pushed, isTrue);
|
|
||||||
expect(remote.writes, [
|
|
||||||
'todo-sync/notes/me.json',
|
|
||||||
'todo-sync/revs/me',
|
|
||||||
]);
|
|
||||||
remote.writes.clear();
|
|
||||||
|
|
||||||
final second = await SyncService(stateStore: store).sync(repo, remote);
|
|
||||||
|
|
||||||
expect(second.pushed, isFalse);
|
|
||||||
expect(remote.writes, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('still syncs on a backend without a bulk-map read', () async {
|
|
||||||
// GitHub has no cheap revision map; correctness must not depend on the
|
|
||||||
// optimisation being available.
|
|
||||||
final peerLog = logToJson(await _peerLog());
|
|
||||||
final remote = _FakeRemoteWithoutBulkRead({
|
|
||||||
'todo-sync/notes/phone.json': peerLog,
|
|
||||||
});
|
|
||||||
|
|
||||||
final result = await SyncService(
|
|
||||||
stateStore: InMemorySyncStateStore(),
|
|
||||||
).sync(repo, remote);
|
|
||||||
|
|
||||||
expect(result.mergedDevices, 1);
|
|
||||||
expect(remote.reads, contains('todo-sync/notes/phone.json'));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds a one-note log as it would arrive from another device.
|
|
||||||
Future<Log> _peerLog({String title = 'from phone'}) async {
|
|
||||||
final peer = await NoteRepository.openInMemory(nodeId: 'phone');
|
|
||||||
await peer.upsert(_note('peer-note', title));
|
|
||||||
final log = peer.exportLog();
|
|
||||||
await peer.close();
|
|
||||||
return log;
|
|
||||||
}
|
|
||||||
|
|||||||
99
test/wrapper_server_harness.dart
Normal file
99
test/wrapper_server_harness.dart
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
/// The temp web root, the served instance, and enabledOrigin.
|
||||||
|
///
|
||||||
|
/// Shared by the files `wrapper_server_test.dart` was split into for the
|
||||||
|
/// 250-line cap. Deliberately NOT named `*_test.dart`: the runner would
|
||||||
|
/// collect it and fail on the missing `main()`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:todo/desktop/wrapper_server.dart';
|
||||||
|
|
||||||
|
/// One test's temp web root and the [WrapperServer] serving it.
|
||||||
|
///
|
||||||
|
/// A class rather than bare `setUp`/`late` globals because [enabledOrigin]
|
||||||
|
/// needs the temp root, and a top-level function cannot close over a `late`
|
||||||
|
/// that `setUp` assigns. [install] wires the lifecycle; each test file calls
|
||||||
|
/// it once at the top of its `main()`.
|
||||||
|
class WrapperHarness {
|
||||||
|
/// Temp directory holding the web root, the state dir, and the configs.
|
||||||
|
late Directory root;
|
||||||
|
|
||||||
|
/// The server under test, listening on an OS-assigned port.
|
||||||
|
late WrapperServer server;
|
||||||
|
|
||||||
|
/// Origin of [server], e.g. `http://localhost:41234`.
|
||||||
|
late String base;
|
||||||
|
|
||||||
|
/// Registers the setUp/tearDown pair that owns this harness.
|
||||||
|
void install() {
|
||||||
|
setUp(() async {
|
||||||
|
root = await Directory.systemTemp.createTemp('wrapper');
|
||||||
|
final webRoot = Directory(p.join(root.path, 'web'))..createSync();
|
||||||
|
File(
|
||||||
|
p.join(webRoot.path, 'index.html'),
|
||||||
|
).writeAsStringSync('<h1>todo</h1>');
|
||||||
|
File(p.join(webRoot.path, 'main.dart.js')).writeAsStringSync('console;');
|
||||||
|
File(p.join(webRoot.path, 'canvaskit.wasm')).writeAsStringSync('binary');
|
||||||
|
|
||||||
|
server = WrapperServer(
|
||||||
|
webRoot: webRoot.path,
|
||||||
|
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
||||||
|
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
||||||
|
// Without this, the default falls back to the real
|
||||||
|
// $HOME/.config/todo/firebase_auth.json -- on a machine that has
|
||||||
|
// actually signed in (a real desktop session), that file exists, so
|
||||||
|
// the "no credentials file exists" test below observes 200 instead
|
||||||
|
// of 404. Point it at this test's own throwaway root instead.
|
||||||
|
todoCredentialsPath: p.join(
|
||||||
|
root.path,
|
||||||
|
'todo-config',
|
||||||
|
'firebase_auth.json',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
// Port 0 lets the OS pick, so tests never collide with a running app.
|
||||||
|
await server.start(0);
|
||||||
|
base = 'http://localhost:${server.port}';
|
||||||
|
});
|
||||||
|
|
||||||
|
tearDown(() async {
|
||||||
|
await server.stop();
|
||||||
|
root.deleteSync(recursive: true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String> enabledOrigin(
|
||||||
|
Map<String, String> files, {
|
||||||
|
String? credentialsJson,
|
||||||
|
}) async {
|
||||||
|
final configDir = Directory(p.join(root.path, 'crdt-sync'))
|
||||||
|
..createSync(recursive: true);
|
||||||
|
files.forEach((name, contents) {
|
||||||
|
File(p.join(configDir.path, name)).writeAsStringSync(contents);
|
||||||
|
});
|
||||||
|
String? credentialsPath;
|
||||||
|
if (credentialsJson != null) {
|
||||||
|
final credentialsDir = Directory(p.join(root.path, 'todo-config'))
|
||||||
|
..createSync(recursive: true);
|
||||||
|
credentialsPath = p.join(credentialsDir.path, 'firebase_auth.json');
|
||||||
|
File(credentialsPath).writeAsStringSync(credentialsJson);
|
||||||
|
}
|
||||||
|
final enabled = WrapperServer(
|
||||||
|
webRoot: p.join(root.path, 'web'),
|
||||||
|
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
||||||
|
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
||||||
|
serveSyncAccount: true,
|
||||||
|
syncConfigDir: configDir.path,
|
||||||
|
todoCredentialsPath:
|
||||||
|
credentialsPath ?? p.join(root.path, 'todo-config', 'absent.json'),
|
||||||
|
);
|
||||||
|
await enabled.start(0);
|
||||||
|
addTearDown(enabled.stop);
|
||||||
|
return 'http://localhost:${enabled.port}';
|
||||||
|
}
|
||||||
|
}
|
||||||
221
test/wrapper_server_provisioning_test.dart
Normal file
221
test/wrapper_server_provisioning_test.dart
Normal file
@ -0,0 +1,221 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:todo/desktop/wrapper_server.dart';
|
||||||
|
|
||||||
|
import 'wrapper_server_harness.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
final h = WrapperHarness()..install();
|
||||||
|
|
||||||
|
group('sync-account provisioning', () {
|
||||||
|
test('is 404 when not enabled', () async {
|
||||||
|
// The default, and the whole security posture: a credential route must
|
||||||
|
// not be reachable just because the app is running.
|
||||||
|
final response = await http.get(Uri.parse('${h.base}$kSyncAccountPath'));
|
||||||
|
|
||||||
|
expect(response.statusCode, HttpStatus.notFound);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('serves the account when enabled', () async {
|
||||||
|
final origin = await h.enabledOrigin({
|
||||||
|
'firebase.json': '{"email":"a@b.c"}',
|
||||||
|
'password': 'pw\n',
|
||||||
|
});
|
||||||
|
|
||||||
|
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
||||||
|
final account = FirebaseAccount.tryParse(response.body);
|
||||||
|
|
||||||
|
expect(response.statusCode, HttpStatus.ok);
|
||||||
|
expect(account?.email, 'a@b.c');
|
||||||
|
expect(account?.password, 'pw');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is 404 when the config files are absent', () async {
|
||||||
|
final origin = await h.enabledOrigin({});
|
||||||
|
|
||||||
|
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
||||||
|
|
||||||
|
expect(response.statusCode, HttpStatus.notFound);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is 404 when firebase.json has no usable email', () async {
|
||||||
|
final origin = await h.enabledOrigin({
|
||||||
|
'firebase.json': '{"apiKey":"x"}',
|
||||||
|
'password': 'pw',
|
||||||
|
});
|
||||||
|
|
||||||
|
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
||||||
|
|
||||||
|
expect(response.statusCode, HttpStatus.notFound);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('sync-credentials provisioning', () {
|
||||||
|
// Unlike /sync-account, this route needs no CRDT_SYNC_SERVE_ACCOUNT: a
|
||||||
|
// normal launch must self-provision with nothing to remember. [h.base]'s
|
||||||
|
// h.server was built with no credentials file at the default path, so this
|
||||||
|
// exercises the file-absent 404, not a disabled-route 404 -- there is no
|
||||||
|
// "disabled" state for this route anymore.
|
||||||
|
test(
|
||||||
|
'is 404 when no credentials file exists at the default path',
|
||||||
|
() async {
|
||||||
|
final response = await http.get(
|
||||||
|
Uri.parse('${h.base}$kSyncCredentialsPath'),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(response.statusCode, HttpStatus.notFound);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('serves once, then 404s for the rest of the process', () async {
|
||||||
|
final credentialsDir = Directory(p.join(h.root.path, 'todo-config-once'))
|
||||||
|
..createSync(recursive: true);
|
||||||
|
final credentialsPath = p.join(credentialsDir.path, 'firebase_auth.json');
|
||||||
|
File(credentialsPath).writeAsStringSync(
|
||||||
|
jsonEncode({
|
||||||
|
'id_token': 'id',
|
||||||
|
'refresh_token': 'refresh',
|
||||||
|
'expires_at': '2026-01-01T00:00:00.000Z',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
final enabled = WrapperServer(
|
||||||
|
webRoot: p.join(h.root.path, 'web'),
|
||||||
|
backlogPath: p.join(h.root.path, 'todo', 'BACKLOG.md'),
|
||||||
|
logPath: p.join(h.root.path, 'state', 'todo_notes.json'),
|
||||||
|
todoCredentialsPath: credentialsPath,
|
||||||
|
);
|
||||||
|
await enabled.start(0);
|
||||||
|
addTearDown(enabled.stop);
|
||||||
|
final origin = 'http://localhost:${enabled.port}';
|
||||||
|
|
||||||
|
final first = await http.get(Uri.parse('$origin$kSyncCredentialsPath'));
|
||||||
|
final second = await http.get(Uri.parse('$origin$kSyncCredentialsPath'));
|
||||||
|
|
||||||
|
expect(first.statusCode, HttpStatus.ok);
|
||||||
|
expect(second.statusCode, HttpStatus.notFound);
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'serves the seeded credentials, with email from firebase.json',
|
||||||
|
() async {
|
||||||
|
final configDir = Directory(p.join(h.root.path, 'crdt-sync'))
|
||||||
|
..createSync(recursive: true);
|
||||||
|
File(
|
||||||
|
p.join(configDir.path, 'firebase.json'),
|
||||||
|
).writeAsStringSync('{"email":"seeded@example.com"}');
|
||||||
|
final credentialsDir = Directory(p.join(h.root.path, 'todo-config'))
|
||||||
|
..createSync(recursive: true);
|
||||||
|
final credentialsPath = p.join(
|
||||||
|
credentialsDir.path,
|
||||||
|
'firebase_auth.json',
|
||||||
|
);
|
||||||
|
File(credentialsPath).writeAsStringSync(
|
||||||
|
jsonEncode({
|
||||||
|
'id_token': 'id',
|
||||||
|
'refresh_token': 'refresh',
|
||||||
|
'expires_at': '2026-01-01T00:00:00.000Z',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
final enabled = WrapperServer(
|
||||||
|
webRoot: p.join(h.root.path, 'web'),
|
||||||
|
backlogPath: p.join(h.root.path, 'todo', 'BACKLOG.md'),
|
||||||
|
logPath: p.join(h.root.path, 'state', 'todo_notes.json'),
|
||||||
|
serveSyncAccount: true,
|
||||||
|
syncConfigDir: configDir.path,
|
||||||
|
todoCredentialsPath: credentialsPath,
|
||||||
|
);
|
||||||
|
await enabled.start(0);
|
||||||
|
addTearDown(enabled.stop);
|
||||||
|
|
||||||
|
final response = await http.get(
|
||||||
|
Uri.parse('http://localhost:${enabled.port}$kSyncCredentialsPath'),
|
||||||
|
);
|
||||||
|
final body = jsonDecode(response.body) as Map<String, dynamic>;
|
||||||
|
|
||||||
|
expect(response.statusCode, HttpStatus.ok);
|
||||||
|
expect(body['id_token'], 'id');
|
||||||
|
expect(body['refresh_token'], 'refresh');
|
||||||
|
expect(body['expires_at'], '2026-01-01T00:00:00.000Z');
|
||||||
|
expect(body['email'], 'seeded@example.com');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test(
|
||||||
|
'serves credentials with a null email when firebase.json is absent',
|
||||||
|
() async {
|
||||||
|
final credentialsDir = Directory(p.join(h.root.path, 'todo-config-2'))
|
||||||
|
..createSync(recursive: true);
|
||||||
|
final credentialsPath = p.join(
|
||||||
|
credentialsDir.path,
|
||||||
|
'firebase_auth.json',
|
||||||
|
);
|
||||||
|
File(credentialsPath).writeAsStringSync(
|
||||||
|
jsonEncode({
|
||||||
|
'id_token': 'id',
|
||||||
|
'refresh_token': 'refresh',
|
||||||
|
'expires_at': '2026-01-01T00:00:00.000Z',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
final enabled = WrapperServer(
|
||||||
|
webRoot: p.join(h.root.path, 'web'),
|
||||||
|
backlogPath: p.join(h.root.path, 'todo', 'BACKLOG.md'),
|
||||||
|
logPath: p.join(h.root.path, 'state', 'todo_notes.json'),
|
||||||
|
serveSyncAccount: true,
|
||||||
|
syncConfigDir: p.join(h.root.path, 'crdt-sync-absent'),
|
||||||
|
todoCredentialsPath: credentialsPath,
|
||||||
|
);
|
||||||
|
await enabled.start(0);
|
||||||
|
addTearDown(enabled.stop);
|
||||||
|
|
||||||
|
final response = await http.get(
|
||||||
|
Uri.parse('http://localhost:${enabled.port}$kSyncCredentialsPath'),
|
||||||
|
);
|
||||||
|
final body = jsonDecode(response.body) as Map<String, dynamic>;
|
||||||
|
|
||||||
|
expect(response.statusCode, HttpStatus.ok);
|
||||||
|
expect(body['email'], isNull);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('is 404 when the credentials file is absent', () async {
|
||||||
|
final origin = await h.enabledOrigin({});
|
||||||
|
|
||||||
|
final response = await http.get(
|
||||||
|
Uri.parse('$origin$kSyncCredentialsPath'),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(response.statusCode, HttpStatus.notFound);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is 404 when the credentials file is not valid JSON', () async {
|
||||||
|
final origin = await h.enabledOrigin({}, credentialsJson: 'not json');
|
||||||
|
|
||||||
|
final response = await http.get(
|
||||||
|
Uri.parse('$origin$kSyncCredentialsPath'),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(response.statusCode, HttpStatus.notFound);
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'is 404 when the credentials file is missing required fields',
|
||||||
|
() async {
|
||||||
|
final origin = await h.enabledOrigin(
|
||||||
|
{},
|
||||||
|
credentialsJson: jsonEncode({'id_token': 'id'}),
|
||||||
|
);
|
||||||
|
|
||||||
|
final response = await http.get(
|
||||||
|
Uri.parse('$origin$kSyncCredentialsPath'),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(response.statusCode, HttpStatus.notFound);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
134
test/wrapper_server_static_test.dart
Normal file
134
test/wrapper_server_static_test.dart
Normal file
@ -0,0 +1,134 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:todo/desktop/wrapper_server.dart';
|
||||||
|
|
||||||
|
import 'wrapper_server_harness.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
final h = WrapperHarness()..install();
|
||||||
|
|
||||||
|
test('serves index.html at the root', () async {
|
||||||
|
final response = await http.get(Uri.parse('${h.base}/'));
|
||||||
|
expect(response.statusCode, 200);
|
||||||
|
expect(response.body, contains('todo'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('serves nested assets and 404s unknown paths', () async {
|
||||||
|
expect(
|
||||||
|
(await http.get(Uri.parse('${h.base}/main.dart.js'))).statusCode,
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
expect((await http.get(Uri.parse('${h.base}/nope.js'))).statusCode, 404);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('refuses to serve outside the web root', () async {
|
||||||
|
// The served directory sits beside the user's files, so traversal must not
|
||||||
|
// be able to read them. Sent over a raw socket because http.get normalises
|
||||||
|
// `..` away client-side, so the server would never see the attack.
|
||||||
|
File(p.join(h.root.path, 'secret')).writeAsStringSync('do not serve me');
|
||||||
|
|
||||||
|
// Percent-encoded, because both the http client and Dart's HttpServer
|
||||||
|
// collapse a literal `..` before any handler sees it; `%2e%2e` survives
|
||||||
|
// that and is decoded into the path afterwards.
|
||||||
|
final socket = await Socket.connect('localhost', h.server.port);
|
||||||
|
socket.write('GET /%2e%2e/secret HTTP/1.1\r\nHost: localhost\r\n\r\n');
|
||||||
|
await socket.flush();
|
||||||
|
final response = await utf8.decoder.bind(socket).first;
|
||||||
|
await socket.close();
|
||||||
|
|
||||||
|
// Dart's HttpServer decodes and then normalises, so traversal is already
|
||||||
|
// collapsed before any handler runs and this comes back 404 rather than
|
||||||
|
// 403. What matters is the property, not which code rejected it: the file
|
||||||
|
// outside the web h.root is never served.
|
||||||
|
expect(response, isNot(contains('do not serve me')));
|
||||||
|
expect(response, anyOf(contains('403'), contains('404')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failing write reports a server error rather than crashing', () async {
|
||||||
|
// Parent path is a regular file, so creating the directory for the backup
|
||||||
|
// throws. The serve loop must survive it and keep answering requests.
|
||||||
|
final blocked = Directory(p.join(h.root.path, 'blocked'))..createSync();
|
||||||
|
File(p.join(blocked.path, 'wall')).writeAsStringSync('');
|
||||||
|
final wedged = WrapperServer(
|
||||||
|
webRoot: p.join(h.root.path, 'web'),
|
||||||
|
backlogPath: p.join(blocked.path, 'wall', 'nested', 'BACKLOG.md'),
|
||||||
|
logPath: p.join(h.root.path, 'state', 'todo_notes.json'),
|
||||||
|
);
|
||||||
|
await wedged.start(0);
|
||||||
|
addTearDown(wedged.stop);
|
||||||
|
|
||||||
|
final response = await http.post(
|
||||||
|
Uri.parse('http://localhost:${wedged.port}/backup/backlog'),
|
||||||
|
body: 'x',
|
||||||
|
);
|
||||||
|
expect(response.statusCode, 500);
|
||||||
|
|
||||||
|
// Still alive afterwards.
|
||||||
|
final after = await http.get(
|
||||||
|
Uri.parse('http://localhost:${wedged.port}/'),
|
||||||
|
);
|
||||||
|
expect(after.statusCode, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST then GET round-trips the backlog', () async {
|
||||||
|
final posted = await http.post(
|
||||||
|
Uri.parse('${h.base}/backup/backlog'),
|
||||||
|
body: '# backlog\n\nnote one\n',
|
||||||
|
);
|
||||||
|
expect(posted.statusCode, 204);
|
||||||
|
|
||||||
|
// Written to the real path, which is what the user's tooling reads.
|
||||||
|
final onDisk = File(p.join(h.root.path, 'todo', 'BACKLOG.md'));
|
||||||
|
expect(onDisk.existsSync(), isTrue);
|
||||||
|
expect(onDisk.readAsStringSync(), contains('note one'));
|
||||||
|
|
||||||
|
final fetched = await http.get(Uri.parse('${h.base}/backup/backlog'));
|
||||||
|
expect(fetched.statusCode, 200);
|
||||||
|
expect(fetched.body, contains('note one'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST then GET round-trips the note log', () async {
|
||||||
|
await http.post(Uri.parse('${h.base}/backup/log'), body: '{"a":1}');
|
||||||
|
final fetched = await http.get(Uri.parse('${h.base}/backup/log'));
|
||||||
|
expect(fetched.body, '{"a":1}');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET on a backup that does not exist yet 404s', () async {
|
||||||
|
expect((await http.get(Uri.parse('${h.base}/backup/log'))).statusCode, 404);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects unsupported methods on a backup path', () async {
|
||||||
|
final response = await http.delete(Uri.parse('${h.base}/backup/log'));
|
||||||
|
expect(response.statusCode, 405);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('labels wasm and js correctly', () async {
|
||||||
|
// CanvasKit refuses a .wasm served as anything else, and the app then
|
||||||
|
// renders nothing at all.
|
||||||
|
final wasm = await http.get(Uri.parse('${h.base}/canvaskit.wasm'));
|
||||||
|
expect(wasm.headers['content-type'], contains('application/wasm'));
|
||||||
|
final js = await http.get(Uri.parse('${h.base}/main.dart.js'));
|
||||||
|
expect(js.headers['content-type'], contains('javascript'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('contentTypeFor covers the asset kinds the build emits', () {
|
||||||
|
String kind(String name) => WrapperServer.contentTypeFor(name).mimeType;
|
||||||
|
|
||||||
|
expect(kind('a.html'), 'text/html');
|
||||||
|
expect(kind('a.json'), 'application/json');
|
||||||
|
expect(kind('a.css'), 'text/css');
|
||||||
|
expect(kind('a.png'), 'image/png');
|
||||||
|
expect(kind('a.svg'), 'image/svg+xml');
|
||||||
|
expect(kind('a.ttf'), 'font/ttf');
|
||||||
|
expect(kind('a.otf'), 'font/otf');
|
||||||
|
expect(kind('a.woff2'), 'font/woff2');
|
||||||
|
expect(kind('a.mjs'), 'text/javascript');
|
||||||
|
expect(kind('a.bin'), 'application/octet-stream');
|
||||||
|
expect(kind('a.unknown'), 'application/octet-stream');
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -1,402 +0,0 @@
|
|||||||
import 'dart:convert';
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
import 'package:todo/desktop/wrapper_server.dart';
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
late Directory root;
|
|
||||||
late WrapperServer server;
|
|
||||||
late String base;
|
|
||||||
|
|
||||||
setUp(() async {
|
|
||||||
root = await Directory.systemTemp.createTemp('wrapper');
|
|
||||||
final webRoot = Directory(p.join(root.path, 'web'))..createSync();
|
|
||||||
File(p.join(webRoot.path, 'index.html')).writeAsStringSync('<h1>todo</h1>');
|
|
||||||
File(p.join(webRoot.path, 'main.dart.js')).writeAsStringSync('console;');
|
|
||||||
File(p.join(webRoot.path, 'canvaskit.wasm')).writeAsStringSync('binary');
|
|
||||||
|
|
||||||
server = WrapperServer(
|
|
||||||
webRoot: webRoot.path,
|
|
||||||
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
|
||||||
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
|
||||||
// Without this, the default falls back to the real
|
|
||||||
// $HOME/.config/todo/firebase_auth.json -- on a machine that has
|
|
||||||
// actually signed in (a real desktop session), that file exists, so
|
|
||||||
// the "no credentials file exists" test below observes 200 instead
|
|
||||||
// of 404. Point it at this test's own throwaway root instead.
|
|
||||||
todoCredentialsPath: p.join(
|
|
||||||
root.path,
|
|
||||||
'todo-config',
|
|
||||||
'firebase_auth.json',
|
|
||||||
),
|
|
||||||
);
|
|
||||||
// Port 0 lets the OS pick, so tests never collide with a running app.
|
|
||||||
await server.start(0);
|
|
||||||
base = 'http://localhost:${server.port}';
|
|
||||||
});
|
|
||||||
|
|
||||||
tearDown(() async {
|
|
||||||
await server.stop();
|
|
||||||
root.deleteSync(recursive: true);
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Starts a second server with provisioning enabled against [files], and
|
|
||||||
/// optionally a `todo`-specific credentials file at [credentialsJson].
|
|
||||||
Future<String> enabledOrigin(
|
|
||||||
Map<String, String> files, {
|
|
||||||
String? credentialsJson,
|
|
||||||
}) async {
|
|
||||||
final configDir = Directory(p.join(root.path, 'crdt-sync'))
|
|
||||||
..createSync(recursive: true);
|
|
||||||
files.forEach((name, contents) {
|
|
||||||
File(p.join(configDir.path, name)).writeAsStringSync(contents);
|
|
||||||
});
|
|
||||||
String? credentialsPath;
|
|
||||||
if (credentialsJson != null) {
|
|
||||||
final credentialsDir = Directory(p.join(root.path, 'todo-config'))
|
|
||||||
..createSync(recursive: true);
|
|
||||||
credentialsPath = p.join(credentialsDir.path, 'firebase_auth.json');
|
|
||||||
File(credentialsPath).writeAsStringSync(credentialsJson);
|
|
||||||
}
|
|
||||||
final enabled = WrapperServer(
|
|
||||||
webRoot: p.join(root.path, 'web'),
|
|
||||||
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
|
||||||
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
|
||||||
serveSyncAccount: true,
|
|
||||||
syncConfigDir: configDir.path,
|
|
||||||
todoCredentialsPath:
|
|
||||||
credentialsPath ?? p.join(root.path, 'todo-config', 'absent.json'),
|
|
||||||
);
|
|
||||||
await enabled.start(0);
|
|
||||||
addTearDown(enabled.stop);
|
|
||||||
return 'http://localhost:${enabled.port}';
|
|
||||||
}
|
|
||||||
|
|
||||||
test('serves index.html at the root', () async {
|
|
||||||
final response = await http.get(Uri.parse('$base/'));
|
|
||||||
expect(response.statusCode, 200);
|
|
||||||
expect(response.body, contains('todo'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('serves nested assets and 404s unknown paths', () async {
|
|
||||||
expect((await http.get(Uri.parse('$base/main.dart.js'))).statusCode, 200);
|
|
||||||
expect((await http.get(Uri.parse('$base/nope.js'))).statusCode, 404);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('refuses to serve outside the web root', () async {
|
|
||||||
// The served directory sits beside the user's files, so traversal must not
|
|
||||||
// be able to read them. Sent over a raw socket because http.get normalises
|
|
||||||
// `..` away client-side, so the server would never see the attack.
|
|
||||||
File(p.join(root.path, 'secret')).writeAsStringSync('do not serve me');
|
|
||||||
|
|
||||||
// Percent-encoded, because both the http client and Dart's HttpServer
|
|
||||||
// collapse a literal `..` before any handler sees it; `%2e%2e` survives
|
|
||||||
// that and is decoded into the path afterwards.
|
|
||||||
final socket = await Socket.connect('localhost', server.port);
|
|
||||||
socket.write('GET /%2e%2e/secret HTTP/1.1\r\nHost: localhost\r\n\r\n');
|
|
||||||
await socket.flush();
|
|
||||||
final response = await utf8.decoder.bind(socket).first;
|
|
||||||
await socket.close();
|
|
||||||
|
|
||||||
// Dart's HttpServer decodes and then normalises, so traversal is already
|
|
||||||
// collapsed before any handler runs and this comes back 404 rather than
|
|
||||||
// 403. What matters is the property, not which code rejected it: the file
|
|
||||||
// outside the web root is never served.
|
|
||||||
expect(response, isNot(contains('do not serve me')));
|
|
||||||
expect(response, anyOf(contains('403'), contains('404')));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a failing write reports a server error rather than crashing', () async {
|
|
||||||
// Parent path is a regular file, so creating the directory for the backup
|
|
||||||
// throws. The serve loop must survive it and keep answering requests.
|
|
||||||
final blocked = Directory(p.join(root.path, 'blocked'))..createSync();
|
|
||||||
File(p.join(blocked.path, 'wall')).writeAsStringSync('');
|
|
||||||
final wedged = WrapperServer(
|
|
||||||
webRoot: p.join(root.path, 'web'),
|
|
||||||
backlogPath: p.join(blocked.path, 'wall', 'nested', 'BACKLOG.md'),
|
|
||||||
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
|
||||||
);
|
|
||||||
await wedged.start(0);
|
|
||||||
addTearDown(wedged.stop);
|
|
||||||
|
|
||||||
final response = await http.post(
|
|
||||||
Uri.parse('http://localhost:${wedged.port}/backup/backlog'),
|
|
||||||
body: 'x',
|
|
||||||
);
|
|
||||||
expect(response.statusCode, 500);
|
|
||||||
|
|
||||||
// Still alive afterwards.
|
|
||||||
final after = await http.get(
|
|
||||||
Uri.parse('http://localhost:${wedged.port}/'),
|
|
||||||
);
|
|
||||||
expect(after.statusCode, 200);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('POST then GET round-trips the backlog', () async {
|
|
||||||
final posted = await http.post(
|
|
||||||
Uri.parse('$base/backup/backlog'),
|
|
||||||
body: '# backlog\n\nnote one\n',
|
|
||||||
);
|
|
||||||
expect(posted.statusCode, 204);
|
|
||||||
|
|
||||||
// Written to the real path, which is what the user's tooling reads.
|
|
||||||
final onDisk = File(p.join(root.path, 'todo', 'BACKLOG.md'));
|
|
||||||
expect(onDisk.existsSync(), isTrue);
|
|
||||||
expect(onDisk.readAsStringSync(), contains('note one'));
|
|
||||||
|
|
||||||
final fetched = await http.get(Uri.parse('$base/backup/backlog'));
|
|
||||||
expect(fetched.statusCode, 200);
|
|
||||||
expect(fetched.body, contains('note one'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('POST then GET round-trips the note log', () async {
|
|
||||||
await http.post(Uri.parse('$base/backup/log'), body: '{"a":1}');
|
|
||||||
final fetched = await http.get(Uri.parse('$base/backup/log'));
|
|
||||||
expect(fetched.body, '{"a":1}');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('GET on a backup that does not exist yet 404s', () async {
|
|
||||||
expect((await http.get(Uri.parse('$base/backup/log'))).statusCode, 404);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('rejects unsupported methods on a backup path', () async {
|
|
||||||
final response = await http.delete(Uri.parse('$base/backup/log'));
|
|
||||||
expect(response.statusCode, 405);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('labels wasm and js correctly', () async {
|
|
||||||
// CanvasKit refuses a .wasm served as anything else, and the app then
|
|
||||||
// renders nothing at all.
|
|
||||||
final wasm = await http.get(Uri.parse('$base/canvaskit.wasm'));
|
|
||||||
expect(wasm.headers['content-type'], contains('application/wasm'));
|
|
||||||
final js = await http.get(Uri.parse('$base/main.dart.js'));
|
|
||||||
expect(js.headers['content-type'], contains('javascript'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('contentTypeFor covers the asset kinds the build emits', () {
|
|
||||||
String kind(String name) => WrapperServer.contentTypeFor(name).mimeType;
|
|
||||||
|
|
||||||
expect(kind('a.html'), 'text/html');
|
|
||||||
expect(kind('a.json'), 'application/json');
|
|
||||||
expect(kind('a.css'), 'text/css');
|
|
||||||
expect(kind('a.png'), 'image/png');
|
|
||||||
expect(kind('a.svg'), 'image/svg+xml');
|
|
||||||
expect(kind('a.ttf'), 'font/ttf');
|
|
||||||
expect(kind('a.otf'), 'font/otf');
|
|
||||||
expect(kind('a.woff2'), 'font/woff2');
|
|
||||||
expect(kind('a.mjs'), 'text/javascript');
|
|
||||||
expect(kind('a.bin'), 'application/octet-stream');
|
|
||||||
expect(kind('a.unknown'), 'application/octet-stream');
|
|
||||||
});
|
|
||||||
|
|
||||||
group('sync-account provisioning', () {
|
|
||||||
test('is 404 when not enabled', () async {
|
|
||||||
// The default, and the whole security posture: a credential route must
|
|
||||||
// not be reachable just because the app is running.
|
|
||||||
final response = await http.get(Uri.parse('$base$kSyncAccountPath'));
|
|
||||||
|
|
||||||
expect(response.statusCode, HttpStatus.notFound);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('serves the account when enabled', () async {
|
|
||||||
final origin = await enabledOrigin({
|
|
||||||
'firebase.json': '{"email":"a@b.c"}',
|
|
||||||
'password': 'pw\n',
|
|
||||||
});
|
|
||||||
|
|
||||||
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
|
||||||
final account = FirebaseAccount.tryParse(response.body);
|
|
||||||
|
|
||||||
expect(response.statusCode, HttpStatus.ok);
|
|
||||||
expect(account?.email, 'a@b.c');
|
|
||||||
expect(account?.password, 'pw');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is 404 when the config files are absent', () async {
|
|
||||||
final origin = await enabledOrigin({});
|
|
||||||
|
|
||||||
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
|
||||||
|
|
||||||
expect(response.statusCode, HttpStatus.notFound);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is 404 when firebase.json has no usable email', () async {
|
|
||||||
final origin = await enabledOrigin({
|
|
||||||
'firebase.json': '{"apiKey":"x"}',
|
|
||||||
'password': 'pw',
|
|
||||||
});
|
|
||||||
|
|
||||||
final response = await http.get(Uri.parse('$origin$kSyncAccountPath'));
|
|
||||||
|
|
||||||
expect(response.statusCode, HttpStatus.notFound);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('sync-credentials provisioning', () {
|
|
||||||
// Unlike /sync-account, this route needs no CRDT_SYNC_SERVE_ACCOUNT: a
|
|
||||||
// normal launch must self-provision with nothing to remember. [base]'s
|
|
||||||
// server was built with no credentials file at the default path, so this
|
|
||||||
// exercises the file-absent 404, not a disabled-route 404 -- there is no
|
|
||||||
// "disabled" state for this route anymore.
|
|
||||||
test(
|
|
||||||
'is 404 when no credentials file exists at the default path',
|
|
||||||
() async {
|
|
||||||
final response = await http.get(
|
|
||||||
Uri.parse('$base$kSyncCredentialsPath'),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(response.statusCode, HttpStatus.notFound);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
test('serves once, then 404s for the rest of the process', () async {
|
|
||||||
final credentialsDir = Directory(p.join(root.path, 'todo-config-once'))
|
|
||||||
..createSync(recursive: true);
|
|
||||||
final credentialsPath = p.join(credentialsDir.path, 'firebase_auth.json');
|
|
||||||
File(credentialsPath).writeAsStringSync(
|
|
||||||
jsonEncode({
|
|
||||||
'id_token': 'id',
|
|
||||||
'refresh_token': 'refresh',
|
|
||||||
'expires_at': '2026-01-01T00:00:00.000Z',
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
final enabled = WrapperServer(
|
|
||||||
webRoot: p.join(root.path, 'web'),
|
|
||||||
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
|
||||||
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
|
||||||
todoCredentialsPath: credentialsPath,
|
|
||||||
);
|
|
||||||
await enabled.start(0);
|
|
||||||
addTearDown(enabled.stop);
|
|
||||||
final origin = 'http://localhost:${enabled.port}';
|
|
||||||
|
|
||||||
final first = await http.get(Uri.parse('$origin$kSyncCredentialsPath'));
|
|
||||||
final second = await http.get(Uri.parse('$origin$kSyncCredentialsPath'));
|
|
||||||
|
|
||||||
expect(first.statusCode, HttpStatus.ok);
|
|
||||||
expect(second.statusCode, HttpStatus.notFound);
|
|
||||||
});
|
|
||||||
|
|
||||||
test(
|
|
||||||
'serves the seeded credentials, with email from firebase.json',
|
|
||||||
() async {
|
|
||||||
final configDir = Directory(p.join(root.path, 'crdt-sync'))
|
|
||||||
..createSync(recursive: true);
|
|
||||||
File(
|
|
||||||
p.join(configDir.path, 'firebase.json'),
|
|
||||||
).writeAsStringSync('{"email":"seeded@example.com"}');
|
|
||||||
final credentialsDir = Directory(p.join(root.path, 'todo-config'))
|
|
||||||
..createSync(recursive: true);
|
|
||||||
final credentialsPath = p.join(
|
|
||||||
credentialsDir.path,
|
|
||||||
'firebase_auth.json',
|
|
||||||
);
|
|
||||||
File(credentialsPath).writeAsStringSync(
|
|
||||||
jsonEncode({
|
|
||||||
'id_token': 'id',
|
|
||||||
'refresh_token': 'refresh',
|
|
||||||
'expires_at': '2026-01-01T00:00:00.000Z',
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
final enabled = WrapperServer(
|
|
||||||
webRoot: p.join(root.path, 'web'),
|
|
||||||
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
|
||||||
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
|
||||||
serveSyncAccount: true,
|
|
||||||
syncConfigDir: configDir.path,
|
|
||||||
todoCredentialsPath: credentialsPath,
|
|
||||||
);
|
|
||||||
await enabled.start(0);
|
|
||||||
addTearDown(enabled.stop);
|
|
||||||
|
|
||||||
final response = await http.get(
|
|
||||||
Uri.parse('http://localhost:${enabled.port}$kSyncCredentialsPath'),
|
|
||||||
);
|
|
||||||
final body = jsonDecode(response.body) as Map<String, dynamic>;
|
|
||||||
|
|
||||||
expect(response.statusCode, HttpStatus.ok);
|
|
||||||
expect(body['id_token'], 'id');
|
|
||||||
expect(body['refresh_token'], 'refresh');
|
|
||||||
expect(body['expires_at'], '2026-01-01T00:00:00.000Z');
|
|
||||||
expect(body['email'], 'seeded@example.com');
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
test(
|
|
||||||
'serves credentials with a null email when firebase.json is absent',
|
|
||||||
() async {
|
|
||||||
final credentialsDir = Directory(p.join(root.path, 'todo-config-2'))
|
|
||||||
..createSync(recursive: true);
|
|
||||||
final credentialsPath = p.join(
|
|
||||||
credentialsDir.path,
|
|
||||||
'firebase_auth.json',
|
|
||||||
);
|
|
||||||
File(credentialsPath).writeAsStringSync(
|
|
||||||
jsonEncode({
|
|
||||||
'id_token': 'id',
|
|
||||||
'refresh_token': 'refresh',
|
|
||||||
'expires_at': '2026-01-01T00:00:00.000Z',
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
final enabled = WrapperServer(
|
|
||||||
webRoot: p.join(root.path, 'web'),
|
|
||||||
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
|
||||||
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
|
||||||
serveSyncAccount: true,
|
|
||||||
syncConfigDir: p.join(root.path, 'crdt-sync-absent'),
|
|
||||||
todoCredentialsPath: credentialsPath,
|
|
||||||
);
|
|
||||||
await enabled.start(0);
|
|
||||||
addTearDown(enabled.stop);
|
|
||||||
|
|
||||||
final response = await http.get(
|
|
||||||
Uri.parse('http://localhost:${enabled.port}$kSyncCredentialsPath'),
|
|
||||||
);
|
|
||||||
final body = jsonDecode(response.body) as Map<String, dynamic>;
|
|
||||||
|
|
||||||
expect(response.statusCode, HttpStatus.ok);
|
|
||||||
expect(body['email'], isNull);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
test('is 404 when the credentials file is absent', () async {
|
|
||||||
final origin = await enabledOrigin({});
|
|
||||||
|
|
||||||
final response = await http.get(
|
|
||||||
Uri.parse('$origin$kSyncCredentialsPath'),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(response.statusCode, HttpStatus.notFound);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is 404 when the credentials file is not valid JSON', () async {
|
|
||||||
final origin = await enabledOrigin({}, credentialsJson: 'not json');
|
|
||||||
|
|
||||||
final response = await http.get(
|
|
||||||
Uri.parse('$origin$kSyncCredentialsPath'),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(response.statusCode, HttpStatus.notFound);
|
|
||||||
});
|
|
||||||
|
|
||||||
test(
|
|
||||||
'is 404 when the credentials file is missing required fields',
|
|
||||||
() async {
|
|
||||||
final origin = await enabledOrigin(
|
|
||||||
{},
|
|
||||||
credentialsJson: jsonEncode({'id_token': 'id'}),
|
|
||||||
);
|
|
||||||
|
|
||||||
final response = await http.get(
|
|
||||||
Uri.parse('$origin$kSyncCredentialsPath'),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(response.statusCode, HttpStatus.notFound);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Loading…
Reference in New Issue
Block a user